Use new get_returns method by default
[Business-OnlinePayment-WesternACH.git] / lib / Business / OnlinePayment / WesternACH.pm
1 package Business::OnlinePayment::WesternACH;
2
3 use strict;
4 use Carp;
5 use Business::OnlinePayment 3;
6 use Business::OnlinePayment::HTTPS;
7 use XML::Simple;
8 use MIME::Base64;
9 use Date::Format 'time2str';
10 use Date::Parse  'str2time';
11 use vars qw($VERSION @ISA $me $DEBUG);
12
13 @ISA = qw(Business::OnlinePayment::HTTPS);
14 $VERSION = '0.06';
15 $me = 'Business::OnlinePayment::WesternACH';
16
17 $DEBUG = 0;
18
19 my $defaults = {
20   command      => 'payment',
21   check_ver    => 'yes',
22   sec_code     => 'PPD',
23   tender_type  => 'check',
24   check_number => 9999,
25   schedule     => 'live',
26 };
27
28 my $required = { map { $_ => 1 } ( qw(
29   login
30   password
31   command
32   amount
33   tender_type
34   _full_name
35   routing_code
36   check_number
37   _check_type 
38 ))};
39
40
41
42 # Structure of the XML request document
43 # Right sides of the hash entries are Business::OnlinePayment 
44 # field names.  Those that start with _ are local method names.
45
46 my $auth = {
47 Authentication => {
48   username => 'login',
49   password => 'password',
50 }
51 };
52
53 my $request = {
54 TransactionRequest => {
55   %$auth,
56   Request => {
57     command => 'command',
58     Payment => {
59       type   => '_payment_type',
60       amount => 'amount',
61       # effective date: not supported
62       Tender => {
63         type   => 'tender_type',
64         amount => 'amount',
65         InvoiceNumber => { value => 'invoice_number' },
66         AccountHolder => { value => '_full_name'      },
67         Address       => { value => 'address'       },
68         ClientID      => { value => 'customer_id'    },
69         UserDefinedID => { value => 'email' },
70         CheckDetails => {
71           routing      => 'routing_code',
72           account      => 'account_number',
73           check        => 'check_number',
74           type         => '_check_type',
75           verification => 'check_ver',
76         },
77         Authorization => { schedule => 'schedule' },
78         SECCode => { value => 'sec_code' },
79       },
80     },
81   }
82 }
83 };
84
85 my $returns_request = {
86 TransactionRequest => {
87   %$auth,
88   Request => {
89     command => 'command',
90     DateRange => {
91       start => '_start',
92       end   => '_end',
93     },
94   },
95 }
96 };
97
98 sub set_defaults {
99   my $self = shift;
100   $self->server('www.webcheckexpress.com');
101   $self->port(443);
102   $self->path('/requester.php');
103   return;
104 }
105
106 sub submit {
107   my $self = shift;
108   $Business::OnlinePayment::HTTPS::DEBUG = $DEBUG;
109   $DB::single = $DEBUG; # If you're debugging this, you probably want to stop here.
110   my $xml_request;
111
112   if ($self->{_content}->{command} eq 'get_returns') {
113     # Setting get_returns overrides anything else.
114     $xml_request = XMLout($self->build($returns_request), KeepRoot => 1);
115   }
116   else {
117     # Error-check and prepare as a normal transaction.
118
119       eval {
120       # Return-with-error situations
121       croak "Unsupported transaction type: '" . $self->transaction_type . "'"
122         if(not $self->transaction_type =~ /^e?check$/i);
123
124       croak "Unsupported action: '" . $self->{_content}->{action} . "'"
125         if(!defined($self->_payment_type));
126
127       croak 'Test transactions not supported'
128         if($self->test_transaction());
129     };
130
131     if($@) {
132       $self->is_success(0);
133       $self->error_message($@);
134       return;
135     }
136     
137     $xml_request = XMLout($self->build($request), KeepRoot => 1);
138   }
139   my ($xml_reply, $response, %reply_headers) = $self->https_post({ 'Content-Type' => 'text/xml' }, $xml_request);
140   
141   if(not $response =~ /^200/) {
142     croak "HTTPS error: '$response'";
143   }
144
145   $self->server_response($xml_reply);
146   my $reply = XMLin($xml_reply, KeepRoot => 1)->{TransactionResponse};
147
148   if(exists($reply->{Response})) {
149     $self->is_success( ( $reply->{Response}->{status} eq 'successful') ? 1 : 0);
150     $self->error_message($reply->{Response}->{ErrorMessage});
151     if(exists($reply->{Response}->{TransactionID})) {
152       # get_returns puts its results here
153       my $tid = $reply->{Response}->{TransactionID};
154       if($self->{_content}->{command} eq 'get_returns') {
155         if(ref($tid) eq 'ARRAY') {
156           $self->{_content}->{returns} =  [ map { $_->{value} } @$tid ];
157         }
158         else {
159           $self->{_content}->{returns} = [ $tid->{value} ];
160         }
161       }
162       else { # It's not get_returns
163         $self->authorization($tid->{value});
164       }
165     }
166   }
167   elsif(exists($reply->{FatalException})) {
168     $self->is_success(0);
169     $self->error_message($reply->{FatalException});
170   }
171
172
173   return;
174 }
175
176 sub get_returns {
177   my $self = shift;
178   my $content = $self->{_content};
179   if(exists($content->{'command'})) {
180     croak 'get_returns: command is already set on this transaction';
181   }
182   if ($content->{'returns_method'} eq 'requester') {
183 # Obsolete, deprecated method supported for now as a fallback option.
184     $content->{'command'} = 'get_returns';
185     $self->submit;
186     if($self->is_success) {
187       if(exists($content->{'returns'})) {
188         return @{$content->{'returns'}};
189       }
190       else {
191         return ();
192       }
193     }
194     # you need to check error_message() for details.
195     return ();
196   }
197   else {
198     $Business::OnlinePayment::HTTPS::DEBUG = $DEBUG;
199     $DB::single = $DEBUG;
200     if (defined($content->{'login'}) and defined($content->{'password'})) {
201       # transret.php doesn't respect date ranges.  It returns anything from the 
202       # same month as the date argument.  Therefore we generate one request for 
203       # each month in the date range, and then filter them by date later.
204       my $path = ('transret.php?style=csv&sort=id&date=');
205       my $starttime = str2time($self->_start);
206       my $endtime = str2time($self->_end) - 1;
207       my @months = map { s/^(....)(..)$/$1-$2-01/; $_ } (
208           time2str('%Y%m', $starttime)..time2str('%Y%m', $endtime)
209           );
210       my $headers = { 
211          Authorization => 'Basic ' . MIME::Base64::encode($content->{'login'} . ':' . $content->{'password'}) 
212           };
213       my @tids;
214       foreach my $m (@months) {
215         $self->path($path . $m);
216         # B:OP:HTTPS::https_get doesn't use $DEBUG.
217         my ($page, $reply, %headers) = 
218             $self->https_get(
219               { headers => $headers },
220               {},
221             );
222         if ($reply =~ /^200/) {
223           $self->is_success(1);
224         }
225         else {
226           $self->error_message($reply);
227           carp $reply if $DEBUG;
228           carp $page if $DEBUG >= 3;
229           $self->is_success(0);
230           return;
231         }
232         foreach my $trans (split("\cJ", $page)) {
233           my @fields = split(',', $trans);
234           # fields:
235           # id, Date Returned, Type, Amount, Name, Customer ID Number,
236           # Email Address, Invoice Number, Status Code, SEC
237
238           # we only care about id and date.
239           next if scalar(@fields) < 10;
240           next if not($fields[0] =~ /^\d+$/);
241           my $rettime = str2time($fields[1]);
242           next if (!$rettime or $rettime < $starttime or $rettime > $endtime);
243           carp $trans if $DEBUG > 1;
244           push @tids, $fields[0];
245         }
246       }
247       return @tids;
248     }
249     else {
250       croak 'login and password required';
251     }
252   } 
253 }
254
255 sub build {
256   my $self = shift;
257     my $content = { $self->content };
258     my $skel = shift;
259     my $data;
260     if (ref($skel) ne 'HASH') { croak 'Failed to build non-hash' };
261     foreach my $k (keys(%$skel)) {
262       my $val = $skel->{$k};
263       # Rules for building from the skeleton:
264       # 1. If the value is a hashref, build it recursively.
265       if(ref($val) eq 'HASH') {
266         $data->{$k} = $self->build($val);
267       }
268       # 2. If the value starts with an underscore, it's treated as a method name.
269       elsif($val =~ /^_/ and $self->can($val)) {
270         $data->{$k} = $self->can($val)->($self);
271       }
272       # 3. If the value is undefined, keep it undefined.
273       elsif(!defined($val)) {
274         $data->{$k} = undef;
275       }
276       # 4. If the value is the name of a key in $self->content, look up that value.
277     elsif(exists($content->{$val})) {
278       $data->{$k} = $content->{$val};
279     }
280     # 5. If the value is a key in $defaults, use that value.
281     elsif(exists($defaults->{$val})) {
282       $data->{$k} = $defaults->{$val};
283     }
284     # 6. If the value is not required, use an empty string.
285     elsif(! $required->{$val}) {
286       $data->{$k} = '';
287     }
288     # 7. Fail.
289     else {
290       croak "Missing request field: '$val'";
291     }
292   }
293   return $data;
294 }
295
296 sub XML {
297   # For testing build().
298   my $self = shift;
299   return XMLout($self->build($request), KeepRoot => 1);
300 }
301
302 sub _payment_type {
303   my $self = shift;
304   my $action = $self->{_content}->{action};
305   if(!defined($action) or $action =~ /^normal authorization$/i) {
306     return 'debit';
307   }
308   elsif($action =~ /^credit$/i) {
309     return 'credit';
310   }
311   else {
312     return;
313   }
314 }
315
316 sub _check_type {
317   my $self = shift;
318   my $type = $self->{_content}->{account_type};
319   return 'checking' if($type =~ /checking/i);
320   return 'savings'  if($type =~ /savings/i);
321   croak "Invalid account_type: '$type'";
322 }
323
324 sub _full_name {
325   my $self = shift;
326   return join(' ',$self->{_content}->{first_name},$self->{_content}->{last_name});
327 }
328
329 sub _start {
330   my $self = shift;
331   if($self->{_content}->{start}) {
332     my $start = time2str('%Y-%m-%d', str2time($self->{_content}->{start}));
333     croak "Invalid start date: '".$self->{_content}->{start} if !$start;
334     return $start;
335   }
336   else {
337     return time2str('%Y-%m-%d', time - 86400);
338   }
339 }
340
341 sub _end {
342   my $self = shift;
343   my $end = $self->{_content}->{end};
344   if($end) {
345     $end = time2str('%Y-%m-%d', str2time($end));
346     croak "Invalid end date: '".$self->{_content}->{end} if !$end;
347     return $end;
348   }
349   else {
350     return time2str('%Y-%m-%d', time);
351   }
352 }
353
354 1;
355 __END__
356
357 =head1 NAME
358
359 Business::OnlinePayment::WesternACH - Western ACH backend for Business::OnlinePayment
360
361 =head1 SYNOPSIS
362
363   use Business::OnlinePayment;
364
365   ####
366   # Electronic check authorization.  We only support 
367   # 'Normal Authorization' and 'Credit'.
368   ####
369
370   my $tx = new Business::OnlinePayment("WesternACH");
371   $tx->content(
372       type           => 'ECHECK',
373       login          => 'testdrive',
374       password       => 'testpass',
375       action         => 'Normal Authorization',
376       description    => 'Business::OnlinePayment test',
377       amount         => '49.95',
378       invoice_number => '100100',
379       first_name     => 'Jason',
380       last_name      => 'Kohles',
381       address        => '123 Anystreet',
382       city           => 'Anywhere',
383       state          => 'UT',
384       zip            => '84058',
385       account_type   => 'personal checking',
386       account_number => '1000468551234',
387       routing_code   => '707010024',
388       check_number   => '1001', # optional
389   );
390   $tx->submit();
391
392   if($tx->is_success()) {
393       print "Check processed successfully: ".$tx->authorization."\n";
394   } else {
395       print "Check was rejected: ".$tx->error_message."\n";
396   }
397
398   my $tx = new Business::OnlinePayment("WesternACH");
399   $tx->content(
400       login     => 'testdrive',
401       password  => 'testpass',
402       start     => '2009-06-25', # optional; defaults to yesterday
403       end       => '2009-06-26', # optional; defaults to today
404       );
405   $tx->get_returns;
406   
407
408 =head1 SUPPORTED TRANSACTION TYPES
409
410 =head2 ECHECK
411
412 Content required: type, login, password|transaction_key, action, amount, first_name, last_name, account_number, routing_code, account_type.
413
414 =head1 DESCRIPTION
415
416 For detailed information see L<Business::OnlinePayment>.
417
418 =head1 METHODS AND FUNCTIONS
419
420 See L<Business::OnlinePayment> for the complete list. The following methods either override the methods in L<Business::OnlinePayment> or provide additional functions.  
421
422 =head2 result_code
423
424 Currently returns nothing; these transactions don't seem to have result codes.
425
426 =head2 error_message
427
428 Returns the response reason text.  This can come from several locations in the response document or from certain local errors.
429
430 =head2 server_response
431
432 Returns the complete response from the server.
433
434 =head1 Handling of content(%content) data:
435
436 =head2 action
437
438 The following actions are valid:
439
440   normal authorization
441   credit
442
443 =head1 AUTHOR
444
445 Mark Wells <mark@freeside.biz> with advice from Ivan Kohler <ivan-westernach@freeside.biz>.
446
447 =head1 SEE ALSO
448
449 perl(1). L<Business::OnlinePayment>.
450
451 =cut
452