Add avs_code and cvv2_response to build_subs, they're standard fields
[Business-OnlinePayment.git] / OnlinePayment.pm
1 package Business::OnlinePayment;
2
3 use strict;
4 use vars qw($VERSION %_info_handler);
5 use Carp;
6
7 require 5.005;
8
9 $VERSION = '3.03_01';
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 @methods = qw(
16     authorization
17     order_number
18     error_message
19     failure_status
20     fraud_detect
21     is_success
22     maximum_risk
23     path
24     port
25     require_avs
26     result_code
27     server
28     server_response
29     test_transaction
30     transaction_type
31     fraud_score
32     fraud_transaction_id
33     response_code
34     response_header
35     response_page
36     avs_code
37     cvv2_response
38 );
39
40 #fallback
41 sub _info {
42   my $class = shift;
43   ( my $gw = $class ) =~ s/^Business::OnlinePayment:://;
44   {
45     'info_compat'    => '0.00',
46     'gateway_name'   => $gw,
47     'module_notes'   => "Module does not yet provide info.",
48   };
49 }
50
51 #allow classes to declare info in a flexible way, but return normalized info
52 %_info_handler = (
53   'supported_types'   => sub {
54     my( $class, $v ) = @_;
55     my $types = ref($v) ? $v : defined($v) ? [ $v ] : [];
56     $types = { map { $_=>1 } @$types } if ref($types) eq 'ARRAY';
57     $types;
58   },
59   'supported_actions' => sub {
60     my( $class, $v ) = @_;
61     return %$v if ref($v) eq 'HASH';
62     $v = [ $v ] unless ref($v);
63     my $types = $class->info('supported_types') || {};
64     ( map { $_ => $v } keys %$types );
65   },
66 );
67
68 sub info {
69   my $class = shift; #class or object
70   my $info = $class->_info;
71   if ( @_ ) {
72     my $key = shift;
73     exists($_info_handler{$key})
74       ? &{ $_info_handler{$key} }( $class, $info->{$key} )
75       : $info->{$key};
76   } else {
77     wantarray ? ( keys %$info ) : [ keys %$info ];
78   }
79 }
80
81 sub new {
82     my($class,$processor,%data) = @_;
83
84     croak("unspecified processor") unless $processor;
85
86     my $subclass = "${class}::$processor";
87     eval "use $subclass";
88     croak("unknown processor $processor ($@)") if $@;
89
90     my $self = bless {processor => $processor}, $subclass;
91     $self->build_subs(@methods);
92
93     if($self->can("set_defaults")) {
94         $self->set_defaults(%data);
95     }
96
97     foreach(keys %data) {
98         my $key = lc($_);
99         my $value = $data{$_};
100         $key =~ s/^\-+//;
101         $self->build_subs($key);
102         $self->$key($value);
103     }
104
105     # "wrap" submit with _pre_submit only once
106     unless ( $Presubmit_Added{$subclass} ) {
107         my $real_submit = $subclass->can('submit');
108
109         no warnings 'redefine';
110         no strict 'refs';
111
112         *{"${subclass}::submit"} = sub {
113             my $self = shift;
114             return unless $self->_pre_submit(@_);
115             return $real_submit->($self, @_);
116         }
117     }
118
119     return $self;
120 }
121
122 sub _risk_detect {
123     my ($self, $risk_transaction) = @_;
124
125     my %parent_content = $self->content();
126     $parent_content{action} = 'Fraud Detect';
127     $risk_transaction->content( %parent_content );
128     $risk_transaction->submit();
129     if ($risk_transaction->is_success()) {
130          $self->fraud_score( $risk_transaction->fraud_score );
131          $self->fraud_transaction_id( $risk_transaction->fraud_transaction_id );
132         if ( $risk_transaction->fraud_score <= $self->maximum_fraud_score()) {
133             return 1;
134         } else {
135             $self->error_message('Excessive risk from risk management');
136         }
137     } else {
138         $self->error_message('Error in risk detection stage: ' .  $risk_transaction->error_message);
139     }
140     $self->is_success(0);
141     return 0;
142 }
143
144 my @Fraud_Class_Path = qw(Business::OnlinePayment Business::FraudDetect);
145
146 sub _pre_submit {
147     my ($self) = @_;
148     my $fraud_detection = $self->fraud_detect();
149
150     # early return if user does not want optional risk mgt
151     return 1 unless $fraud_detection;
152
153     # Search for an appropriate FD module
154     foreach my $fraud_class ( @Fraud_Class_Path ) {
155         my $subclass = $fraud_class . "::" . $fraud_detection;
156         eval "use $subclass ()";
157         if ($@) {
158             croak("error loading fraud_detection module ($@)")
159               unless ( $@ =~ m/^Can\'t locate/ );
160         } else {
161             my $risk_tx = bless( { processor => $fraud_detection }, $subclass );
162             $risk_tx->build_subs(@methods);
163             if ($risk_tx->can('set_defaults')) {
164                 $risk_tx->set_defaults();
165             }
166             $risk_tx->_glean_parameters_from_parent($self);
167             return $self->_risk_detect($risk_tx);
168         }
169     }
170     croak("Unable to locate fraud_detection module $fraud_detection"
171                 . " in \@INC under Fraud_Class_Path (\@Fraud_Class_Path"
172                 . " contains: @Fraud_Class_Path) (\@INC contains: @INC)");
173 }
174
175 sub content {
176     my($self,%params) = @_;
177
178     if(%params) {
179         if($params{'type'}) { $self->transaction_type($params{'type'}); }
180         %{$self->{'_content'}} = %params;
181     }
182     return exists $self->{'_content'} ? %{$self->{'_content'}} : ();
183 }
184
185 sub required_fields {
186     my($self,@fields) = @_;
187
188     my @missing;
189     my %content = $self->content();
190     foreach(@fields) {
191         push(@missing, $_) unless exists $content{$_};
192     }
193
194     croak("missing required field(s): " . join(", ", @missing) . "\n")
195           if(@missing);
196 }
197
198 sub get_fields {
199     my($self, @fields) = @_;
200
201     my %content = $self->content();
202
203     #my %new = ();
204     #foreach(@fields) { $new{$_} = $content{$_}; }
205     #return %new;
206     map { $_ => $content{$_} } grep defined $content{$_}, @fields;
207 }
208
209 sub remap_fields {
210     my($self,%map) = @_;
211
212     my %content = $self->content();
213     foreach( keys %map ) {
214         $content{$map{$_}} = $content{$_};
215     }
216     $self->content(%content);
217 }
218
219 sub submit {
220     my($self) = @_;
221
222     croak("Processor subclass did not override submit function");
223 }
224
225 sub dump_contents {
226     my($self) = @_;
227
228     my %content = $self->content();
229     my $dump = "";
230     foreach(sort keys %content) {
231         $dump .= "$_ = $content{$_}\n";
232     }
233     return $dump;
234 }
235
236 # didnt use AUTOLOAD because Net::SSLeay::AUTOLOAD passes right to
237 # AutoLoader::AUTOLOAD, instead of passing up the chain
238 sub build_subs {
239     my $self = shift;
240
241     foreach(@_) {
242         next if($self->can($_));
243         eval "sub $_ { my \$self = shift; if(\@_) { \$self->{$_} = shift; } return \$self->{$_}; }";
244     }
245 }
246
247 #helper method
248
249 sub silly_bool {
250   my( $self, $value ) = @_;
251   return 1 if $value =~ /^[yt]/i;
252   return 0 if $value =~ /^[fn]/i;
253   #return 1 if $value == 1;
254   #return 0 if $value == 0;
255   $value; #die??
256 }
257
258 1;
259
260 __END__
261
262 =head1 NAME
263
264 Business::OnlinePayment - Perl extension for online payment processing
265
266 =head1 SYNOPSIS
267
268   use Business::OnlinePayment;
269   
270   my $transaction = new Business::OnlinePayment($processor, %processor_info);
271   $transaction->content(
272                         type        => 'Visa',
273                         amount      => '49.95',
274                         card_number => '1234123412341238',
275                         expiration  => '06/15',
276                         name        => 'John Q Doe',
277                        );
278   $transaction->submit();
279   
280   if($transaction->is_success()) {
281     print "Card processed successfully: ", $transaction->authorization(), "\n";
282   } else {
283     print "Card was rejected: ", $transaction->error_message(), "\n";
284   }
285
286 =head1 DESCRIPTION
287
288 Business::OnlinePayment is a generic module for processing payments
289 through online credit card processors, electronic cash systems, etc.
290
291 =head1 CONSTRUCTOR
292
293 =head2 new($processor, %processor_options)
294
295 Create a new Business::OnlinePayment object, $processor is required,
296 and defines the online processor to use.  If necessary, processor
297 options can be specified, currently supported options are 'Server',
298 'Port', and 'Path', which specify how to find the online processor
299 (https://server:port/path), but individual processor modules should
300 supply reasonable defaults for this information, override the defaults
301 only if absolutely necessary (especially path), as the processor
302 module was probably written with a specific target script in mind.
303
304 =head1 TRANSACTION SETUP METHODS
305
306 =head2 content(%content)
307
308 The information necessary for the transaction, this tends to vary a
309 little depending on the processor, so we have chosen to use a system
310 which defines specific fields in the frontend which get mapped to the
311 correct fields in the backend.  The currently defined fields are:
312
313 =head3 PROCESSOR FIELDS
314
315 =over 4
316
317 =item login
318
319 Your login name to use for authentication to the online processor.
320
321 =item password
322
323 Your password to use for authentication to the online processor.
324
325 =back
326
327 =head3 REQUIRED TRANSACTION FIELDS
328
329 =over 4
330
331 =item type
332
333 Transaction type, supported types are: CC (credit card), ECHECK
334 (electronic check) and LEC (phone bill billing).  Deprecated types
335 are: Visa, MasterCard, American Express, Discover, Check.  Not all
336 processors support all transaction types.
337
338 =item action
339
340 What action being taken by this transaction. Currently available are:
341
342 =over 8
343
344 =item Normal Authorization
345
346 =item Authorization Only
347
348 =item Post Authorization
349
350 =item Reverse Authorization
351
352 =item Void
353
354 =item Credit
355
356 =item Recurring Authorization
357
358 =item Modify Recurring Authorization
359
360 =item Cancel Recurring Authorization
361
362 =back
363
364 =item amount
365
366 The amount of the transaction.  No dollar signs or currency identifiers,
367 just a whole or floating point number (i.e. 26, 26.1 or 26.13).
368
369 =back
370
371 =head3 OPTIONAL TRANSACTION FIELDS
372
373 =over 4
374
375 =item description
376
377 A description of the transaction (used by some processors to send
378 information to the client, normally not a required field).
379
380 =item invoice_number
381
382 An invoice number, for your use and not normally required, many
383 processors require this field to be a numeric only field.
384
385 =item po_number
386
387 Purchase order number (normally not required).
388
389 =item tax
390
391 Tax amount (portion of amount field, not added to it).
392
393 =item freight
394
395 Freight amount (portion of amount field, not added to it).
396
397 =item duty
398
399 Duty amount (portion of amount field, not added to it).
400
401 =item tax_exempt
402
403 Tax exempt flag (i.e. TRUE, FALSE, T, F, YES, NO, Y, N, 1, 0).
404
405 =item currency
406
407 Currency, specified as an ISO 4217 three-letter code, such as USD, CAD, EUR,
408 AUD, DKK, GBP, JPY, NZD, etc.
409
410 =back
411
412 =head3 CUSTOMER INFO FIELDS
413
414 =over 4
415
416 =item customer_id
417
418 A customer identifier, again not normally required.
419
420 =item name
421
422 The customer's name, your processor may not require this.
423
424 =item first_name
425
426 =item last_name
427
428 The customer's first and last name as separate fields.
429
430 =item company
431
432 The customer's company name, not normally required.
433
434 =item address
435
436 The customer's address (your processor may not require this unless you
437 are requiring AVS Verification).
438
439 =item city
440
441 The customer's city (your processor may not require this unless you
442 are requiring AVS Verification).
443
444 =item state
445
446 The customer's state (your processor may not require this unless you
447 are requiring AVS Verification).
448
449 =item zip
450
451 The customer's zip code (your processor may not require this unless
452 you are requiring AVS Verification).
453
454 =item country
455
456 Customer's country.
457
458 =item ship_first_name
459
460 =item ship_last_name
461
462 =item ship_company
463
464 =item ship_address
465
466 =item ship_city
467
468 =item ship_state
469
470 =item ship_zip
471
472 =item ship_country
473
474 These shipping address fields may be accepted by your processor.
475 Refer to the description for the corresponding non-ship field for
476 general information on each field.
477
478 =item phone
479
480 Customer's phone number.
481
482 =item fax
483
484 Customer's fax number.
485
486 =item email
487
488 Customer's email address.
489
490 =item customer_ip
491
492 IP Address from which the transaction originated.
493
494 =back
495
496 =head3 CREDIT CARD FIELDS
497
498 =over 4
499
500 =item card_number
501
502 Credit card number.
503
504 =item expiration
505
506 Credit card expiration, MM/YY.
507
508 =item cvv2
509
510 CVV2 number (also called CVC2 or CID) is a three- or four-digit
511 security code used to reduce credit card fraud.
512
513 =item card_token
514
515 If supported by your gateway, you can pass a card_token instead of a
516 card_number and expiration.
517
518 =cut
519
520 #=item card_response
521 #
522 #Some card_token schemes implement a challenge/response handshake.  In those
523 #cases, this field is used for the response.  In most cases the handshake
524 #it taken care of by the gateway module.
525
526 =item track1
527
528 Track 1 on the magnetic stripe (Card present only)
529
530 =item track2
531
532 Track 2 on the magnetic stripe (Card present only)
533
534 =item recurring_billing
535
536 Recurring billing flag
537
538 =back
539
540 =head3 ELECTRONIC CHECK FIELDS
541
542 =over 4
543
544 =item account_number
545
546 Bank account number
547
548 =item routing_code
549
550 Bank's routing code
551
552 =item account_type
553
554 Account type.  Can be (case-insensitive): B<Personal Checking>,
555 B<Personal Savings>, B<Business Checking> or B<Business Savings>.
556
557 =item account_name
558
559 Account holder's name.
560
561 =item bank_name
562
563 Bank name.
564
565 =item bank_city
566
567 Bank city.
568
569 =item bank_state
570
571 Bank state.
572
573 =item check_type
574
575 Check type.
576
577 =item customer_org
578
579 Customer organization type.
580
581 =item customer_ssn
582
583 Customer's social security number.
584
585 =item license_num
586
587 Customer's driver's license number.
588
589 =item license_dob
590
591 Customer's date of birth.
592
593 =back
594
595 =head3 RECURRING BILLING FIELDS
596
597 =over 4
598
599 =item interval 
600
601 Interval expresses the amount of time between billings: digits, whitespace
602 and units (currently "days" or "months" in either singular or plural form).
603
604 =item start
605
606 The date of the first transaction (used for processors which allow delayed
607 start) expressed as YYYY-MM-DD.
608
609 =item periods
610
611 The number of cycles of interval length for which billing should occur 
612 (inclusive of 'trial periods' if the processor supports recurring billing
613 at more than one rate)
614
615 =back
616
617 =head2 test_transaction()
618
619 Most processors provide a test mode, where submitted transactions will
620 not actually be charged or added to your batch, calling this function
621 with a true argument will turn that mode on if the processor supports
622 it, or generate a fatal error if the processor does not support a test
623 mode (which is probably better than accidentally making real charges).
624
625 =head2 require_avs()
626
627 Providing a true argument to this module will turn on address
628 verification (if the processor supports it).
629
630 =head1 TRANSACTION SUBMISSION METHOD
631
632 =head2 submit()
633
634 Submit the transaction to the processor for completion
635
636 =head1 TRANSACTION RESULT METHODS
637
638 =head2 is_success()
639
640 Returns true if the transaction was approved by the gateway, false if 
641 it was submitted but not approved, or undef if it has not been 
642 submitted yet.
643
644 =head2 error_message()
645
646 If the transaction has been submitted but was not accepted, this
647 function will return the provided error message (if any) that the
648 processor returned.
649
650 =head2 failure_status()
651
652 If the transaction failed, it can optionally return a specific failure
653 status (normalized, not gateway-specific).  Currently defined statuses
654 are: "expired", "nsf" (non-sufficient funds), "stolen", "pickup",
655 "blacklisted" and "declined" (card/transaction declines only, not
656 other errors).
657
658 Note that (as of Aug 2006) this is only supported by some of the
659 newest processor modules, and that, even if supported, a failure
660 status is an entirely optional field that is only set for specific
661 kinds of failures.
662
663 =head2 authorization()
664
665 If the transaction has been submitted and accepted, this function will
666 provide you with the authorization code that the processor returned.
667 Store this if you would like to run inquiries or refunds on the transaction
668 later.
669
670 =head2 order_number()
671
672 The unique order number for the transaction generated by the gateway.  Store
673 this if you would like to run inquiries or refunds on the transaction later.
674
675 =head2 card_token()
676
677 If supported by your gateway, a card_token can be used in a subsequent
678 transaction to refer to a card number.
679
680 =head2 fraud_score()
681
682 Retrieve or change the fraud score from any Business::FraudDetect plugin
683
684 =head2 fraud_transaction_id()
685
686 Retrieve or change the transaction id from any Business::FraudDetect plugin
687
688 =head2 response_code()
689
690 =head2 response_headers()
691
692 =head2 response_page()
693
694 These three fields are set by some processors (especially those which use
695 HTTPS) when the transaction fails at the communication level rather than
696 as a transaction.
697
698 response_code is the HTTP response code and message, i.e.
699 '500 Internal Server Error'.
700
701 response_headers is a hash reference of the response headers
702
703 response_page is the raw content.
704
705 =head2 result_code()
706
707 Returns the precise result code that the processor returned, these are
708 normally one letter codes that don't mean much unless you understand
709 the protocol they speak, you probably don't need this, but it's there
710 just in case.
711
712 =head2 avs_code()
713
714 =head2 cvv2_response()
715
716 =head1 MISCELLANEOUS INTERNAL METHODS
717
718 =head2 transaction_type()
719
720 Retrieve the transaction type (the 'type' argument to contents()).
721 Generally only used internally, but provided in case it is useful.
722
723 =head2 server()
724
725 Retrieve or change the processor submission server address (CHANGE AT
726 YOUR OWN RISK).
727
728 =head2 port()
729
730 Retrieve or change the processor submission port (CHANGE AT YOUR OWN
731 RISK).
732
733 =head2 path()
734
735 Retrieve or change the processor submission path (CHANGE AT YOUR OWN
736 RISK).
737
738 =head1 HELPER METHODS FOR GATEWAY MODULE AUTHORS
739
740 =head2 build_subs( @sub_names )
741
742 Build setter/getter subroutines for new return values.
743
744 =head2 get_fields( @fields )
745
746 Get the named fields if they are defined.
747
748 =head2 remap_fields( %map )
749
750 Remap field content (and stuff it back into content).
751
752 =head2 required_fields( @fields )
753
754 Croaks if any of the required fields are not present.
755
756 =head2 dump_contents
757
758 =head2 silly_bool( $value )
759
760 Returns 0 if the value starts with y, Y, t or T.
761 Returns 1 if the value starts with n, N, f or F.
762 Otherwise returns the value itself.
763
764 Use this for handling boolean content like tax_exempt.
765
766 =head1 AUTHORS
767
768 (v2 series)
769
770 Jason Kohles, email@jasonkohles.com
771
772 (v3 rewrite)
773
774 Ivan Kohler <ivan-business-onlinepayment@420.am>
775
776 Phil Lobbes E<lt>phil at perkpartners dot comE<gt>
777
778 =head1 COPYRIGHT
779
780 Copyright (c) 1999-2004 Jason Kohles
781 Copyright (c) 2004 Ivan Kohler
782 Copyright (c) 2007-2014 Freeside Internet Services, Inc.
783
784 All rights reserved.
785
786 This program is free software; you can redistribute it and/or modify it under
787 the same terms as Perl itself.
788
789 =head1 HOMEPAGE
790
791 Homepage:  http://420.am/business-onlinepayment/
792
793 Development:  http://420.am/business-onlinepayment/ng.html
794
795 =head1 MAILING LIST
796
797 Please direct current development questions, patches, etc. to the mailing list:
798 http://420.am/cgi-bin/mailman/listinfo/bop-devel/
799
800 =head1 REPOSITORY
801
802 The code is available from our public git repository:
803
804   git clone git://git.freeside.biz/Business-OnlinePayment.git
805
806 Or on the web:
807
808   http://freeside.biz/gitweb/?p=Business-OnlinePayment.git
809
810 Many (but by no means all!) processor plugins are also available in the same
811 repository, see:
812
813   http://freeside.biz/gitweb/
814
815 =head1 DISCLAIMER
816
817 THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
818 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
819 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
820
821 =head1 SEE ALSO
822
823 http://420.am/business-onlinepayment/
824
825 For verification of credit card checksums, see L<Business::CreditCard>.
826
827 =cut