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