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