09c9b4b6c928c8fcf6d017c9ea354abe955bae3a
[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.00_09';
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 1;
201
202 __END__
203
204 =head1 NAME
205
206 Business::OnlinePayment - Perl extension for online payment processing
207
208 =head1 SYNOPSIS
209
210   use Business::OnlinePayment;
211   
212   my $transaction = new Business::OnlinePayment($processor, %processor_info);
213   $transaction->content(
214                         type        => 'Visa',
215                         amount      => '49.95',
216                         card_number => '1234123412341238',
217                         expiration  => '0100',
218                         name        => 'John Q Doe',
219                        );
220   $transaction->submit();
221   
222   if($transaction->is_success()) {
223     print "Card processed successfully: ", $transaction->authorization(), "\n";
224   } else {
225     print "Card was rejected: ", $transaction->error_message(), "\n";
226   }
227
228 =head1 DESCRIPTION
229
230 Business::OnlinePayment is a generic module for processing payments
231 through online credit card processors, electronic cash systems, etc.
232
233 =head1 METHODS AND FUNCTIONS
234
235 =head2 new($processor, %processor_options);
236
237 Create a new Business::OnlinePayment object, $processor is required,
238 and defines the online processor to use.  If necessary, processor
239 options can be specified, currently supported options are 'Server',
240 'Port', and 'Path', which specify how to find the online processor
241 (https://server:port/path), but individual processor modules should
242 supply reasonable defaults for this information, override the defaults
243 only if absolutely necessary (especially path), as the processor
244 module was probably written with a specific target script in mind.
245
246 =head2 content(%content);
247
248 The information necessary for the transaction, this tends to vary a
249 little depending on the processor, so we have chosen to use a system
250 which defines specific fields in the frontend which get mapped to the
251 correct fields in the backend.  The currently defined fields are:
252
253 =head3 PROCESSOR FIELDS
254
255 =over 4
256
257 =item * login
258
259 Your login name to use for authentication to the online processor.
260
261 =item * password
262
263 Your password to use for authentication to the online processor.
264
265 =back
266
267 =head3 GENERAL TRANSACTION FIELDS
268
269 =over 4
270
271 =item * type
272
273 Transaction type, supported types are: CC (credit card), ECHECK
274 (electronic check) and LEC (phone bill billing).  Deprecated types
275 are: Visa, MasterCard, American Express, Discover, Check (not all
276 processors support all these transaction types).
277
278 =item * action
279
280 What to do with the transaction (currently available are: Normal
281 Authorization, Authorization Only, Credit, Post Authorization)
282
283 =item * description
284
285 A description of the transaction (used by some processors to send
286 information to the client, normally not a required field).
287
288 =item * amount
289
290 The amount of the transaction, most processors don't want dollar signs
291 and the like, just a floating point number.
292
293 =item * invoice_number
294
295 An invoice number, for your use and not normally required, many
296 processors require this field to be a numeric only field.
297
298 =back
299
300 =head3 CUSTOMER INFO FIELDS
301
302 =over 4
303
304 =item * customer_id
305
306 A customer identifier, again not normally required.
307
308 =item * name
309
310 The customer's name, your processor may not require this.
311
312 =item * first_name
313
314 =item * last_name
315
316 The customer's first and last name as separate fields.
317
318 =item * company
319
320 The customer's company name, not normally required.
321
322 =item * address
323
324 The customer's address (your processor may not require this unless you
325 are requiring AVS Verification).
326
327 =item * city
328
329 The customer's city (your processor may not require this unless you
330 are requiring AVS Verification).
331
332 =item * state
333
334 The customer's state (your processor may not require this unless you
335 are requiring AVS Verification).
336
337 =item * zip
338
339 The customer's zip code (your processor may not require this unless
340 you are requiring AVS Verification).
341
342 =item * country
343
344 Customer's country.
345
346 =item * ship_first_name
347
348 =item * ship_last_name
349
350 =item * ship_company
351
352 =item * ship_address
353
354 =item * ship_city
355
356 =item * ship_state
357
358 =item * ship_zip
359
360 =item * ship_country
361
362 These shipping address fields may be accepted by your processor.
363 Refer to the description for the corresponding non-ship field for
364 general information on each field.
365
366 =item * phone
367
368 Customer's phone number.
369
370 =item * fax
371
372 Customer's fax number.
373
374 =item * email
375
376 Customer's email address.
377
378 =item * customer_ip
379
380 IP Address from which the transaction originated.
381
382 =back
383
384 =head3 CREDIT CARD FIELDS
385
386 =over 4
387
388 =item * card_number
389
390 Credit card number (obviously not required for non-credit card
391 transactions).
392
393 =item * cvv2
394
395 CVV2 number (also called CVC2 or CID) is a three- or four-digit
396 security code used to reduce credit card fraud.
397
398 =item * expiration
399
400 Credit card expiration (obviously not required for non-credit card
401 transactions).
402
403 =item * recurring billing
404
405 Recurring billing flag
406
407 =back
408
409 =head3 ELECTRONIC CHECK FIELDS
410
411 =over 4
412
413 =item * account_number
414
415 Bank account number for electronic checks or electronic funds
416 transfer.
417
418 =item * routing_code
419
420 Bank's routing code for electronic checks or electronic funds
421 transfer.
422
423 =item * account_type
424
425 Account type for electronic checks or electronic funds transfer.  Can be
426 (case-insensitive): B<Personal Checking>, B<Personal Savings>,
427 B<Business Checking> or B<Business Savings>.
428
429 =item * account_name
430
431 Account holder's name for electronic checks or electronic funds
432 transfer.
433
434 =item * bank_name
435
436 Bank's name for electronic checks or electronic funds transfer.
437
438 =item * check_type
439
440 Check type for electronic checks or electronic funds transfer.
441
442 =item * customer_org
443
444 Customer organization type.
445
446 =item * customer_ssn
447
448 Customer's social security number.  Typically only required for
449 electronic checks or electronic funds transfer.
450
451 =item * license_num
452
453 Customer's driver's license number.  Typically only required for
454 electronic checks or electronic funds transfer.
455
456 =item * license_dob
457
458 Customer's date of birth.  Typically only required for electronic
459 checks or electronic funds transfer.
460
461 =back
462
463 =head2 submit();
464
465 Submit the transaction to the processor for completion
466
467 =head2 is_success();
468
469 Returns true if the transaction was submitted successfully, false if
470 it failed (or undef if it has not been submitted yet).
471
472 =head2 failure_status();
473
474 If the transaction failed, it can optionally return a specific failure
475 status (normalized, not gateway-specific).  Currently defined statuses
476 are: "expired", "nsf" (non-sufficient funds), "stolen", "pickup",
477 "blacklisted" and "declined" (card/transaction declines only, not
478 other errors).
479
480 Note that (as of Aug 2006) this is only supported by some of the
481 newest processor modules, and that, even if supported, a failure
482 status is an entirely optional field that is only set for specific
483 kinds of failures.
484
485 =head2 result_code();
486
487 Returns the precise result code that the processor returned, these are
488 normally one letter codes that don't mean much unless you understand
489 the protocol they speak, you probably don't need this, but it's there
490 just in case.
491
492 =head2 test_transaction();
493
494 Most processors provide a test mode, where submitted transactions will
495 not actually be charged or added to your batch, calling this function
496 with a true argument will turn that mode on if the processor supports
497 it, or generate a fatal error if the processor does not support a test
498 mode (which is probably better than accidentally making real charges).
499
500 =head2 require_avs();
501
502 Providing a true argument to this module will turn on address
503 verification (if the processor supports it).
504
505 =head2 transaction_type();
506
507 Retrieve the transaction type (the 'type' argument to contents()).
508 Generally only used internally, but provided in case it is useful.
509
510 =head2 error_message();
511
512 If the transaction has been submitted but was not accepted, this
513 function will return the provided error message (if any) that the
514 processor returned.
515
516 =head2 authorization();
517
518 If the transaction has been submitted and accepted, this function will
519 provide you with the authorization code that the processor returned.
520
521 =head2 server();
522
523 Retrieve or change the processor submission server address (CHANGE AT
524 YOUR OWN RISK).
525
526 =head2 port();
527
528 Retrieve or change the processor submission port (CHANGE AT YOUR OWN
529 RISK).
530
531 =head2 path();
532
533 Retrieve or change the processor submission path (CHANGE AT YOUR OWN
534 RISK).
535
536 =head2 fraud_score();
537
538 Retrieve or change the fraud score from any Business::FraudDetect plugin
539
540 =head2 fraud_transaction_id();
541
542 Retrieve or change the transaction id from any Business::FraudDetect plugin
543
544 =head1 AUTHORS
545
546 Jason Kohles, email@jasonkohles.com
547
548 (v3 rewrite) Ivan Kohler <ivan-business-onlinepayment@420.am>
549
550 Phil Lobbes E<lt>phil at perkpartners dot comE<gt>
551
552 =head1 MAILING LIST
553
554 Please direct current development questions, patches, etc. to the mailing list:
555 http://420.am/cgi-bin/mailman/listinfo/bop-devel/
556
557 =head1 DISCLAIMER
558
559 THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
560 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
561 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
562
563 =head1 SEE ALSO
564
565 http://420.am/business-onlinepayment/
566
567 For verification of credit card checksums, see L<Business::CreditCard>.
568
569 =cut