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