Fix idiotic bug; start adding transret.php method for returns
[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.04';
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   my $xml_request;
110
111   if ($self->{_content}->{command} eq 'get_returns') {
112     # Setting get_returns overrides anything else.
113     $xml_request = XMLout($self->build($returns_request), KeepRoot => 1);
114   }
115   else {
116     # Error-check and prepare as a normal transaction.
117
118       eval {
119       # Return-with-error situations
120       croak "Unsupported transaction type: '" . $self->transaction_type . "'"
121         if(not $self->transaction_type =~ /^e?check$/i);
122
123       croak "Unsupported action: '" . $self->{_content}->{action} . "'"
124         if(!defined($self->_payment_type));
125
126       croak 'Test transactions not supported'
127         if($self->test_transaction());
128     };
129
130     if($@) {
131       $self->is_success(0);
132       $self->error_message($@);
133       return;
134     }
135     
136     $xml_request = XMLout($self->build($request), KeepRoot => 1);
137   }
138   $DB::single=1;
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   $DB::single = 1 if $DEBUG;
173
174   return;
175 }
176
177 sub get_returns {
178   my $self = shift;
179   my $content = $self->{_content};
180   if(exists($content->{'command'})) {
181     croak 'get_returns: command is already set on this transaction';
182   }
183   if ($content->{'returns_method'} eq 'transret') {
184     $Business::OnlinePayment::HTTPS::DEBUG = $DEBUG;
185     if (defined($content->{'login'}) and defined($content->{'password'})) {
186       # date range doesn't work quite right with transret
187       my $path = ('transret.php?style=csv&sort=id&date=');
188       my $starttime = str2time($self->_start);
189       my $endtime = str2time($self->_end) - 1;
190       $DB::single=1;
191       my @months = map { s/^(....)(..)$/$1-$2-01/; $_ } (
192           time2str('%Y%m', $starttime)..time2str('%Y%m', $endtime)
193           );
194       my $headers = { 
195          Authorization => 'Basic ' . MIME::Base64::encode($content->{'login'} . ':' . $content->{'password'}) 
196           };
197       my @tids;
198       foreach my $m (@months) {
199         $self->path($path . $m);
200         my ($page, $reply, %headers) = 
201             $self->https_get(
202               { headers => $headers },
203               {},
204             );
205         if ($reply =~ /^200/) {
206           $self->is_success(1);
207         }
208         else {
209           $self->error_message($reply);
210           carp $page if $DEBUG > 1;
211           $self->is_success(0);
212           return;
213         }
214         foreach my $trans (split("\cJ", $page)) {
215           my @fields = split(',', $trans);
216           # fields:
217           # id, Date Returned, Type, Amount, Name, Customer ID Number, Email Address, Invoice Number, Status Code, SEC
218           # we only care about id and date.
219           next if scalar(@fields) < 10;
220           next if not($fields[0] =~ /^\d+$/);
221           my $rettime = str2time($fields[1]);
222           next if (!$rettime or $rettime < $starttime or $rettime > $endtime);
223           carp $trans if $DEBUG > 1;
224           push @tids, $fields[0];
225         }
226       }
227       return @tids;
228     }
229     else {
230       croak 'login and password required';
231     }
232   } 
233   else {
234     $content->{'command'} = 'get_returns';
235     $self->submit;
236     if($self->is_success) {
237       if(exists($content->{'returns'})) {
238         return @{$content->{'returns'}};
239       }
240       else {
241         return ();
242       }
243     } else {
244     # you need to check error_message() for details.
245     return ();
246     }
247   }
248 }
249
250 sub build {
251   my $self = shift;
252     my $content = { $self->content };
253     my $skel = shift;
254     my $data;
255     if (ref($skel) ne 'HASH') { croak 'Failed to build non-hash' };
256     foreach my $k (keys(%$skel)) {
257       my $val = $skel->{$k};
258       # Rules for building from the skeleton:
259       # 1. If the value is a hashref, build it recursively.
260       if(ref($val) eq 'HASH') {
261         $data->{$k} = $self->build($val);
262       }
263       # 2. If the value starts with an underscore, it's treated as a method name.
264       elsif($val =~ /^_/ and $self->can($val)) {
265         $data->{$k} = $self->can($val)->($self);
266       }
267       # 3. If the value is undefined, keep it undefined.
268       elsif(!defined($val)) {
269         $data->{$k} = undef;
270       }
271       # 4. If the value is the name of a key in $self->content, look up that value.
272     elsif(exists($content->{$val})) {
273       $data->{$k} = $content->{$val};
274     }
275     # 5. If the value is a key in $defaults, use that value.
276     elsif(exists($defaults->{$val})) {
277       $data->{$k} = $defaults->{$val};
278     }
279     # 6. If the value is not required, use an empty string.
280     elsif(! $required->{$val}) {
281       $data->{$k} = '';
282     }
283     # 7. Fail.
284     else {
285       croak "Missing request field: '$val'";
286     }
287   }
288   return $data;
289 }
290
291 sub XML {
292   # For testing build().
293   my $self = shift;
294   return XMLout($self->build($request), KeepRoot => 1);
295 }
296
297 sub _payment_type {
298   my $self = shift;
299   my $action = $self->{_content}->{action};
300   if(!defined($action) or $action =~ /^normal authorization$/i) {
301     return 'debit';
302   }
303   elsif($action =~ /^credit$/i) {
304     return 'credit';
305   }
306   else {
307     return;
308   }
309 }
310
311 sub _check_type {
312   my $self = shift;
313   my $type = $self->{_content}->{account_type};
314   return 'checking' if($type =~ /checking/i);
315   return 'savings'  if($type =~ /savings/i);
316   croak "Invalid account_type: '$type'";
317 }
318
319 sub _full_name {
320   my $self = shift;
321   return join(' ',$self->{_content}->{first_name},$self->{_content}->{last_name});
322 }
323
324 sub _start {
325   my $self = shift;
326   if($self->{_content}->{start}) {
327     my $start = time2str('%Y-%m-%d', str2time($self->{_content}->{start}));
328     croak "Invalid start date: '".$self->{_content}->{start} if !$start;
329     return $start;
330   }
331   else {
332     return time2str('%Y-%m-%d', time - 86400);
333   }
334 }
335
336 sub _end {
337   my $self = shift;
338   my $end = $self->{_content}->{end};
339   if($end) {
340     $end = time2str('%Y-%m-%d', str2time($end));
341     croak "Invalid end date: '".$self->{_content}->{end} if !$end;
342     return $end;
343   }
344   else {
345     return time2str('%Y-%m-%d', time);
346   }
347 }
348
349 1;
350 __END__
351
352 =head1 NAME
353
354 Business::OnlinePayment::WesternACH - Western ACH backend for Business::OnlinePayment
355
356 =head1 SYNOPSIS
357
358   use Business::OnlinePayment;
359
360   ####
361   # Electronic check authorization.  We only support 
362   # 'Normal Authorization' and 'Credit'.
363   ####
364
365   my $tx = new Business::OnlinePayment("WesternACH");
366   $tx->content(
367       type           => 'ECHECK',
368       login          => 'testdrive',
369       password       => 'testpass',
370       action         => 'Normal Authorization',
371       description    => 'Business::OnlinePayment test',
372       amount         => '49.95',
373       invoice_number => '100100',
374       first_name     => 'Jason',
375       last_name      => 'Kohles',
376       address        => '123 Anystreet',
377       city           => 'Anywhere',
378       state          => 'UT',
379       zip            => '84058',
380       account_type   => 'personal checking',
381       account_number => '1000468551234',
382       routing_code   => '707010024',
383       check_number   => '1001', # optional
384   );
385   $tx->submit();
386
387   if($tx->is_success()) {
388       print "Check processed successfully: ".$tx->authorization."\n";
389   } else {
390       print "Check was rejected: ".$tx->error_message."\n";
391   }
392
393   my $tx = new Business::OnlinePayment("WesternACH");
394   $tx->content(
395       login     => 'testdrive',
396       password  => 'testpass',
397       start     => '2009-06-25', # optional; defaults to yesterday
398       end       => '2009-06-26', # optional; defaults to today
399       );
400   $tx->get_returns;
401   
402
403 =head1 SUPPORTED TRANSACTION TYPES
404
405 =head2 ECHECK
406
407 Content required: type, login, password|transaction_key, action, amount, first_name, last_name, account_number, routing_code, account_type.
408
409 =head1 DESCRIPTION
410
411 For detailed information see L<Business::OnlinePayment>.
412
413 =head1 METHODS AND FUNCTIONS
414
415 See L<Business::OnlinePayment> for the complete list. The following methods either override the methods in L<Business::OnlinePayment> or provide additional functions.  
416
417 =head2 result_code
418
419 Currently returns nothing; these transactions don't seem to have result codes.
420
421 =head2 error_message
422
423 Returns the response reason text.  This can come from several locations in the response document or from certain local errors.
424
425 =head2 server_response
426
427 Returns the complete response from the server.
428
429 =head1 Handling of content(%content) data:
430
431 =head2 action
432
433 The following actions are valid:
434
435   normal authorization
436   credit
437
438 =head1 AUTHOR
439
440 Mark Wells <mark@freeside.biz> with advice from Ivan Kohler <ivan-westernach@freeside.biz>.
441
442 =head1 SEE ALSO
443
444 perl(1). L<Business::OnlinePayment>.
445
446 =cut
447