initial import
[Business-OnlinePayment-IPPay.git] / IPPay.pm
1 package Business::OnlinePayment::IPPay;
2
3 use strict;
4 use Carp;
5 use Tie::IxHash;
6 use XML::Simple;
7 use XML::Writer;
8 use LWP::UserAgent;
9 use HTTP::Request;
10 use HTTP::Request::Common qw (POST);
11 use Date::Calc qw(Add_Delta_YM Add_Delta_Days);
12 use Business::OnlinePayment;
13 use Business::OnlinePayment::HTTPS;
14 use vars qw($VERSION $DEBUG @ISA $me);
15
16 @ISA = qw(Business::OnlinePayment::HTTPS);
17 $VERSION = '0.01';
18 $DEBUG = 1;
19 $me = 'Business::OnlinePayment::IPPay';
20
21 sub set_defaults {
22     my $self = shift;
23     my %opts = @_;
24
25     # standard B::OP methods/data
26     $self->server('test1.jetpay.com') unless $self->server;
27     $self->port('443') unless $self->port;
28     $self->path('/jetpay') unless $self->path;
29
30     $self->build_subs(qw( order_number avs_code cvv2_response
31                           response_page response_code response_headers
32                      ));
33
34     # module specific data
35     if ( $opts{debug} ) {
36         $self->debug( $opts{debug} );
37         delete $opts{debug};
38     }
39
40     my %_defaults = ();
41     foreach my $key (keys %opts) {
42       $key =~ /^default_(\w*)$/ or next;
43       $_defaults{$1} = $opts{$key};
44       delete $opts{$key};
45     }
46     $self->{_defaults} = \%_defaults;
47 }
48
49 sub map_fields {
50     my($self) = @_;
51
52     my %content = $self->content();
53
54     # TYPE MAP
55     my %types = ( 'visa'               => 'CC',
56                   'mastercard'         => 'CC',
57                   'american express'   => 'CC',
58                   'discover'           => 'CC',
59                   'check'              => 'ECHECK',
60                 );
61     $content{'type'} = $types{lc($content{'type'})} || $content{'type'};
62     $self->transaction_type($content{'type'});
63     
64     # ACTION MAP 
65     my $action = lc($content{'action'});
66     my %actions =
67       ( 'normal authorization'            => 'SALE',
68         'authorization only'              => 'AUTHONLY',
69         'post authorization'              => 'CAPT',
70         'void'                            => 'VOID',
71         'credit'                          => 'CREDIT',
72       );
73     my %check_actions =
74       ( 'normal authorization'            => 'CHECK',
75         'void'                            => 'VOIDACH',
76         'credit'                          => 'REVERSAL',
77       );
78     if ($self->transaction_type eq 'CC') {
79       $content{'TransactionType'} = $actions{$action} || $action;
80     }elsif ($self->transaction_type eq 'ECHECK') {
81       $content{'TransactionType'} = $check_actions{$action} || $action;
82     }
83
84
85     # ACCOUNT TYPE MAP
86     my %account_types = ('personal checking'   => 'Checking',
87                          'personal savings'    => 'Savings',
88                          'business checking'   => 'BusinessCk',
89                         );
90     $content{'account_type'} = $account_types{lc($content{'account_type'})}
91                                || $content{'account_type'};
92
93     $content{Origin} = 'RECURRING' 
94       if ($content{recurring_billing} &&$content{recurring_billing} eq 'YES' );
95
96     # stuff it back into %content
97     $self->content(%content);
98
99 }
100
101 sub expdate_month {
102   my ($self, $exp) = (shift, shift);
103   my $month;
104   if ( defined($exp) and $exp =~ /^(\d+)\D+\d*\d{2}$/ ) {
105     $month  = sprintf( "%02d", $1 );
106   }elsif ( defined($exp) and $exp =~ /^(\d{2})\d{2}$/ ) {
107     $month  = sprintf( "%02d", $1 );
108   }
109   return $month;
110 }
111
112 sub expdate_year {
113   my ($self, $exp) = (shift, shift);
114   my $year;
115   if ( defined($exp) and $exp =~ /^\d+\D+\d*(\d{2})$/ ) {
116     $year  = sprintf( "%02d", $1 );
117   }elsif ( defined($exp) and $exp =~ /^\d{2}(\d{2})$/ ) {
118     $year  = sprintf( "%02d", $1 );
119   }
120   return $year;
121 }
122
123 sub revmap_fields {
124   my $self = shift;
125   tie my(%map), 'Tie::IxHash', @_;
126   my %content = $self->content();
127   map {
128         my $value;
129         if ( ref( $map{$_} ) eq 'HASH' ) {
130           $value = $map{$_} if ( keys %{ $map{$_} } );
131         }elsif( ref( $map{$_} ) ) {
132           $value = ${ $map{$_} };
133         }elsif( exists( $content{ $map{$_} } ) ) {
134           $value = $content{ $map{$_} };
135         }
136
137         if (defined($value)) {
138           ($_ => $value);
139         }else{
140           ();
141         }
142       } (keys %map);
143 }
144
145 sub submit {
146   my($self) = @_;
147
148   $self->is_success(0);
149   $self->map_fields();
150
151   my @required_fields = qw(action login type);
152
153   my $action = lc($self->{_content}->{action});
154   my $type = $self->transaction_type();
155   if ( $action eq 'normal authorization'
156     || $action eq 'credit'
157     || $action eq 'authorization only' && $type eq 'CC')
158   {
159     push @required_fields, qw( amount );
160
161     push @required_fields, qw( card_number expiration )
162       if ($type eq "CC"); 
163         
164     push @required_fields,
165       qw( routing_code account_number name ) # account_type
166       if ($type eq "ECHECK");
167         
168   }elsif ( $action eq 'post authorization' && $type eq 'CC') {
169     push @required_fields, qw( order_number );
170   }elsif ( $action eq 'void') {
171     push @required_fields, qw( order_number amount );
172
173     push @required_fields, qw( authorization card_number )
174       if ($type eq "CC");
175
176     push @required_fields,
177       qw( routing_code account_number name ) # account_type
178       if ($type eq "ECHECK");
179
180   }else{
181     croak "$me can't handle transaction type: ".
182       $self->{_content}->{action}. " for ".
183       $self->transaction_type();
184   }
185
186   my %content = $self->content();
187   foreach ( keys ( %{($self->{_defaults})} ) ) {
188     $content{$_} = $self->{_defaults}->{$_} unless exists($content{$_});
189   }
190   $self->content(%content);
191
192   $self->required_fields(@required_fields);
193
194   my $transaction_id = $content{'order_number'};
195   unless ($transaction_id) {
196     my ($page, $server_response, %headers) = $self->https_get('dummy' => 1);
197     return unless $server_response=~ /^200/;
198     $transaction_id = $page;
199   }
200
201   my $cardexpmonth = $self->expdate_month($content{expiration});
202   my $cardexpyear  = $self->expdate_year($content{expiration});
203   my $cardstartmonth = $self->expdate_month($content{card_start});
204   my $cardstartyear  = $self->expdate_year($content{card_start});
205  
206   my $amount;
207   if (defined($content{amount})) {
208     $amount = sprintf("%.2f", $content{amount});
209     $amount =~ s/\.//;
210   }
211
212   my $check_number = $content{check_number} || "100"  # make one up
213     if($content{account_number});
214
215   my $terminalid = $content{login} if $type eq 'CC';
216   my $merchantid = $content{login} if $type eq 'ECHECK';
217
218   tie my %ach, 'Tie::IxHash',
219     $self->revmap_fields(
220                           #AccountType         => 'account_type',
221                           AccountNumber       => 'account_number',
222                           ABA                 => 'routing_code',
223                           CheckNumber         => \$check_number,
224                         );
225
226   tie my %industryinfo, 'Tie::IxHash',
227     $self->revmap_fields(
228                           Type                => 'IndustryInfo',
229                         );
230
231   tie my %shippingaddr, 'Tie::IxHash',
232     $self->revmap_fields(
233                           Address             => 'ship_address',
234                           City                => 'ship_city',
235                           StateProv           => 'ship_state',
236                           Country             => 'ship_country',
237                           Phone               => 'ship_phone',
238                         );
239
240   tie my %shippinginfo, 'Tie::IxHash',
241     $self->revmap_fields(
242                           CustomerPO          => 'CustomerPO',
243                           ShippingMethod      => 'ShippingMethod',
244                           ShippingName        => 'ship_name',
245                           ShippingAddr        => \%shippingaddr,
246                         );
247
248   tie my %req, 'Tie::IxHash',
249     $self->revmap_fields(
250                           TransactionType     => 'TransactionType',
251                           TerminalID          => 'login',
252 #                          TerminalID          => \$terminalid,
253 #                          MerchantID          => \$merchantid,
254                           TransactionID       => \$transaction_id,
255                           RoutingCode         => 'RoutingCode',
256                           Approval            => 'authorization',
257                           BatchID             => 'BatchID',
258                           Origin              => 'Origin',
259                           Password            => 'password',
260                           OrderNumber         => 'invoice_number',
261                           CardNum             => 'card_number',
262                           CVV2                => 'cvv2',
263                           Issue               => 'issue_number',
264                           CardExpMonth        => \$cardexpmonth,
265                           CardExpYear         => \$cardexpyear,
266                           CardStartMonth      => \$cardstartmonth,
267                           CardStartYear       => \$cardstartyear,
268                           Track1              => 'track1',
269                           Track2              => 'track2',
270                           ACH                 => \%ach,
271                           CardName            => 'name',
272                           DispositionType     => 'DispositionType',
273                           TotalAmount         => \$amount,
274                           FeeAmount           => 'FeeAmount',
275                           TaxAmount           => 'TaxAmount',
276                           BillingAddress      => 'address',
277                           BillingCity         => 'city',
278                           BillingStateProv    => 'state',
279                           BillingPostalCode   => 'zip',
280                           BillingCountry      => 'country',
281                           BillingPhone        => 'phone',
282                           Email               => 'email',
283                           UserIPAddr          => 'customer_ip',
284                           UserHost            => 'UserHost',
285                           UDField1            => 'UDField1',
286                           UDField2            => 'UDField2',
287                           UDField3            => 'UDField3',
288                           ActionCode          => 'ActionCode',
289                           IndustryInfo        => \%industryinfo,
290                           ShippingInfo        => \%shippinginfo,
291                         );
292
293   my $post_data;
294   my $writer = new XML::Writer( OUTPUT      => \$post_data,
295                                 DATA_MODE   => 1,
296                                 DATA_INDENT => 1,
297                                 ENCODING    => 'us-ascii',
298                               );
299   $writer->xmlDecl();
300   $writer->startTag('JetPay');
301   foreach ( keys ( %req ) ) {
302     $self->_xmlwrite($writer, $_, $req{$_});
303   }
304   $writer->endTag('JetPay');
305   $writer->end();
306
307   if ($self->test_transaction()) {
308     $self->server('test1.jetpay.com');
309     $self->port('443');
310     $self->path('/jetpay');
311   }
312
313   warn "$post_data\n" if $DEBUG;
314
315   my ($page,$server_response,%headers) = $self->https_post($post_data);
316
317   warn "$page\n" if $DEBUG;
318
319   my $response = {};
320   if ($server_response =~ /^200/){
321     $response = XMLin($page);
322     if (  exists($response->{ActionCode}) && !exists($response->{ErrMsg})) {
323       $self->error_message($response->{ResponseText});
324     }else{
325       $self->error_message($response->{Errmsg});
326     }
327 #  }else{
328 #    $self->error_message("Server Failed");
329   }
330
331   $self->result_code($response->{ActionCode} || '');
332   $self->order_number($response->{TransactionID} || '');
333   $self->authorization($response->{Approval} || '');
334   $self->cvv2_response($response->{CVV2} || '');
335   $self->avs_code($response->{AVS} || '');
336
337   $self->is_success($self->result_code() eq '000' ? 1 : 0);
338
339   unless ($self->is_success()) {
340     unless ( $self->error_message() ) { #additional logging information
341       $self->error_message(
342         "(HTTPS response: $server_response) ".
343         "(HTTPS headers: ".
344           join(", ", map { "$_ => ". $headers{$_} } keys %headers ). ") ".
345         "(Raw HTTPS content: $page)"
346       );
347     }
348   }
349
350 }
351
352 sub _xmlwrite {
353   my ($self, $writer, $item, $value) = @_;
354   $writer->startTag($item);
355   if ( ref( $value ) eq 'HASH' ) {
356     foreach ( keys ( %$value ) ) {
357       $self->_xmlwrite($writer, $_, $value->{$_});
358     }
359   }else{
360     $writer->characters($value);
361   }
362   $writer->endTag($item);
363 }
364
365 1;
366 __END__
367
368 =head1 NAME
369
370 Business::OnlinePayment::IPPay - IPPay backend for Business::OnlinePayment
371
372 =head1 SYNOPSIS
373
374   use Business::OnlinePayment;
375
376   my $tx =
377     new Business::OnlinePayment( "IPPay",
378                                  'default_Origin' => 'PHONE ORDER',
379                                );
380   $tx->content(
381       type           => 'VISA',
382       login          => 'testdrive',
383       password       => '', #password 
384       action         => 'Normal Authorization',
385       description    => 'Business::OnlinePayment test',
386       amount         => '49.95',
387       customer_id    => 'tfb',
388       name           => 'Tofu Beast',
389       address        => '123 Anystreet',
390       city           => 'Anywhere',
391       state          => 'UT',
392       zip            => '84058',
393       card_number    => '4007000000027',
394       expiration     => '09/02',
395       cvv2           => '1234', #optional
396   );
397   $tx->submit();
398
399   if($tx->is_success()) {
400       print "Card processed successfully: ".$tx->authorization."\n";
401   } else {
402       print "Card was rejected: ".$tx->error_message."\n";
403   }
404
405 =head1 SUPPORTED TRANSACTION TYPES
406
407 =head2 CC, Visa, MasterCard, American Express, Discover
408
409 Content required: type, login, action, amount, card_number, expiration.
410
411 =head2 Check
412
413 Content required: type, login, action, amount, name, account_number, routing_code.
414
415 =head1 DESCRIPTION
416
417 For detailed information see L<Business::OnlinePayment>.
418
419 =head1 METHODS AND FUNCTIONS
420
421 See L<Business::OnlinePayment> for the complete list. The following methods either override the methods in L<Business::OnlinePayment> or provide additional functions.  
422
423 =head2 result_code
424
425 Returns the response error code.
426
427 =head2 error_message
428
429 Returns the response error description text.
430
431 =head2 server_response
432
433 Returns the complete response from the server.
434
435 =head1 Handling of content(%content) data:
436
437 =head2 action
438
439 The following actions are valid
440
441   normal authorization
442   authorization only
443   post authorization
444   credit
445   void
446
447 =head1 Setting IPPay parameters from content(%content)
448
449 The following rules are applied to map data to IPPay parameters
450 from content(%content):
451
452       # param => $content{<key>}
453       TransactionType     => 'TransactionType',
454       TerminalID          => 'login',
455       TransactionID       => 'order_number',
456       RoutingCode         => 'RoutingCode',
457       Approval            => 'authorization',
458       BatchID             => 'BatchID',
459       Origin              => 'Origin',
460       Password            => 'password',
461       OrderNumber         => 'invoice_number',
462       CardNum             => 'card_number',
463       CVV2                => 'cvv2',
464       Issue               => 'issue_number',
465       CardExpMonth        => \( $month ), # MM from MM(-)YY(YY) of 'expiration'
466       CardExpYear         => \( $year ), # YY from MM(-)YY(YY) of 'expiration'
467       CardStartMonth      => \( $month ), # MM from MM(-)YY(YY) of 'card_start'
468       CardStartYear       => \( $year ), # YY from MM(-)YY(YY) of 'card_start'
469       Track1              => 'track1',
470       Track2              => 'track2',
471       ACH
472         AccountNumber       => 'account_number',
473         ABA                 => 'routing_code',
474         CheckNumber         => 'check_number',
475       CardName            => 'name',
476       DispositionType     => 'DispositionType',
477       TotalAmount         => 'amount' reformatted into cents
478       FeeAmount           => 'FeeAmount',
479       TaxAmount           => 'TaxAmount',
480       BillingAddress      => 'address',
481       BillingCity         => 'city',
482       BillingStateProv    => 'state',
483       BillingPostalCode   => 'zip',
484       BillingCountry      => 'country',
485       BillingPhone        => 'phone',
486       Email               => 'email',
487       UserIPAddr          => 'customer_ip',
488       UserHost            => 'UserHost',
489       UDField1            => 'UDField1',
490       UDField2            => 'UDField2',
491       UDField3            => 'UDField3',
492       ActionCode          => 'ActionCode',
493       IndustryInfo
494         Type                => 'IndustryInfo',
495       ShippingInfo
496         CustomerPO          => 'CustomerPO',
497         ShippingMethod      => 'ShippingMethod',
498         ShippingName        => 'ship_name',
499         ShippingAddr
500           Address             => 'ship_address',
501           City                => 'ship_city',
502           StateProv           => 'ship_state',
503           Country             => 'ship_country',
504           Phone               => 'ship_phone',
505
506 =head1 NOTE
507
508 =head1 COMPATIBILITY
509
510 Business::OnlinePayment::IPPay uses IPPay XML Product Specifications version
511 1.1.2.
512
513 See http://www.ippay.com/ for more information.
514
515 =head1 AUTHOR
516
517 Jeff Finucane, ippay@weasellips.com
518
519 =head1 SEE ALSO
520
521 perl(1). L<Business::OnlinePayment>.
522
523 =cut
524