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