72b5afe74813bdfae5d97a9954e79d0b64e06f34
[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 Moose;
87 with 'Business::BatchPayment::Processor';
88
89 our $VERSION = '0.02';
90
91 has [ qw(username password) ] => (
92    is  => 'ro',
93    isa => 'Str',
94 );
95
96 has 'host' => (
97    is  => 'ro',
98    isa => 'Str',
99    default => 'xmlrpc.billbuddy.com',
100 );
101
102 has 'path' => (
103    is  => 'ro',
104    isa => 'Str',
105    default => '/',
106 );
107
108 has 'port' => (
109    is  => 'ro',
110    isa => 'Str',
111    default => '443',
112 );
113
114 sub default_transport {
115   my $self = shift;
116   Business::BatchPayment->create('BillBuddy::Transport',
117     username      => $self->username,
118     password      => $self->password,
119     host          => $self->host,
120     port          => $self->port,
121     path          => $self->path,
122     debug         => $self->debug,
123   );
124 }
125
126 sub format_item {
127   my ($self,$item,$batch) = @_;
128   #Position Length Content
129   #1-1 1 "D" 
130   my $line = 'D';
131   #2-17 16 Reference Number  
132   $line .= sprintf("%-16s",$item->tid);
133   #18-18 1 blank, filled with space 
134   $line .= ' ';
135   #19-28 10 amount, numbers only, by cents, zero padded to the left 
136   $line .= sprintf("%10s",$item->amount * 100);
137   #29-30 2 blank, filled with spaces 
138   $line .= '  ';
139   #31-32 2 account type: "BC" for bank account, "CC" for credit card account 
140   my $pt = $item->payment_type;
141   if ($pt eq 'CC') {
142     #we currently don't support CC, but leaving the code in place for future development
143     die 'Business::BatchPayment::BillBuddy currently does not handle credit card transactions';
144     $line .= 'CC';
145   } elsif ($pt eq 'ECHECK') {
146     $line .= 'BC';
147   } else {
148     die "Unknown payment type";
149   }
150   #33-33 1 blank 
151   $line .= ' ';
152   #34-40 7 BSB for bank account, formatted in 000-000. blank for credit card account 
153   my $bsb = ($pt eq 'CC') ? sprintf("%7s",'') : $item->routing_code;
154   $bsb =~ s/^(\d{3})(\d{3})/$1\-$2/;
155   die "Bad routing code $bsb" if ($pt ne 'CC') && ($bsb !~ /^\d{3}\-\d{3}$/);
156   $line .= $bsb;
157   #41-41 1 blank 
158   $line .= ' ';
159   #42-50 9 Account number for bank accounts. blank for credit card account 
160   my $anum = ($pt eq 'CC') ? sprintf("%9s",'') : sprintf("%09s",$item->account_number);
161   $line .= $anum;
162   #51-66 16 credit card number, left padded with zero if less than 16 digits. Blank for bank accounts 
163   my $cnum = ($pt eq 'CC') ? sprintf("%016s",$item->card_number) : sprintf("%16s",'');
164   $line .= $cnum;
165   #67-98 32 bank account name or name on the credit card 
166   my $name = $item->first_name . ' ' . $item->last_name;
167   $line .= sprintf("%-32.32s",$name);
168   #99-99 1 blank 
169   $line .= ' ';
170   #100-103 4 credit card expiry date, formatted as mmdd. "0000" for bank account. 
171   my $exp = ($pt eq 'CC') ? $item->expiration : '';
172   $line .= sprintf("%04s",$exp);
173   #104-104 1 blank 
174   #105-111 7 reserved, always "0000000" 
175   #112-114 3 reserved, blank 
176   $line .= ' 0000000   ';
177   #115-120 6 line number, left padded with zero
178   $line .= sprintf("%06s",$batch->num);
179   $line .= "\n";
180   return $line;
181 }
182
183 #overriding this just to be able to pass batch to upload
184 #but maybe this should go in standard module?
185 sub submit {
186   my $self = shift;
187   my $batch = shift;
188   my $request = $self->format_request($batch);
189   $self->transport->upload($request,$batch);
190 }
191
192 #overriding this to pass process_ids to download,
193 #but maybe this should go in standard module?
194 sub receive {
195   my $self = shift;
196   return $self->transport->download(@_);
197 }
198
199 package Business::BatchPayment::BillBuddy::Transport;
200
201 use XML::Simple qw(:strict);
202 use XML::Writer;
203
204 use Moose;
205 extends 'Business::BatchPayment::Transport::HTTPS';
206
207 has [ qw(username password) ] => (
208    is  => 'ro',
209    isa => 'Str',
210    required => 1,
211 );
212
213 has 'path' => (
214    is  => 'ro',
215    isa => 'Str',
216    default => '',
217 );
218
219 has 'debug' => (
220   is => 'rw',
221   isa => 'Int',
222   default => 0,
223 );
224
225 # this is really specific to BillBuddy, not a generic XML formatting routine
226 sub xml_format {
227   my ($self,$sid,@param) = @_;
228   my $out;
229   my $xml = XML::Writer->new(
230     OUTPUT   => \$out,
231     ENCODING => 'UTF-8',
232   );
233   $xml->startTag('postdata');
234   $xml->dataElement('sessionid',$sid);
235   $xml->dataElement('clientidentifier','');
236   $xml->startTag('parameters');
237   foreach my $param (@param) {
238     if (ref($param) eq 'ARRAY') {
239       my $type  = $$param[0];
240       my $value = $$param[1];
241       $xml->$type('parameter',$value);
242     } else {
243       $xml->dataElement('parameter',$param);
244     }
245   }
246   $xml->endTag('parameters');
247   $xml->endTag('postdata');
248   $xml->end();
249   return $out;
250 }
251
252 # also specific to BillBuddy, doesn't actually follow XMLRPC standard for response
253 sub xmlrpc_post {
254   my ($self,$func,$sid,@param) = @_;
255   my $path = $self->path;
256   $path = '/' . $path unless $path =~ /^\//;
257   $path .= '/' unless $path =~ /\/$/;
258   $path .= $func;
259   my $xmlcontent = $self->xml_format($sid,@param);
260   warn $self->host . ' ' . $self->port . ' ' . $path . "\n" . $xmlcontent if $self->debug;
261   my ($response, $rcode, %rheaders) = $self->https_post($path,$xmlcontent);
262   die "Bad response from gateway: $rcode\n" unless $rcode eq '200 OK';
263   warn $response . "\n" if $self->debug;
264   my $rref = XMLin($response, KeyAttr => ['ResponseData'], ForceArray => []);
265   die "Error from gateway: " . $rref->{'ResponseStatusDescription'}. "\n"
266     if $rref->{'ResponseStatus'};
267   return $rref;
268 }
269
270 #gets date from batch & sets processor_id in batch
271 sub upload {
272   my ($self,$request,$batch) = @_;
273   my @tokens = ();
274   # get date from batch
275   my ($date) = $batch->process_date =~ /^(....-..-..)/;
276   # login
277   my $resp = $self->xmlrpc_post('xmlrpc_tp_Login.asp','',$self->username,$self->password);
278   my $sid = $resp->{'ResponseData'}->{'sessionID'};
279   die "Could not parse sessionid from gateway response" unless $sid;
280   # start a payment batch
281   $resp = $self->xmlrpc_post('xmlrpc_tp_DDRBatch_Open.asp',$sid,$self->username,$date);
282   my $batchno = $resp->{'ResponseData'}->{'batchno'};
283   die "Could not parse batchno from gateway response" unless $batchno;
284   $batch->processor_id($batchno);
285   # post a payment transaction
286   foreach my $line (split(/\n/,$request)) {
287     $self->xmlrpc_post('xmlrpc_tp_DDRTransaction_Add.asp',$sid,$self->username,$batchno,['cdataElement',$line]);
288   }
289   # close payment batch
290   $self->xmlrpc_post('xmlrpc_tp_DDRBatch_Close.asp',$sid,$self->username,$batchno);
291   # submit payment batch
292   $self->xmlrpc_post('xmlrpc_tp_DDRBatch_Submit.asp',$sid,$self->username,$batchno);
293   # logout
294   $self->xmlrpc_post('xmlrpc_tp_Logout.asp',$sid,$self->username);
295   return '';
296 }
297
298 # caution--this method developed without access to completed test payments
299 # built with best guesses, cross your fingers...
300 sub download {
301   my $self = shift;
302   my @processor_ids = @_;
303   return () unless @processor_ids;
304   # login
305   my $resp = $self->xmlrpc_post('xmlrpc_tp_Login.asp','',$self->username,$self->password);
306   my $sid = $resp->{'ResponseData'}->{'sessionID'};
307   die "Could not parse sessionid from gateway response" unless $sid;
308   my @batches = ();
309   foreach my $batchno (@processor_ids) {
310     #get BillBuddy transaction ids for batch
311     $resp = $self->xmlrpc_post('xmlrpc_tp_DDRBatch_getTranList.asp',$sid,$self->username,$batchno);
312     my $tids = $resp->{'ResponseData'}->{'id'};
313     next unless $tids; #error/die instead?
314     my @batchitems = ();
315     $tids = ref($tids) ? $tids : [ $tids ];
316     #get status by individual transaction
317     foreach my $tid (@$tids) {
318       $resp = $self->xmlrpc_post('xmlrpc_tp_DDRBatch_getTranStatus.asp',$sid,$self->username,$tid);
319       my $status = lc($resp->{'ResponseData'}->{'bankprocessstatus'});
320       my $error = '';
321       next if grep(/^$status$/,('submitted','processing','scheduled'));
322       $error = "Unknown return status: $status"
323         unless grep(/^$status$/,('deleted','declined'));
324       my $item = Business::BatchPayment->create(Item =>
325         order_number  => $tid,
326         tid           => $resp->{'ResponseData'}->{'referencenumber'},
327         approved      => ($status eq 'approved') ? 1 : 0,
328         error_message => $error,
329         authorization => '',
330       );
331       #not sure what format date gets returned in, item creation will fail on bad format,
332       #so I'm taking a guess, and not recording the date if my guess is wrong
333       if ($resp->{'ResponseData'}->{'actualprocessdate'} =~ /^(\d\d\d\d).(\d\d).(\d\d)/) {
334         $item->payment_date($1.'-'.$2.'-'.$3);
335       }
336       push(@batchitems,$item);
337     }
338     if (@batchitems) {
339       push(@batches, Business::BatchPayment->create('Batch', items => \@batchitems));
340     }
341   }
342   # logout
343   $self->xmlrpc_post('xmlrpc_tp_Logout.asp',$sid,$self->username);
344   return @batches;
345 }
346
347 1;
348