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