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