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