doc: list a bunch of previously undocumented fields
[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_06';
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 );
31
32 sub new {
33     my($class,$processor,%data) = @_;
34
35     Carp::croak("unspecified processor") unless $processor;
36
37     my $subclass = "${class}::$processor";
38     if(!defined(&$subclass)) {
39         eval "use $subclass";
40         Carp::croak("unknown processor $processor ($@)") if $@;
41     }
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();
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         if ( $risk_transaction->fraud_score <= $self->maximum_fraud_score()) {
84             return 1;
85         } else {
86             $self->error_message('Excessive risk from risk management');
87         }
88     } else {
89         $self->error_message('Error in risk detection stage: ' .  $risk_transaction->error_message);
90     }
91     $self->is_success(0);
92     return 0;
93 }
94
95 my @Fraud_Class_Path = qw(Business::OnlinePayment Business::FraudDetect);
96
97 sub _pre_submit {
98     my ($self) = @_;
99     my $fraud_detection = $self->fraud_detect();
100
101     # early return if user does not want optional risk mgt
102     return 1 unless $fraud_detection;
103
104     # Search for an appropriate FD module
105     foreach my $fraud_class ( @Fraud_Class_Path ) {
106         my $subclass = $fraud_class . "::" . $fraud_detection;
107         if (!defined(&$subclass)) {
108             eval "use $subclass ()";
109             if ($@) {
110                 Carp::croak("error loading fraud_detection module ($@)")
111                       unless ( $@ =~ m/^Can\'t locate/ );
112             } else {
113                 my $risk_tx = bless ( { processor => $fraud_detection } , $subclass );
114                 $risk_tx->build_subs(keys %fields);
115                 if ($risk_tx->can('set_defaults')) {
116                     $risk_tx->set_defaults();
117                 }
118                 $risk_tx->_glean_parameters_from_parent($self);
119                 return $self->_risk_detect($risk_tx);
120             }
121         }
122     }
123     Carp::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     Carp::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     Carp::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 =head3 GENERAL TRANSACTION FIELDS
266
267 =item * type
268
269 Transaction type, supported types are: CC (credit card), ECHECK (electronic
270 check) and LEC (phone bill billing).  Deprecated types are: Visa, MasterCard,
271 American Express, Discover, Check (not all processors support all these
272 transaction types).
273
274 =item * action
275
276 What to do with the transaction (currently available are: Normal
277 Authorization, Authorization Only, Credit, Post Authorization)
278
279 =item * description
280
281 A description of the transaction (used by some processors to send
282 information to the client, normally not a required field).
283
284 =item * amount
285
286 The amount of the transaction, most processors don't want dollar signs
287 and the like, just a floating point number.
288
289 =item * invoice_number
290
291 An invoice number, for your use and not normally required, many
292 processors require this field to be a numeric only field.
293
294 =head3 CUSTOMER INFO FIELDS
295
296 =item * customer_id
297
298 A customer identifier, again not normally required.
299
300 =item * name
301
302 The customer's name, your processor may not require this.
303
304 =item * first_name
305
306 =item * last_name
307
308 The customer's first and last name as separate fields.
309
310 =item * company
311
312 The customer's company name, not normally required.
313
314 =item * address
315
316 The customer's address (your processor may not require this unless you
317 are requiring AVS Verification).
318
319 =item * city
320
321 The customer's city (your processor may not require this unless you are
322 requiring AVS Verification).
323
324 =item * state
325
326 The customer's state (your processor may not require this unless you
327 are requiring AVS Verification).
328
329 =item * zip
330
331 The customer's zip code (your processor may not require this unless you
332 are requiring AVS Verification).
333
334 =item * country
335
336 Customer's country.
337
338 =item * ship_first_name
339
340 =item * ship_last_name
341
342 =item * ship_company
343
344 =item * ship_address
345
346 =item * ship_city
347
348 =item * ship_state
349
350 =item * ship_zip
351
352 =item * ship_country
353
354 These shipping address fields may be accepted by your processor.  Refer to the
355 description for the corresponding non-ship field for general information on
356 each field.
357
358 =item * phone
359
360 Customer's phone number.
361
362 =item * fax
363
364 Customer's fax number.
365
366 =item * email
367
368 Customer's email address.
369
370 =head3 CREDIT CARD FIELDS
371
372 =item * card_number
373
374 Credit card number (obviously not required for non-credit card
375 transactions).
376
377 =item * cvv2
378
379 CVV2 number (also called CVC2 or CID) is a three- or four-digit security code
380 used to reduce credit card fraud.
381
382 =item * expiration
383
384 Credit card expiration (obviously not required for non-credit card
385 transactions).
386
387 =item * recurring billing
388
389 Recurring billing flag
390
391 =head3 ELECTRONIC CHECK FIELDS
392
393 =item * account_number
394
395 Bank account number for electronic checks or electronic funds transfer.
396
397 =item * routing_code
398
399 Bank's routing code for electronic checks or electronic funds transfer.
400
401 =item * account_type
402
403 Account type for electronic checks or electronic funds transfer.
404
405 =item * account_name
406
407 Account holder's name for electronic checks or electronic funds transfer.
408
409 =item * bank_name
410
411 Bank's name for electronic checks or electronic funds transfer.
412
413 =item * check_type
414
415 Check type for electronic checks or electronic funds transfer.
416
417 =item * customer_org
418
419 Customer organization type.
420
421 =item * customer_ssn
422
423 Customer's social security number.  Typically only required for electronic
424 checks or electronic funds transfer.
425
426 =item * license_num
427
428 Customer's driver's license number.  Typically only required for electronic
429 checks or electronic funds transfer.
430
431 =item * license_dob
432
433 Customer's date of birth.  Typically only required for electronic
434 checks or electronic funds transfer.
435
436 =back
437
438 =head2 submit();
439
440 Submit the transaction to the processor for completion
441
442 =head2 is_success();
443
444 Returns true if the transaction was submitted successfully, false if
445 it failed (or undef if it has not been submitted yet).
446
447 =head2 failure_status();
448
449 If the transaction failed, it can optionally return a specific
450 failure status (normalized, not gateway-specific).  Currently defined
451 statuses are: "expired", "nsf" (non-sufficient funds), "stolen",
452 "pickup", "blacklisted" and "declined" (card/transaction declines
453 only, not other errors).
454
455 Note that (as of Aug 2006) this is only supported by some of the
456 newest processor modules, and that, even if supported, a failure
457 status is an entirely optional field that is only set for specific
458 kinds of failures.
459
460 =head2 result_code();
461
462 Returns the precise result code that the processor returned, these are
463 normally one letter codes that don't mean much unless you understand
464 the protocol they speak, you probably don't need this, but it's there
465 just in case.
466
467 =head2 test_transaction();
468
469 Most processors provide a test mode, where submitted transactions will
470 not actually be charged or added to your batch, calling this function
471 with a true argument will turn that mode on if the processor supports
472 it, or generate a fatal error if the processor does not support a test
473 mode (which is probably better than accidentally making real charges).
474
475 =head2 require_avs();
476
477 Providing a true argument to this module will turn on address
478 verification (if the processor supports it).
479
480 =head2 transaction_type();
481
482 Retrieve the transaction type (the 'type' argument to contents();).
483 Generally only used internally, but provided in case it is useful.
484
485 =head2 error_message();
486
487 If the transaction has been submitted but was not accepted, this
488 function will return the provided error message (if any) that the
489 processor returned.
490
491 =head2 authorization();
492
493 If the transaction has been submitted and accepted, this function will
494 provide you with the authorization code that the processor returned.
495
496 =head2 server();
497
498 Retrieve or change the processor submission server address (CHANGE AT
499 YOUR OWN RISK).
500
501 =head2 port();
502
503 Retrieve or change the processor submission port (CHANGE AT YOUR OWN RISK).
504
505 =head2 path();
506
507 Retrieve or change the processor submission path (CHANGE AT YOUR OWN RISK).
508
509 =head1 AUTHORS
510
511 Jason Kohles, email@jasonkohles.com
512
513 (v3 rewrite) Ivan Kohler <ivan-business-onlinepayment@420.am>
514
515 Phil Lobbes E<lt>phil at perkpartners dot comE<gt>
516
517 =head1 DISCLAIMER
518
519 THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
520 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
521 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
522
523 =head1 SEE ALSO
524
525 http://420.am/business-onlinepayment/
526
527 For verification of credit card checksums, see L<Business::CreditCard>.
528
529 =cut