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