RT72219, calculate process date using upstream date
[Business-BatchPayment-BillBuddy.git] / BillBuddy.pm
1 package Business::BatchPayment::BillBuddy;
2
3 use strict;
4
5 =head1 NAME
6
7 Business::BatchPayment::BillBuddy - BillBuddy batch payment format and transport
8
9 =head1 USAGE
10
11 See L<Business::BatchPayment> for general usage notes.
12
13 =head2 SYNOPSIS
14
15         use Business::BatchPayment;
16
17         # Upload batch
18         my @items = Business::BatchPayment::Item->new( ... );
19         my $batch = Business::BatchPayment->create(Batch =>
20           batch_id  => $self->batchnum,
21           items     => \@items
22         );
23
24         my $processor = Business::BatchPayment->processor('BillBuddy',
25           login         => 'USER_ID',
26           password      => 'API_KEY',
27           host          => 'xmlrpc.billbuddy.com',
28           path          => 'v1_sandbox',
29           #optional...
30           port          => 443,
31           debug         => 1,
32         );
33
34         my $result = $processor->submit($batch);
35
36         # this gets set by submit, and is needed for receive
37         my $processor_id = $batch->processor_id;
38
39         # Download results
40         my @reply = $processor->receive(@process_ids);
41
42 =head2 PROCESSOR ATTRIBUTES
43
44 =over 4
45
46 =item username - the user_id provided to you by BillBuddy
47
48 =item password - the api_key (NOT the web portal password) provided to you by BillBuddy
49
50 =item host - the domain name for BillBuddy XMLRPC requests
51
52 =item path - the path for BillBuddy XMLRPC requests
53
54 =item port - the port for BillBuddy XMLRPC requests (optional, default 443)
55
56 =item debug - print debug warnings if true, including XML requests and responses
57
58 =back
59
60 =head1 AUTHOR
61
62 Jonathan Prykop, jonathan@freeside.biz
63
64 =head1 SUPPORT
65
66 You can find documentation for this module with the perldoc command.
67
68     perldoc Business::BatchPayment::BillBuddy
69
70 Commercial support is available from Freeside Internet Services,
71 L<http://www.freeside.biz> 
72
73 =head1 LICENSE AND COPYRIGHT
74
75 Copyright 2015 Freeside Internet Services
76
77 This program is free software; you can redistribute it and/or modify it
78 under the terms of either: the GNU General Public License as published
79 by the Free Software Foundation; or the Artistic License.
80
81 See http://dev.perl.org/licenses/ for more information.
82
83 =cut
84
85 use Business::BatchPayment;
86 use DateTime;
87 use Moose;
88 with 'Business::BatchPayment::Processor';
89
90 our $VERSION = '0.03';
91
92 has [ qw(username password) ] => (
93    is  => 'ro',
94    isa => 'Str',
95 );
96
97 has 'host' => (
98    is  => 'ro',
99    isa => 'Str',
100    default => 'xmlrpc.billbuddy.com',
101 );
102
103 has 'path' => (
104    is  => 'ro',
105    isa => 'Str',
106    default => '/',
107 );
108
109 has 'port' => (
110    is  => 'ro',
111    isa => 'Str',
112    default => '443',
113 );
114
115 sub default_transport {
116   my $self = shift;
117   Business::BatchPayment->create('BillBuddy::Transport',
118     username      => $self->username,
119     password      => $self->password,
120     host          => $self->host,
121     port          => $self->port,
122     path          => $self->path,
123     debug         => $self->debug,
124   );
125 }
126
127 sub format_item {
128   my ($self,$item,$batch) = @_;
129   #Position Length Content
130   #1-1 1 "D" 
131   my $line = 'D';
132   #2-17 16 Reference Number  
133   $line .= sprintf("%-16s",$item->tid);
134   #18-18 1 blank, filled with space 
135   $line .= ' ';
136   #19-28 10 amount, numbers only, by cents, zero padded to the left 
137   $line .= sprintf("%10s",$item->amount * 100);
138   #29-30 2 blank, filled with spaces 
139   $line .= '  ';
140   #31-32 2 account type: "BC" for bank account, "CC" for credit card account 
141   my $pt = $item->payment_type;
142   if ($pt eq 'CC') {
143     #we currently don't support CC, but leaving the code in place for future development
144     die 'Business::BatchPayment::BillBuddy currently does not handle credit card transactions';
145     $line .= 'CC';
146   } elsif ($pt eq 'ECHECK') {
147     $line .= 'BC';
148   } else {
149     die "Unknown payment type";
150   }
151   #33-33 1 blank 
152   $line .= ' ';
153   #34-40 7 BSB for bank account, formatted in 000-000. blank for credit card account 
154   my $bsb = ($pt eq 'CC') ? sprintf("%7s",'') : $item->routing_code;
155   $bsb =~ s/^(\d{3})(\d{3})/$1\-$2/;
156   die "Bad routing code $bsb" if ($pt ne 'CC') && ($bsb !~ /^\d{3}\-\d{3}$/);
157   $line .= $bsb;
158   #41-41 1 blank 
159   $line .= ' ';
160   #42-50 9 Account number for bank accounts. blank for credit card account 
161   my $anum = ($pt eq 'CC') ? sprintf("%9s",'') : sprintf("%09s",$item->account_number);
162   $line .= $anum;
163   #51-66 16 credit card number, left padded with zero if less than 16 digits. Blank for bank accounts 
164   my $cnum = ($pt eq 'CC') ? sprintf("%016s",$item->card_number) : sprintf("%16s",'');
165   $line .= $cnum;
166   #67-98 32 bank account name or name on the credit card 
167   my $name = $item->first_name . ' ' . $item->last_name;
168   $line .= sprintf("%-32.32s",$name);
169   #99-99 1 blank 
170   $line .= ' ';
171   #100-103 4 credit card expiry date, formatted as mmdd. "0000" for bank account. 
172   my $exp = ($pt eq 'CC') ? $item->expiration : '';
173   $line .= sprintf("%04s",$exp);
174   #104-104 1 blank 
175   #105-111 7 reserved, always "0000000" 
176   #112-114 3 reserved, blank 
177   $line .= ' 0000000   ';
178   #115-120 6 line number, left padded with zero
179   $line .= sprintf("%06s",$batch->num);
180   $line .= "\n";
181   return $line;
182 }
183
184 #overriding this just to be able to pass batch to upload
185 #but maybe this should go in standard module?
186 sub submit {
187   my $self = shift;
188   my $batch = shift;
189   my $request = $self->format_request($batch);
190   $self->transport->upload($request,$batch);
191 }
192
193 #overriding this to pass process_ids to download,
194 #but maybe this should go in standard module?
195 sub receive {
196   my $self = shift;
197   return $self->transport->download(@_);
198 }
199
200 package Business::BatchPayment::BillBuddy::Transport;
201
202 use XML::Simple qw(:strict);
203 use XML::Writer;
204
205 use Moose;
206 extends 'Business::BatchPayment::Transport::HTTPS';
207
208 has [ qw(username password) ] => (
209    is  => 'ro',
210    isa => 'Str',
211    required => 1,
212 );
213
214 has 'path' => (
215    is  => 'ro',
216    isa => 'Str',
217    default => '',
218 );
219
220 has 'debug' => (
221   is => 'rw',
222   isa => 'Int',
223   default => 0,
224 );
225
226 # this is really specific to BillBuddy, not a generic XML formatting routine
227 sub xml_format {
228   my ($self,$sid,@param) = @_;
229   my $out;
230   my $xml = XML::Writer->new(
231     OUTPUT   => \$out,
232     ENCODING => 'UTF-8',
233   );
234   $xml->startTag('postdata');
235   $xml->dataElement('sessionid',$sid);
236   $xml->dataElement('clientidentifier','');
237   $xml->startTag('parameters');
238   foreach my $param (@param) {
239     if (ref($param) eq 'ARRAY') {
240       my $type  = $$param[0];
241       my $value = $$param[1];
242       $xml->$type('parameter',$value);
243     } else {
244       $xml->dataElement('parameter',$param);
245     }
246   }
247   $xml->endTag('parameters');
248   $xml->endTag('postdata');
249   $xml->end();
250   return $out;
251 }
252
253 # also specific to BillBuddy, doesn't actually follow XMLRPC standard for response
254 sub xmlrpc_post {
255   my ($self,$func,$sid,@param) = @_;
256   my $path = $self->path;
257   $path = '/' . $path unless $path =~ /^\//;
258   $path .= '/' unless $path =~ /\/$/;
259   $path .= $func;
260   my $xmlcontent = $self->xml_format($sid,@param);
261   warn $self->host . ' ' . $self->port . ' ' . $path . "\n" . $xmlcontent if $self->debug;
262   my ($response, $rcode, %rheaders) = $self->https_post($path,$xmlcontent);
263   die "Bad response from gateway: $rcode\n" unless $rcode eq '200 OK';
264   warn $response . "\n" if $self->debug;
265   my $rref = XMLin($response, KeyAttr => ['ResponseData'], ForceArray => []);
266   die "Error from gateway: " . $rref->{'ResponseStatusDescription'}. "\n"
267     if $rref->{'ResponseStatus'};
268   return $rref;
269 }
270
271 #gets date from batch & sets processor_id in batch
272 sub upload {
273   my ($self,$request,$batch) = @_;
274   my @tokens = ();
275   # login
276   my $resp = $self->xmlrpc_post('xmlrpc_tp_Login.asp','',$self->username,$self->password);
277   my $sid = $resp->{'ResponseData'}->{'sessionID'};
278   die "Could not parse sessionid from gateway response" unless $sid;
279   # get date from login, to ensure we're using upstream date
280   my ($year,$mon,$mday,$hour,$min,$sec) = $resp->{'ResponseTimestamp'} =~ /^(....)-(..)-(..)\s+(..):(..):(..)/;
281   # then add a day and a bit, because "processs date need to be a date in the future"
282   my $date = DateTime->new(
283     year      => $year,
284     month     => $mon,
285     day       => $mday,
286     hour      => $hour,
287     minute    => $min,
288     second    => $sec,
289     # timezone on object mostly doesn't matter,
290     # but this does appear to be the tz being passed by BillBuddy,
291     # and this should avoid DST troubles (Queensland does not do DST)
292     time_zone => 'Australia/Queensland',
293   )->add_duration(
294     # extra hour is buffer for upload to run, hopefully that's plenty
295     DateTime::Duration->new( hours => 25 )
296   )->ymd;
297   # start a payment batch
298   $resp = $self->xmlrpc_post('xmlrpc_tp_DDRBatch_Open.asp',$sid,$self->username,$date);
299   my $batchno = $resp->{'ResponseData'}->{'batchno'};
300   die "Could not parse batchno from gateway response" unless $batchno;
301   $batch->processor_id($batchno);
302   # post a payment transaction
303   foreach my $line (split(/\n/,$request)) {
304     $self->xmlrpc_post('xmlrpc_tp_DDRTransaction_Add.asp',$sid,$self->username,$batchno,['cdataElement',$line]);
305   }
306   # close payment batch
307   $self->xmlrpc_post('xmlrpc_tp_DDRBatch_Close.asp',$sid,$self->username,$batchno);
308   # submit payment batch
309   $self->xmlrpc_post('xmlrpc_tp_DDRBatch_Submit.asp',$sid,$self->username,$batchno);
310   # logout
311   $self->xmlrpc_post('xmlrpc_tp_Logout.asp',$sid,$self->username);
312   return '';
313 }
314
315 # caution--this method developed without access to completed test payments
316 # built with best guesses, cross your fingers...
317 sub download {
318   my $self = shift;
319   my @processor_ids = @_;
320   return () unless @processor_ids;
321   # login
322   my $resp = $self->xmlrpc_post('xmlrpc_tp_Login.asp','',$self->username,$self->password);
323   my $sid = $resp->{'ResponseData'}->{'sessionID'};
324   die "Could not parse sessionid from gateway response" unless $sid;
325   my @batches = ();
326   foreach my $batchno (@processor_ids) {
327     #get BillBuddy transaction ids for batch
328     $resp = $self->xmlrpc_post('xmlrpc_tp_DDRBatch_getTranList.asp',$sid,$self->username,$batchno);
329     my $tids = $resp->{'ResponseData'}->{'id'};
330     next unless $tids; #error/die instead?
331     my @batchitems = ();
332     $tids = ref($tids) ? $tids : [ $tids ];
333     #get status by individual transaction
334     foreach my $tid (@$tids) {
335       $resp = $self->xmlrpc_post('xmlrpc_tp_DDRBatch_getTranStatus.asp',$sid,$self->username,$tid);
336       my $status = lc($resp->{'ResponseData'}->{'bankprocessstatus'});
337       my $error = '';
338       next if grep(/^$status$/,('submitted','processing','scheduled'));
339       $error = "Unknown return status: $status"
340         unless grep(/^$status$/,('deleted','declined'));
341       my $item = Business::BatchPayment->create(Item =>
342         order_number  => $tid,
343         tid           => $resp->{'ResponseData'}->{'referencenumber'},
344         approved      => ($status eq 'approved') ? 1 : 0,
345         error_message => $error,
346         authorization => '',
347       );
348       if ($resp->{'ResponseData'}->{'actualprocessdate'} =~ /^(\d\d\d\d).(\d\d).(\d\d)/) {
349         $item->payment_date($1.'-'.$2.'-'.$3);
350       } else {
351         warn "Could not parse actualprocessdate ".$resp->{'ResponseData'}->{'actualprocessdate'};
352       }
353       push(@batchitems,$item);
354     }
355     if (@batchitems) {
356       push(@batches, Business::BatchPayment->create('Batch', items => \@batchitems));
357     }
358   }
359   # logout
360   $self->xmlrpc_post('xmlrpc_tp_Logout.asp',$sid,$self->username);
361   return @batches;
362 }
363
364 1;
365