]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Circ/CreditCard.pm
Typo
[working/Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Circ / CreditCard.pm
1 # --------------------------------------------------------------------
2 # Copyright (C) 2008 Niles Ingalls 
3 # Niles Ingalls <nilesi@zionsville.lib.in.us>
4 # Bill Erickson <erickson@esilibrary.com>
5 # Joe Atzberger <jatzberger@esilibrary.com>
6 # Lebbeous Fogle-Weekley <lebbeous@esilibrary.com>
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License
10 # as published by the Free Software Foundation; either version 2
11 # of the License, or (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU General Public License for more details.
17 # --------------------------------------------------------------------
18 package OpenILS::Application::Circ::CreditCard;
19 use base qw/OpenSRF::Application/;
20 use strict; use warnings;
21
22 use Business::CreditCard;
23 use Business::OnlinePayment;
24 use Locale::Country;
25
26 use OpenILS::Event;
27 use OpenSRF::Utils::Logger qw/:logger/;
28 use OpenILS::Utils::CStoreEditor qw/:funcs/;
29 use OpenILS::Application::AppUtils;
30 my $U = "OpenILS::Application::AppUtils";
31
32 use constant CREDIT_NS => "credit";
33
34 # Given the argshash from process_payment(), this helper function just finds
35 # a function in the current namespace named "bop_args_{processor}" and calls
36 # it with $argshash as an argument, returning the result, or returning an
37 # empty hash if it can't find such a function.
38 sub get_bop_args_filler {
39     no strict 'refs';
40
41     my $argshash = shift;
42     my $funcname = "bop_args_" . $argshash->{processor};
43     return &{$funcname}($argshash) if defined &{$funcname};
44     return ();
45 }
46
47 # Provide default arguments for calls using the AuthorizeNet processor
48 sub bop_args_AuthorizeNet {
49     my $argshash = shift;
50     if ($argshash->{server}) {
51         return (
52             # One might provide "test.authorize.net" here.
53             Server => $argshash->{server},
54         );
55     }
56     else {
57         return ();
58     }
59 }
60
61 # Provide default arguments for calls using the PayPal processor
62 sub bop_args_PayPal {
63     my $argshash = shift;
64     return (
65         Username => $argshash->{login},
66         Password => $argshash->{password},
67         Signature => $argshash->{signature}
68     );
69 }
70
71 sub get_processor_settings {
72     my $org_unit = shift;
73     my $processor = lc shift;
74
75     +{ map { ($_ =>
76         $U->ou_ancestor_setting_value(
77             $org_unit, CREDIT_NS . ".processor.${processor}.${_}"
78         )) } qw/enabled login password signature server testmode/
79     };
80 }
81
82 #    signature => {
83 #        desc   => 'Process a payment via a supported processor (AuthorizeNet, Paypal)',
84 #        params => [
85 #            { desc => q/Hash of arguments with these keys:
86 #                patron_id: Not a barcode, but a patron's internal ID
87 #                       ou: Org unit where transaction happens
88 #                processor: Payment processor to use (AuthorizeNet, PayPal, etc)
89 #                       cc: credit card number
90 #                     cvv2: 3 or 4 digits from back of card
91 #                   amount: transaction value
92 #                   action: optional (default: Normal Authorization)
93 #               first_name: optional (default: patron's first_given_name field)
94 #                last_name: optional (default: patron's family_name field)
95 #                  address: optional (default: patron's street1 field + street2)
96 #                     city: optional (default: patron's city field)
97 #                    state: optional (default: patron's state field)
98 #                      zip: optional (default: patron's zip field)
99 #                  country: optional (some processor APIs: 2 letter code.)
100 #              description: optional
101 #                /, type => 'hash' }
102 #        ],
103 #        return => { desc => 'an ilsevent' }
104 #    }
105
106 sub process_payment {
107     my ($argshash) = @_;
108
109     # Confirm some required arguments.
110     return OpenILS::Event->new('BAD_PARAMS')
111         unless $argshash
112             and $argshash->{cc}
113             and $argshash->{amount}
114             and $argshash->{expiration}
115             and $argshash->{ou};
116
117     if (!$argshash->{processor}) {
118         if (!($argshash->{processor} =
119                 $U->ou_ancestor_setting_value(
120                     $argshash->{ou}, CREDIT_NS . '.processor.default'))) {
121             return OpenILS::Event->new('CREDIT_PROCESSOR_NOT_SPECIFIED');
122         }
123     }
124     # Basic sanity check on processor name.
125     if ($argshash->{processor} !~ /^[a-z0-9_\-]+$/i) {
126         return OpenILS::Event->new('CREDIT_PROCESSOR_NOT_ALLOWED');
127     }
128
129     # Get org unit settings related to our processor
130     my $psettings = get_processor_settings(
131         $argshash->{ou}, $argshash->{processor}
132     );
133
134     if (!$psettings->{enabled}) {
135         return OpenILS::Event->new('CREDIT_PROCESSOR_NOT_ENABLED');
136     }
137
138     # Add the org unit settings for the chosen processor to our argshash.
139     $argshash = +{ %{$argshash}, %{$psettings} };
140
141     # At least the following (derived from org unit settings) are required.
142     return OpenILS::Event->new('CREDIT_PROCESSOR_BAD_PARAMS')
143         unless $argshash->{login}
144             and $argshash->{password};
145
146     # A valid patron_id is also required.
147     my $e = new_editor();
148     my $patron = $e->retrieve_actor_user(
149         [
150             $argshash->{patron_id},
151             {
152                 flesh        => 1,
153                 flesh_fields => { au => ["mailing_address"] }
154             }
155         ]
156     ) or return $e->event;
157
158     return dispatch($argshash, $patron);
159 }
160
161 sub prepare_bop_content {
162     my ($argshash, $patron, $cardtype) = @_;
163
164     my %content;
165     foreach (qw/
166         login
167         password
168         description
169         first_name
170         last_name
171         amount
172         expiration
173         cvv2
174         address
175         city
176         state
177         zip
178         country/) {
179         if (exists $argshash->{$_}) {
180             $content{$_} = $argshash->{$_};
181         }
182     }
183     
184     $content{action}       = $argshash->{action} || "Normal Authorization";
185     $content{type}         = $cardtype;      #'American Express', 'VISA', 'MasterCard'
186     $content{card_number}  = $argshash->{cc};
187     $content{customer_id}  = $patron->id;
188     
189     $content{first_name} ||= $patron->first_given_name;
190     $content{last_name}  ||= $patron->family_name;
191
192     $content{FirstName}    = $content{first_name};   # kludge mcugly for PP
193     $content{LastName}     = $content{last_name};
194
195
196     # Especially for the following fields, do we need to support different
197     # mapping of fields for different payment processors, particularly ones
198     # in other countries?
199     $content{address}    ||= $patron->mailing_address->street1;
200     $content{address} .= ", " . $patron->mailing_address->street2
201         if $patron->mailing_address->street2;
202
203     $content{city}       ||= $patron->mailing_address->city;
204     $content{state}      ||= $patron->mailing_address->state;
205     $content{zip}        ||= $patron->mailing_address->post_code;
206     $content{country}    ||= $patron->mailing_address->country;
207
208     # Yet another fantastic kludge. country2code() comes from Locale::Country.
209     # PayPal must have 2 letter country field (ISO 3166) that's uppercase.
210     if (length($content{country}) > 2 && $argshash->{processor} eq 'PayPal') {
211         $content{country} = uc country2code($content{country});
212     }
213
214     %content;
215 }
216
217 sub dispatch {
218     my ($argshash, $patron) = @_;
219     
220     # The validate() sub is exported by Business::CreditCard.
221     if (!validate($argshash->{cc})) {
222         # Although it might help a troubleshooter, it's probably not a good
223         # idea to put the credit card number in the log file.
224         $logger->info("Credit card number invalid");
225
226         return new OpenILS::Event("CREDIT_PROCESSOR_INVALID_CC_NUMBER");
227     }
228
229     # cardtype() also comes from Business::CreditCard.  It is not certain that
230     # a) the card type returned by this method will be suitable input for
231     #   a payment processor, nor that
232     # b) it is even necessary to supply this argument to processors in all
233     #   cases.  Testing this with several processors would be a good idea.
234     (my $cardtype = cardtype($argshash->{cc})) =~ s/ card//i;
235
236     if (lc($cardtype) eq "unknown") {
237         $logger->info("Credit card number passed validate(), " .
238             "yet cardtype() returned $cardtype");
239         return new OpenILS::Event(
240             "CREDIT_PROCESSOR_INVALID_CC_NUMBER", "note" => "cardtype $cardtype"
241         );
242     }
243
244     $logger->debug(
245         "applying payment via processor '" . $argshash->{processor} . "'"
246     );
247
248     # Find B:OP constructor arguments specific to our payment processor.
249     my %bop_args = get_bop_args_filler($argshash);
250
251     # We're assuming that all B:OP processors accept this argument to the
252     # constructor.
253     $bop_args{test_transaction} = $argshash->{testmode};
254
255     my $transaction = new Business::OnlinePayment(
256         $argshash->{processor}, %bop_args
257     );
258
259     $transaction->content(prepare_bop_content($argshash, $patron, $cardtype));
260
261     # XXX submit() does not return a value, although crashing is possible here
262     # with some bad input depending on the payment processor.
263     $transaction->submit;
264
265     my $payload = {
266         "processor" => $argshash->{"processor"},
267         "card_type" => $cardtype,
268         "server_response" => $transaction->server_response
269     };
270
271     foreach (qw/authorization correlationid avs_code cvv2_code error_message/) {
272         # authorization should always be present for successes, and
273         # error_message should always be present for failures. The remaining
274         # field may be important in PayPal transacations? Not sure.
275         $payload->{$_} = $transaction->$_ if $transaction->can($_);
276     }
277
278     my $event_name;
279
280     if ($transaction->is_success()) {
281         $logger->info($argshash->{processor} . " payment succeeded");
282         $event_name = "SUCCESS";
283     } else {
284         $logger->info($argshash->{processor} . " payment failed");
285         $event_name = "CREDIT_PROCESSOR_DECLINED_TRANSACTION";
286     }
287
288     return new OpenILS::Event($event_name, "payload" => $payload);
289 }
290
291
292 1;