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