- Removed some old commented out 2.x statements
[Business-OnlinePayment.git] / OnlinePayment.pm
1 package Business::OnlinePayment;
2
3 use strict;
4 use vars qw($VERSION);
5 use Carp;
6 use Symbol;
7
8 require 5.005;
9
10 $VERSION = '3.00_04';
11 $VERSION = eval $VERSION; # modperlstyle: convert the string into a number
12
13 my %fields = (
14     is_success       => undef,
15     failure_status   => undef,
16     result_code      => undef,
17     test_transaction => undef,
18     require_avs      => undef,
19     transaction_type => undef,
20     error_message    => undef,
21     authorization    => undef,
22     server           => undef,
23     port             => undef,
24     path             => undef,
25     fraud_detect     => undef,
26     server_response  => undef,
27     maximum_risk     => undef,
28 );
29
30
31 sub new {
32     my($class,$processor,%data) = @_;
33
34     Carp::croak("unspecified processor") unless $processor;
35
36     my $subclass = "${class}::$processor";
37     if(!defined(&$subclass)) {
38         eval "use $subclass";
39         Carp::croak("unknown processor $processor ($@)") if $@;
40     }
41
42     my $self = bless {processor => $processor}, $subclass;
43     $self->build_subs(keys %fields);
44
45     if($self->can("set_defaults")) {
46         $self->set_defaults();
47     }
48
49     foreach(keys %data) {
50         my $key = lc($_);
51         my $value = $data{$_};
52         $key =~ s/^\-+//;
53         $self->build_subs($key);
54         $self->$key($value);
55     }
56
57     {
58         no strict 'refs';
59         no warnings 'redefine';
60         my $submit = qualify_to_ref('submit', $subclass);
61         $self->{_child_submit} = \&$submit;
62         *{"${subclass}::submit"} = sub {
63             my $self = shift;
64             $self->_pre_submit();
65
66         }
67     }
68
69     return $self;
70 }
71
72 sub _risk_detect {
73     my ($self, $risk_transaction) = @_;
74
75     my %parent_content = $self->content();
76     $parent_content{action} = 'Fraud Detect';
77     $risk_transaction->content( %parent_content ); 
78     $risk_transaction->submit();
79     if ($risk_transaction->is_success()) {
80         if ( $risk_transaction->fraud_score <= $self->maximum_fraud_score()) {
81             $self->{_child_submit}->($self);
82         } else {
83             $self->is_success(0);
84             $self->error_message('Excessive risk from risk management');
85         }
86     } else {
87         $self->error_message('Error in risk detection stage: ' .  $risk_transaction->error_message);
88         $self->is_success(0);
89     }
90 }
91
92 sub _pre_submit{
93     my ($self) = @_;
94     my $fraud_detection = $self->fraud_detect();
95
96     #
97     # early return if user does not want optional risk mgt
98     #
99
100     return $self->{_child_submit}->($self,@_) unless $fraud_detection && length $fraud_detection;
101
102     #
103
104     # Search for an appropriate FD module
105     #
106     
107     foreach my $subclass ( q(Business::OnlinePayment::) . $fraud_detection,
108                            q(Business::FraudDetect::).$fraud_detection) {
109
110         if (!defined(&$subclass)) {
111             eval "use $subclass";
112             if ($@) {
113                 Carp::croak("serious problem loading fraud_detection module ($@)") unless
114                     $@ =~ m/^Can\'t locate/;
115             } else {
116                 my $risk_tx = bless ( { processor => $fraud_detection } , $subclass );
117                 $risk_tx->build_subs(keys %fields);
118                 if ($risk_tx->can('set_defaults')) {
119                     $risk_tx->set_defaults();
120                 }
121                 $risk_tx->_glean_parameters_from_parent($self);
122                 return $self->_risk_detect($risk_tx);
123             }
124         }
125     }
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(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 through
231 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, and defines the online processor to use.  If necessary, processor options can be specified, currently supported options are 'Server', 'Port', and 'Path', which specify how to find the online processor (https://server:port/path), but individual processor modules should supply reasonable defaults for this information, override the defaults only if absolutely necessary (especially path), as the processor module was probably written with a specific target script in mind.
238
239 =head2 content(%content);
240
241 The information necessary for the transaction, this tends to vary a little depending on the processor, so we have chosen to use a system which defines specific fields in the frontend which get mapped to the correct fields in the backend.  The currently defined fields are:
242
243 =over 4
244
245 =item * type
246
247 Transaction type, supported types are:
248 Visa, MasterCard, American Express, Discover, Check (not all processors support all these transaction types).
249
250 =item * login
251
252 Your login name to use for authentication to the online processor.
253
254 =item * password
255
256 Your password to use for authentication to the online processor.
257
258 =item * action
259
260 What to do with the transaction (currently available are: Normal Authorization, Authorization Only, Credit, Post Authorization)
261
262 =item * description
263
264 A description of the transaction (used by some processors to send information to the client, normally not a required field).
265
266 =item * amount
267
268 The amount of the transaction, most processors dont want dollar signs and the like, just a floating point number.
269
270 =item * invoice_number
271
272 An invoice number, for your use and not normally required, many processors require this field to be a numeric only field.
273
274 =item * customer_id
275
276 A customer identifier, again not normally required.
277
278 =item * name
279
280 The customers name, your processor may not require this.
281
282 =item * address
283
284 The customers address (your processor may not require this unless you are requiring AVS Verification).
285
286 =item * city
287
288 The customers city (your processor may not require this unless you are requiring AVS Verification).
289
290 =item * state
291
292 The customers state (your processor may not require this unless you are requiring AVS Verification).
293
294 =item * zip
295
296 The customers zip code (your processor may not require this unless you are requiring AVS Verification).
297
298 =item * country
299
300 Customer's country.
301
302 =item * phone
303
304 Customer's phone number.
305
306 =item * fax
307
308 Customer's fax number.
309
310 =item * email
311
312 Customer's email address.
313
314 =item * card_number
315
316 Credit card number (obviously not required for non-credit card transactions).
317
318 =item * exp_date
319
320 Credit card expiration (obviously not required for non-credit card transactions).
321
322 =item * account_number
323
324 Bank account number for electronic checks or electronic funds transfer.
325
326 =item * routing_code
327
328 Bank's routing code for electronic checks or electronic funds transfer.
329
330 =item * bank_name
331
332 Bank's name for electronic checks or electronic funds transfer.
333
334 =back
335
336 =head2 submit();
337
338 Submit the transaction to the processor for completion
339
340 =head2 is_success();
341
342 Returns true if the transaction was submitted successfully, false if it failed (or undef if it has not been submitted yet).
343
344 =head2 failure_status();
345
346 If the transactdion failed, it can optionally return a specific failure status
347 (normalized, not gateway-specific).  Currently defined statuses are: "expired",
348 "nsf" (non-sufficient funds), "stolen", "pickup", "blacklisted" and
349 "declined" (card/transaction declines only, not other errors).
350
351 Note that (as of Aug 2006) this is only supported by some of the newest
352 processor modules, and that, even if supported, a failure status is an entirely
353 optional field that is only set for specific kinds of failures.
354
355 =head2 result_code();
356
357 Returns the precise result code that the processor returned, these are normally one letter codes that don't mean much unless you understand the protocol they speak, you probably don't need this, but it's there just in case.
358
359 =head2 test_transaction();
360
361 Most processors provide a test mode, where submitted transactions will not actually be charged or added to your batch, calling this function with a true argument will turn that mode on if the processor supports it, or generate a fatal error if the processor does not support a test mode (which is probably better than accidentally making real charges).
362
363 =head2 require_avs();
364
365 Providing a true argument to this module will turn on address verification (if the processor supports it).
366
367 =head2 transaction_type();
368
369 Retrieve the transaction type (the 'type' argument to contents();).  Generally only used internally, but provided in case it is useful.
370
371 =head2 error_message();
372
373 If the transaction has been submitted but was not accepted, this function will return the provided error message (if any) that the processor returned.
374
375 =head2 authorization();
376
377 If the transaction has been submitted and accepted, this function will provide you with the authorization code that the processor returned.
378
379 =head2 server();
380
381 Retrieve or change the processor submission server address (CHANGE AT YOUR OWN RISK).
382
383 =head2 port();
384
385 Retrieve or change the processor submission port (CHANGE AT YOUR OWN RISK).
386
387 =head2 path();
388
389 Retrieve or change the processor submission path (CHANGE AT YOUR OWN RISK).
390
391 =head1 AUTHORS
392
393 Jason Kohles, email@jasonkohles.com
394
395 (v3 rewrite) Ivan Kohler <ivan-business-onlinepayment@420.am>
396
397 =head1 DISCLAIMER
398
399 THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
400 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
401 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
402
403
404 =head1 SEE ALSO
405
406 http://420.am/business-onlinepayment/
407
408 For verification of credit card checksums, see L<Business::CreditCard>.
409
410 =cut