add ECHECK_void_requires_account to introspection info
[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   if ($self->test_transaction()) {
217     $self->server('test1.jetpay.com');
218     $self->port('443');
219     $self->path('/jetpay');
220   }
221
222   my $transaction_id = $content{'order_number'};
223   unless ($transaction_id) {
224     my ($page, $server_response, %headers) = $self->https_get('dummy' => 1);
225     warn "fetched transaction id: (HTTPS response: $server_response) ".
226          "(HTTPS headers: ".
227          join(", ", map { "$_ => ". $headers{$_} } keys %headers ). ") ".
228          "(Raw HTTPS content: $page)"
229       if $DEBUG;
230     return unless $server_response=~ /^200/;
231     $transaction_id = $page;
232   }
233
234   my $cardexpmonth = $self->expdate_month($content{expiration});
235   my $cardexpyear  = $self->expdate_year($content{expiration});
236   my $cardstartmonth = $self->expdate_month($content{card_start});
237   my $cardstartyear  = $self->expdate_year($content{card_start});
238  
239   my $amount;
240   if (defined($content{amount})) {
241     $amount = sprintf("%.2f", $content{amount});
242     $amount =~ s/\.//;
243   }
244
245   my $check_number = $content{check_number} || "100"  # make one up
246     if($content{account_number});
247
248   my $terminalid = $content{login} if $type eq 'CC';
249   my $merchantid = $content{login} if $type eq 'ECHECK';
250
251   my $country = country2code( $content{country}, LOCALE_CODE_ALPHA_3 );
252   $country  = country_code2code( $content{country},
253                                  LOCALE_CODE_ALPHA_2,
254                                  LOCALE_CODE_ALPHA_3
255                                )
256     unless $country;
257   $country = $content{country}
258     unless $country;
259   $country = uc($country) if $country;
260
261   my $ship_country =
262     country2code( $content{ship_country}, LOCALE_CODE_ALPHA_3 );
263   $ship_country  = country_code2code( $content{ship_country},
264                                  LOCALE_CODE_ALPHA_2,
265                                  LOCALE_CODE_ALPHA_3
266                                )
267     unless $ship_country;
268   $ship_country = $content{ship_country}
269     unless $ship_country;
270   $ship_country = uc($ship_country) if $ship_country;
271
272   tie my %ach, 'Tie::IxHash',
273     $self->revmap_fields(
274                           #AccountType         => 'account_type',
275                           AccountNumber       => 'account_number',
276                           ABA                 => 'routing_code',
277                           CheckNumber         => \$check_number,
278                         );
279
280   tie my %industryinfo, 'Tie::IxHash',
281     $self->revmap_fields(
282                           Type                => 'IndustryInfo',
283                         );
284
285   tie my %shippingaddr, 'Tie::IxHash',
286     $self->revmap_fields(
287                           Address             => 'ship_address',
288                           City                => 'ship_city',
289                           StateProv           => 'ship_state',
290                           Country             => \$ship_country,
291                           Phone               => 'ship_phone',
292                         );
293
294   unless ( $type ne 'CC' || keys %shippingaddr ) {
295     tie %shippingaddr, 'Tie::IxHash',
296       $self->revmap_fields(
297                             Address             => 'address',
298                             City                => 'city',
299                             StateProv           => 'state',
300                             Country             => \$country,
301                             Phone               => 'phone',
302                           );
303   }
304
305   tie my %shippinginfo, 'Tie::IxHash',
306     $self->revmap_fields(
307                           CustomerPO          => 'CustomerPO',
308                           ShippingMethod      => 'ShippingMethod',
309                           ShippingName        => 'ship_name',
310                           ShippingAddr        => \%shippingaddr,
311                         );
312
313   tie my %req, 'Tie::IxHash',
314     $self->revmap_fields(
315                           TransactionType     => 'TransactionType',
316                           TerminalID          => 'login',
317 #                          TerminalID          => \$terminalid,
318 #                          MerchantID          => \$merchantid,
319                           TransactionID       => \$transaction_id,
320                           RoutingCode         => 'RoutingCode',
321                           Approval            => 'authorization',
322                           BatchID             => 'BatchID',
323                           Origin              => 'Origin',
324                           Password            => 'password',
325                           OrderNumber         => 'invoice_number',
326                           CardNum             => 'card_number',
327                           CVV2                => 'cvv2',
328                           Issue               => 'issue_number',
329                           CardExpMonth        => \$cardexpmonth,
330                           CardExpYear         => \$cardexpyear,
331                           CardStartMonth      => \$cardstartmonth,
332                           CardStartYear       => \$cardstartyear,
333                           Track1              => 'track1',
334                           Track2              => 'track2',
335                           ACH                 => \%ach,
336                           CardName            => 'name',
337                           DispositionType     => 'DispositionType',
338                           TotalAmount         => \$amount,
339                           FeeAmount           => 'FeeAmount',
340                           TaxAmount           => 'TaxAmount',
341                           BillingAddress      => 'address',
342                           BillingCity         => 'city',
343                           BillingStateProv    => 'state',
344                           BillingPostalCode   => 'zip',
345                           BillingCountry      => \$country,
346                           BillingPhone        => 'phone',
347                           Email               => 'email',
348                           UserIPAddr          => 'customer_ip',
349                           UserHost            => 'UserHost',
350                           UDField1            => 'UDField1',
351                           UDField2            => 'UDField2',
352                           UDField3            => 'UDField3',
353                           ActionCode          => 'ActionCode',
354                           IndustryInfo        => \%industryinfo,
355                           ShippingInfo        => \%shippinginfo,
356                         );
357
358   my $post_data;
359   my $writer = new XML::Writer( OUTPUT      => \$post_data,
360                                 DATA_MODE   => 1,
361                                 DATA_INDENT => 1,
362                                 ENCODING    => 'us-ascii',
363                               );
364   $writer->xmlDecl();
365   $writer->startTag('JetPay');
366   foreach ( keys ( %req ) ) {
367     $self->_xmlwrite($writer, $_, $req{$_});
368   }
369   $writer->endTag('JetPay');
370   $writer->end();
371
372   warn "$post_data\n" if $DEBUG;
373
374   my ($page,$server_response,%headers) = $self->https_post($post_data);
375
376   warn "$page\n" if $DEBUG;
377
378   my $response = {};
379   if ($server_response =~ /^200/){
380     $response = XMLin($page);
381     if (  exists($response->{ActionCode}) && !exists($response->{ErrMsg})) {
382       $self->error_message($response->{ResponseText});
383     }else{
384       $self->error_message($response->{Errmsg});
385     }
386 #  }else{
387 #    $self->error_message("Server Failed");
388   }
389
390   $self->result_code($response->{ActionCode} || '');
391   $self->order_number($response->{TransactionID} || '');
392   $self->authorization($response->{Approval} || '');
393   $self->cvv2_response($response->{CVV2} || '');
394   $self->avs_code($response->{AVS} || '');
395
396   $self->is_success($self->result_code() eq '000' ? 1 : 0);
397
398   unless ($self->is_success()) {
399     unless ( $self->error_message() ) { #additional logging information
400       $self->error_message(
401         "(HTTPS response: $server_response) ".
402         "(HTTPS headers: ".
403           join(", ", map { "$_ => ". $headers{$_} } keys %headers ). ") ".
404         "(Raw HTTPS content: $page)"
405       );
406     }
407   }
408
409 }
410
411 sub _xmlwrite {
412   my ($self, $writer, $item, $value) = @_;
413   $writer->startTag($item);
414   if ( ref( $value ) eq 'HASH' ) {
415     foreach ( keys ( %$value ) ) {
416       $self->_xmlwrite($writer, $_, $value->{$_});
417     }
418   }else{
419     $writer->characters($value);
420   }
421   $writer->endTag($item);
422 }
423
424 1;
425
426 __END__
427
428 =head1 NAME
429
430 Business::OnlinePayment::IPPay - IPPay backend for Business::OnlinePayment
431
432 =head1 SYNOPSIS
433
434   use Business::OnlinePayment;
435
436   my $tx =
437     new Business::OnlinePayment( "IPPay",
438                                  'default_Origin' => 'PHONE ORDER',
439                                );
440   $tx->content(
441       type           => 'VISA',
442       login          => 'testdrive',
443       password       => '', #password 
444       action         => 'Normal Authorization',
445       description    => 'Business::OnlinePayment test',
446       amount         => '49.95',
447       customer_id    => 'tfb',
448       name           => 'Tofu Beast',
449       address        => '123 Anystreet',
450       city           => 'Anywhere',
451       state          => 'UT',
452       zip            => '84058',
453       card_number    => '4007000000027',
454       expiration     => '09/02',
455       cvv2           => '1234', #optional
456   );
457   $tx->submit();
458
459   if($tx->is_success()) {
460       print "Card processed successfully: ".$tx->authorization."\n";
461   } else {
462       print "Card was rejected: ".$tx->error_message."\n";
463   }
464
465 =head1 SUPPORTED TRANSACTION TYPES
466
467 =head2 CC, Visa, MasterCard, American Express, Discover
468
469 Content required: type, login, action, amount, card_number, expiration.
470
471 =head2 Check
472
473 Content required: type, login, action, amount, name, account_number, routing_code.
474
475 =head1 DESCRIPTION
476
477 For detailed information see L<Business::OnlinePayment>.
478
479 =head1 METHODS AND FUNCTIONS
480
481 See L<Business::OnlinePayment> for the complete list. The following methods either override the methods in L<Business::OnlinePayment> or provide additional functions.  
482
483 =head2 result_code
484
485 Returns the response error code.
486
487 =head2 error_message
488
489 Returns the response error description text.
490
491 =head2 server_response
492
493 Returns the complete response from the server.
494
495 =head1 Handling of content(%content) data:
496
497 =head2 action
498
499 The following actions are valid
500
501   normal authorization
502   authorization only
503   post authorization
504   credit
505   void
506
507 =head1 Setting IPPay parameters from content(%content)
508
509 The following rules are applied to map data to IPPay parameters
510 from content(%content):
511
512       # param => $content{<key>}
513       TransactionType     => 'TransactionType',
514       TerminalID          => 'login',
515       TransactionID       => 'order_number',
516       RoutingCode         => 'RoutingCode',
517       Approval            => 'authorization',
518       BatchID             => 'BatchID',
519       Origin              => 'Origin',
520       Password            => 'password',
521       OrderNumber         => 'invoice_number',
522       CardNum             => 'card_number',
523       CVV2                => 'cvv2',
524       Issue               => 'issue_number',
525       CardExpMonth        => \( $month ), # MM from MM(-)YY(YY) of 'expiration'
526       CardExpYear         => \( $year ), # YY from MM(-)YY(YY) of 'expiration'
527       CardStartMonth      => \( $month ), # MM from MM(-)YY(YY) of 'card_start'
528       CardStartYear       => \( $year ), # YY from MM(-)YY(YY) of 'card_start'
529       Track1              => 'track1',
530       Track2              => 'track2',
531       ACH
532         AccountNumber       => 'account_number',
533         ABA                 => 'routing_code',
534         CheckNumber         => 'check_number',
535       CardName            => 'name',
536       DispositionType     => 'DispositionType',
537       TotalAmount         => 'amount' reformatted into cents
538       FeeAmount           => 'FeeAmount',
539       TaxAmount           => 'TaxAmount',
540       BillingAddress      => 'address',
541       BillingCity         => 'city',
542       BillingStateProv    => 'state',
543       BillingPostalCode   => 'zip',
544       BillingCountry      => 'country',           # forced to ISO-3166-alpha-3
545       BillingPhone        => 'phone',
546       Email               => 'email',
547       UserIPAddr          => 'customer_ip',
548       UserHost            => 'UserHost',
549       UDField1            => 'UDField1',
550       UDField2            => 'UDField2',
551       UDField3            => 'UDField3',
552       ActionCode          => 'ActionCode',
553       IndustryInfo
554         Type                => 'IndustryInfo',
555       ShippingInfo
556         CustomerPO          => 'CustomerPO',
557         ShippingMethod      => 'ShippingMethod',
558         ShippingName        => 'ship_name',
559         ShippingAddr
560           Address             => 'ship_address',
561           City                => 'ship_city',
562           StateProv           => 'ship_state',
563           Country             => 'ship_country',  # forced to ISO-3166-alpha-3
564           Phone               => 'ship_phone',
565
566 =head1 NOTE
567
568 =head1 COMPATIBILITY
569
570 Business::OnlinePayment::IPPay uses IPPay XML Product Specifications version
571 1.1.2.
572
573 See http://www.ippay.com/ for more information.
574
575 =head1 AUTHOR
576
577 Jeff Finucane, ippay@weasellips.com
578
579 =head1 SEE ALSO
580
581 perl(1). L<Business::OnlinePayment>.
582
583 =cut
584