defined &$class is not how you detect if a class has been loaded (just using use...
[Business-OnlinePayment.git] / OnlinePayment.pm
1 package Business::OnlinePayment;
2
3 use strict;
4 use vars qw($VERSION);
5 use Carp;
6
7 require 5.005;
8
9 $VERSION = '3.00_08';
10 $VERSION = eval $VERSION; # modperlstyle: convert the string into a number
11
12 # Remember subclasses we have "wrapped" submit() with _pre_submit()
13 my %Presubmit_Added = ();
14
15 my %fields = (
16     authorization    => undef,
17     error_message    => undef,
18     failure_status   => undef,
19     fraud_detect     => undef,
20     is_success       => undef,
21     maximum_risk     => undef,
22     path             => undef,
23     port             => undef,
24     require_avs      => undef,
25     result_code      => undef,
26     server           => undef,
27     server_response  => undef,
28     test_transaction => undef,
29     transaction_type => undef,
30 );
31
32 sub new {
33     my($class,$processor,%data) = @_;
34
35     croak("unspecified processor") unless $processor;
36
37     my $subclass = "${class}::$processor";
38     eval "use $subclass";
39     croak("unknown processor $processor ($@)") if $@;
40
41     my $self = bless {processor => $processor}, $subclass;
42     $self->build_subs(keys %fields);
43
44     if($self->can("set_defaults")) {
45         $self->set_defaults(%data);
46     }
47
48     foreach(keys %data) {
49         my $key = lc($_);
50         my $value = $data{$_};
51         $key =~ s/^\-+//;
52         $self->build_subs($key);
53         $self->$key($value);
54     }
55
56     # "wrap" submit with _pre_submit only once
57     unless ( $Presubmit_Added{$subclass} ) {
58         my $real_submit = $subclass->can('submit');
59
60         no warnings 'redefine';
61         no strict 'refs';
62
63         *{"${subclass}::submit"} = sub {
64             my $self = shift;
65             return unless $self->_pre_submit(@_);
66             return $real_submit->($self, @_);
67         }
68     }
69
70     return $self;
71 }
72
73 sub _risk_detect {
74     my ($self, $risk_transaction) = @_;
75
76     my %parent_content = $self->content();
77     $parent_content{action} = 'Fraud Detect';
78     $risk_transaction->content( %parent_content );
79     $risk_transaction->submit();
80     if ($risk_transaction->is_success()) {
81         if ( $risk_transaction->fraud_score <= $self->maximum_fraud_score()) {
82             return 1;
83         } else {
84             $self->error_message('Excessive risk from risk management');
85         }
86     } else {
87         $self->error_message('Error in risk detection stage: ' .  $risk_transaction->error_message);
88     }
89     $self->is_success(0);
90     return 0;
91 }
92
93 my @Fraud_Class_Path = qw(Business::OnlinePayment Business::FraudDetect);
94
95 sub _pre_submit {
96     my ($self) = @_;
97     my $fraud_detection = $self->fraud_detect();
98
99     # early return if user does not want optional risk mgt
100     return 1 unless $fraud_detection;
101
102     # Search for an appropriate FD module
103     foreach my $fraud_class ( @Fraud_Class_Path ) {
104         my $subclass = $fraud_class . "::" . $fraud_detection;
105         eval "use $subclass ()";
106         if ($@) {
107             croak("error loading fraud_detection module ($@)")
108               unless ( $@ =~ m/^Can\'t locate/ );
109         } else {
110             my $risk_tx = bless( { processor => $fraud_detection }, $subclass );
111             $risk_tx->build_subs(keys %fields);
112             if ($risk_tx->can('set_defaults')) {
113                 $risk_tx->set_defaults();
114             }
115             $risk_tx->_glean_parameters_from_parent($self);
116             return $self->_risk_detect($risk_tx);
117         }
118     }
119     croak("Unable to locate fraud_detection module $fraud_detection"
120                 . " in \@INC under Fraud_Class_Path (\@Fraud_Class_Path"
121                 . " contains: @Fraud_Class_Path) (\@INC contains: @INC)");
122 }
123
124 sub content {
125     my($self,%params) = @_;
126
127     if(%params) {
128         if($params{'type'}) { $self->transaction_type($params{'type'}); }
129         %{$self->{'_content'}} = %params;
130     }
131     return exists $self->{'_content'} ? %{$self->{'_content'}} : ();
132 }
133
134 sub required_fields {
135     my($self,@fields) = @_;
136
137     my @missing;
138     my %content = $self->content();
139     foreach(@fields) {
140         push(@missing, $_) unless exists $content{$_};
141     }
142
143     croak("missing required field(s): " . join(", ", @missing) . "\n")
144           if(@missing);
145 }
146
147 sub get_fields {
148     my($self, @fields) = @_;
149
150     my %content = $self->content();
151
152     #my %new = ();
153     #foreach(@fields) { $new{$_} = $content{$_}; }
154     #return %new;
155     map { $_ => $content{$_} } grep defined $content{$_}, @fields;
156 }
157
158 sub remap_fields {
159     my($self,%map) = @_;
160
161     my %content = $self->content();
162     foreach( keys %map ) {
163         $content{$map{$_}} = $content{$_};
164     }
165     $self->content(%content);
166 }
167
168 sub submit {
169     my($self) = @_;
170
171     croak("Processor subclass did not override submit function");
172 }
173
174 sub dump_contents {
175     my($self) = @_;
176
177     my %content = $self->content();
178     my $dump = "";
179     foreach(sort keys %content) {
180         $dump .= "$_ = $content{$_}\n";
181     }
182     return $dump;
183 }
184
185 # didnt use AUTOLOAD because Net::SSLeay::AUTOLOAD passes right to
186 # AutoLoader::AUTOLOAD, instead of passing up the chain
187 sub build_subs {
188     my $self = shift;
189
190     foreach(@_) {
191         next if($self->can($_));
192         eval "sub $_ { my \$self = shift; if(\@_) { \$self->{$_} = shift; } return \$self->{$_}; }";
193     }
194 }
195
196 1;
197
198 __END__
199
200 =head1 NAME
201
202 Business::OnlinePayment - Perl extension for online payment processing
203
204 =head1 SYNOPSIS
205
206   use Business::OnlinePayment;
207   
208   my $transaction = new Business::OnlinePayment($processor, %processor_info);
209   $transaction->content(
210                         type        => 'Visa',
211                         amount      => '49.95',
212                         card_number => '1234123412341238',
213                         expiration  => '0100',
214                         name        => 'John Q Doe',
215                        );
216   $transaction->submit();
217   
218   if($transaction->is_success()) {
219     print "Card processed successfully: ", $transaction->authorization(), "\n";
220   } else {
221     print "Card was rejected: ", $transaction->error_message(), "\n";
222   }
223
224 =head1 DESCRIPTION
225
226 Business::OnlinePayment is a generic module for processing payments
227 through online credit card processors, electronic cash systems, etc.
228
229 =head1 METHODS AND FUNCTIONS
230
231 =head2 new($processor, %processor_options);
232
233 Create a new Business::OnlinePayment object, $processor is required,
234 and defines the online processor to use.  If necessary, processor
235 options can be specified, currently supported options are 'Server',
236 'Port', and 'Path', which specify how to find the online processor
237 (https://server:port/path), but individual processor modules should
238 supply reasonable defaults for this information, override the defaults
239 only if absolutely necessary (especially path), as the processor
240 module was probably written with a specific target script in mind.
241
242 =head2 content(%content);
243
244 The information necessary for the transaction, this tends to vary a
245 little depending on the processor, so we have chosen to use a system
246 which defines specific fields in the frontend which get mapped to the
247 correct fields in the backend.  The currently defined fields are:
248
249 =head3 PROCESSOR FIELDS
250
251 =over 4
252
253 =item * login
254
255 Your login name to use for authentication to the online processor.
256
257 =item * password
258
259 Your password to use for authentication to the online processor.
260
261 =back
262
263 =head3 GENERAL TRANSACTION FIELDS
264
265 =over 4
266
267 =item * type
268
269 Transaction type, supported types are: CC (credit card), ECHECK
270 (electronic check) and LEC (phone bill billing).  Deprecated types
271 are: Visa, MasterCard, American Express, Discover, Check (not all
272 processors support all these transaction types).
273
274 =item * action
275
276 What to do with the transaction (currently available are: Normal
277 Authorization, Authorization Only, Credit, Post Authorization)
278
279 =item * description
280
281 A description of the transaction (used by some processors to send
282 information to the client, normally not a required field).
283
284 =item * amount
285
286 The amount of the transaction, most processors don't want dollar signs
287 and the like, just a floating point number.
288
289 =item * invoice_number
290
291 An invoice number, for your use and not normally required, many
292 processors require this field to be a numeric only field.
293
294 =back
295
296 =head3 CUSTOMER INFO FIELDS
297
298 =over 4
299
300 =item * customer_id
301
302 A customer identifier, again not normally required.
303
304 =item * name
305
306 The customer's name, your processor may not require this.
307
308 =item * first_name
309
310 =item * last_name
311
312 The customer's first and last name as separate fields.
313
314 =item * company
315
316 The customer's company name, not normally required.
317
318 =item * address
319
320 The customer's address (your processor may not require this unless you
321 are requiring AVS Verification).
322
323 =item * city
324
325 The customer's city (your processor may not require this unless you
326 are requiring AVS Verification).
327
328 =item * state
329
330 The customer's state (your processor may not require this unless you
331 are requiring AVS Verification).
332
333 =item * zip
334
335 The customer's zip code (your processor may not require this unless
336 you are requiring AVS Verification).
337
338 =item * country
339
340 Customer's country.
341
342 =item * ship_first_name
343
344 =item * ship_last_name
345
346 =item * ship_company
347
348 =item * ship_address
349
350 =item * ship_city
351
352 =item * ship_state
353
354 =item * ship_zip
355
356 =item * ship_country
357
358 These shipping address fields may be accepted by your processor.
359 Refer to the description for the corresponding non-ship field for
360 general information on each field.
361
362 =item * phone
363
364 Customer's phone number.
365
366 =item * fax
367
368 Customer's fax number.
369
370 =item * email
371
372 Customer's email address.
373
374 =item * customer_ip
375
376 IP Address from which the transaction originated.
377
378 =back
379
380 =head3 CREDIT CARD FIELDS
381
382 =over 4
383
384 =item * card_number
385
386 Credit card number (obviously not required for non-credit card
387 transactions).
388
389 =item * cvv2
390
391 CVV2 number (also called CVC2 or CID) is a three- or four-digit
392 security code used to reduce credit card fraud.
393
394 =item * expiration
395
396 Credit card expiration (obviously not required for non-credit card
397 transactions).
398
399 =item * recurring billing
400
401 Recurring billing flag
402
403 =back
404
405 =head3 ELECTRONIC CHECK FIELDS
406
407 =over 4
408
409 =item * account_number
410
411 Bank account number for electronic checks or electronic funds
412 transfer.
413
414 =item * routing_code
415
416 Bank's routing code for electronic checks or electronic funds
417 transfer.
418
419 =item * account_type
420
421 Account type for electronic checks or electronic funds transfer.
422
423 =item * account_name
424
425 Account holder's name for electronic checks or electronic funds
426 transfer.
427
428 =item * bank_name
429
430 Bank's name for electronic checks or electronic funds transfer.
431
432 =item * check_type
433
434 Check type for electronic checks or electronic funds transfer.
435
436 =item * customer_org
437
438 Customer organization type.
439
440 =item * customer_ssn
441
442 Customer's social security number.  Typically only required for
443 electronic checks or electronic funds transfer.
444
445 =item * license_num
446
447 Customer's driver's license number.  Typically only required for
448 electronic checks or electronic funds transfer.
449
450 =item * license_dob
451
452 Customer's date of birth.  Typically only required for electronic
453 checks or electronic funds transfer.
454
455 =back
456
457 =head2 submit();
458
459 Submit the transaction to the processor for completion
460
461 =head2 is_success();
462
463 Returns true if the transaction was submitted successfully, false if
464 it failed (or undef if it has not been submitted yet).
465
466 =head2 failure_status();
467
468 If the transaction failed, it can optionally return a specific failure
469 status (normalized, not gateway-specific).  Currently defined statuses
470 are: "expired", "nsf" (non-sufficient funds), "stolen", "pickup",
471 "blacklisted" and "declined" (card/transaction declines only, not
472 other errors).
473
474 Note that (as of Aug 2006) this is only supported by some of the
475 newest processor modules, and that, even if supported, a failure
476 status is an entirely optional field that is only set for specific
477 kinds of failures.
478
479 =head2 result_code();
480
481 Returns the precise result code that the processor returned, these are
482 normally one letter codes that don't mean much unless you understand
483 the protocol they speak, you probably don't need this, but it's there
484 just in case.
485
486 =head2 test_transaction();
487
488 Most processors provide a test mode, where submitted transactions will
489 not actually be charged or added to your batch, calling this function
490 with a true argument will turn that mode on if the processor supports
491 it, or generate a fatal error if the processor does not support a test
492 mode (which is probably better than accidentally making real charges).
493
494 =head2 require_avs();
495
496 Providing a true argument to this module will turn on address
497 verification (if the processor supports it).
498
499 =head2 transaction_type();
500
501 Retrieve the transaction type (the 'type' argument to contents()).
502 Generally only used internally, but provided in case it is useful.
503
504 =head2 error_message();
505
506 If the transaction has been submitted but was not accepted, this
507 function will return the provided error message (if any) that the
508 processor returned.
509
510 =head2 authorization();
511
512 If the transaction has been submitted and accepted, this function will
513 provide you with the authorization code that the processor returned.
514
515 =head2 server();
516
517 Retrieve or change the processor submission server address (CHANGE AT
518 YOUR OWN RISK).
519
520 =head2 port();
521
522 Retrieve or change the processor submission port (CHANGE AT YOUR OWN
523 RISK).
524
525 =head2 path();
526
527 Retrieve or change the processor submission path (CHANGE AT YOUR OWN
528 RISK).
529
530 =head1 AUTHORS
531
532 Jason Kohles, email@jasonkohles.com
533
534 (v3 rewrite) Ivan Kohler <ivan-business-onlinepayment@420.am>
535
536 Phil Lobbes E<lt>phil at perkpartners dot comE<gt>
537
538 =head1 MAILING LIST
539
540 Please direct current development questions, patches, etc. to the mailing list:
541 http://420.am/cgi-bin/mailman/listinfo/bop-devel/
542
543 =head1 DISCLAIMER
544
545 THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
546 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
547 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
548
549 =head1 SEE ALSO
550
551 http://420.am/business-onlinepayment/
552
553 For verification of credit card checksums, see L<Business::CreditCard>.
554
555 =cut