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