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