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