cust_id: Use customer number instead of invoice number / order_id: Append "-invoice_n...
[Business-OnlinePayment-eSelectPlus.git] / eSelectPlus.pm
1 package Business::OnlinePayment::eSelectPlus;
2
3 use strict;
4 use Carp;
5 use Tie::IxHash;
6 use Business::OnlinePayment 3;
7 use Business::OnlinePayment::HTTPS 0.03;
8 use vars qw($VERSION $DEBUG @ISA);
9
10 @ISA = qw(Business::OnlinePayment::HTTPS);
11 $VERSION = '0.07';
12 $DEBUG = 0;
13
14 sub set_defaults {
15     my $self = shift;
16
17     #USD
18     #$self->server('esplusqa.moneris.com');  # development
19     $self->server('esplus.moneris.com');   # production
20     $self->path('/gateway_us/servlet/MpgRequest');
21
22     ##CAD
23     ##$self->server('esqa.moneris.com');  # development
24     #$self->server('www3.moneris.com');   # production
25     #$self->path('/gateway2/servlet/MpgRequest');
26
27     $self->port('443');
28
29     $self->build_subs(qw( order_number avs_code ));
30     # avs_code order_type md5 cvv2_response cavv_response
31 }
32
33 sub submit {
34     my($self) = @_;
35
36     if ( defined( $self->{_content}{'currency'} )
37               &&  $self->{_content}{'currency'} eq 'CAD' ) {
38       $self->server('www3.moneris.com');
39       $self->path('/gateway2/servlet/MpgRequest');
40     } else { #sorry, default to USD
41       $self->server('esplus.moneris.com');
42       $self->path('/gateway_us/servlet/MpgRequest');
43     }
44
45     if ($self->test_transaction)  {
46        if ( defined( $self->{_content}{'currency'} )
47                  &&  $self->{_content}{'currency'} eq 'CAD' ) {
48          $self->server('esqa.moneris.com');
49          $self->{_content}{'login'} = 'store2';   # store[123]
50          $self->{_content}{'password'} = 'yesguy';
51        } else { #sorry, default to USD
52          $self->server('esplusqa.moneris.com');
53          $self->{_content}{'login'} = 'monusqa002';   # monusqa00[123]
54          $self->{_content}{'password'} = 'qatoken';
55        }
56     }
57
58     my %cust_id = ( 'invoice_number' => 'cust_id' );
59
60     my $invoice_number = $self->{_content}{invoice_number};
61
62     # BOP field => eSelectPlus field
63     #$self->map_fields();
64     $self->remap_fields(
65         #                => 'order_type',
66         #                => 'transaction_type',
67         #login            => 'store_id',
68         #password         => 'api_token',
69         #authorization   => 
70         #customer_ip     =>
71         #name            =>
72         #first_name      =>
73         #last_name       =>
74         #company         =>
75         #address         => 
76         #city            => 
77         #state           => 
78         #zip             => 
79         #country         =>
80         phone            => 
81         #fax             =>
82         email            =>
83         card_number      => 'pan',
84         #expiration        =>
85         #                => 'expdate',
86
87         'amount'         => 'amount',
88         customer_id      => 'cust_id',
89         order_number     => 'order_id',   # must be unique number
90         authorization    => 'txn_number'  # reference to previous trans
91
92         #cvv2              =>
93     );
94
95     my $action = $self->{_content}{'action'};
96     if ( $self->{_content}{'action'} =~ /^\s*normal\s*authorization\s*$/i ) {
97       $action = 'purchase';
98     } elsif ( $self->{_content}{'action'} =~ /^\s*authorization\s*only\s*$/i ) {
99       $action = 'preauth';
100     } elsif ( $self->{_content}{'action'} =~ /^\s*post\s*authorization\s*$/i ) {
101       $action = 'completion';
102     } elsif ( $self->{_content}{'action'} =~ /^\s*void\s*$/i ) {
103       $action = 'purchasecorrection';
104     } elsif ( $self->{_content}{'action'} =~ /^\s*credit\s*$/i ) {
105       if ( $self->{_content}{'authorization'} ) {
106         $action = 'refund';
107       } else {
108         $action = 'ind_refund';
109       }
110     }
111
112     if ( $action =~ /^(purchase|preauth|ind_refund)$/ ) {
113
114       $self->required_fields(qw(
115         login password amount card_number expiration
116       ));
117
118       #cardexpiremonth & cardexpireyear
119       $self->{_content}{'expiration'} =~ /^(\d+)\D+\d*(\d{2})$/
120         or croak "unparsable expiration ". $self->{_content}{expiration};
121       my( $month, $year ) = ( $1, $2 );
122       $month = '0'. $month if $month =~ /^\d$/;
123       $self->{_content}{expdate} = $year.$month;
124
125       $self->generate_order_id;
126
127       $self->{_content}{order_id} .= '-'. ($invoice_number || 0);
128
129       $self->{_content}{amount} = sprintf('%.2f', $self->{_content}{amount} );
130
131     } elsif ( $action =~ /^(completion|purchasecorrection|refund)$/ ) {
132
133       $self->required_fields(qw(
134         login password order_number authorization
135       ));
136
137       if ( $action eq 'completion' ) {
138         $self->{_content}{comp_amount} = delete $self->{_content}{amount};
139       } elsif ( $action eq 'purchasecorrection' ) {
140         delete $self->{_content}{amount};
141       #} elsif ( $action eq 'refund' ) {
142       } 
143
144     }
145
146     # E-Commerce Indicator (see eSelectPlus docs)
147     $self->{_content}{'crypt_type'} ||= 7;
148
149     $action = "us_$action"
150       unless defined( $self->{_content}{'currency'} )
151                    && $self->{_content}{'currency'} eq 'CAD';
152
153     #no, values aren't escaped for XML.  their "mpgClasses.pl" example doesn't
154     #appear to do so, i dunno
155     tie my %fields, 'Tie::IxHash', $self->get_fields( $self->fields );
156     my $post_data =
157       '<?xml version="1.0"?>'.
158       '<request>'.
159       '<store_id>'.  $self->{_content}{'login'}. '</store_id>'.
160       '<api_token>'. $self->{_content}{'password'}. '</api_token>'.
161       "<$action>".
162       join('', map "<$_>$fields{$_}</$_>", keys %fields ).
163       "</$action>".
164       '</request>';
165
166     warn "POSTING: ".$post_data if $DEBUG > 1;
167
168     my( $page, $response, @reply_headers) = $self->https_post( $post_data );
169
170     if ($DEBUG > 1) {
171       my %reply_headers = @reply_headers;
172       warn join('', map { "  $_ => $reply_headers{$_}\n" } keys %reply_headers)
173     }
174
175     if ($response !~ /^200/)  {
176         # Connection error
177         $response =~ s/[\r\n]+/ /g;  # ensure single line
178         $self->is_success(0);
179         my $diag_message = $response || "connection error";
180         die $diag_message;
181     }
182
183     # avs_code - eSELECTplus_Perl_IG.pdf Appendix F
184     my %avsTable = ('A' => 'A',
185                     'B' => 'A',
186                     'C' => 'E',
187                     'D' => 'Y',
188                     'G' => '',
189                     'I' => '',
190                     'M' => 'Y',
191                     'N' => 'N',
192                     'P' => 'Z',
193                     'R' => 'R',
194                     'S' => '',
195                     'U' => 'E',
196                     'W' => 'Z',
197                     'X' => 'Y',
198                     'Y' => 'Y',
199                     'Z' => 'Z',
200                     );
201     my $AvsResultCode = $self->GetXMLProp($page, 'AvsResultCode');
202     $self->avs_code( defined($AvsResultCode) && exists $avsTable{$AvsResultCode}
203                          ?  $avsTable{$AvsResultCode}
204                          :  $AvsResultCode
205                    );
206
207     #md5 cvv2_response cavv_response ...?
208
209     $self->server_response($page);
210
211     my $result = $self->GetXMLProp($page, 'ResponseCode');
212
213     die "gateway error: ". $self->GetXMLProp( $page, 'Message' )
214       if $result =~ /^null$/i;
215
216     # Original order_id supplied to the gateway
217     $self->order_number($self->GetXMLProp($page, 'ReceiptId'));
218
219     # We (Whizman & DonorWare) do not have enough info about "ISO"
220     # response codes to make use of them.
221     # There may be good reasons why the ISO codes could be preferable,
222     # but we would need more information.  For now, the ResponseCode.
223     # $self->result_code( $self->GetXMLProp( $page, 'ISO' ) );
224     $self->result_code( $result );
225
226     if ( $result =~ /^\d+$/ && $result < 50 ) {
227         $self->is_success(1);
228         $self->authorization($self->GetXMLProp($page, 'TransID'));
229     } elsif ( $result =~ /^\d+$/ ) {
230         $self->is_success(0);
231         my $tmp_msg = $self->GetXMLProp( $page, 'Message' );
232         $tmp_msg =~ s/\s{2,}//g;
233         $tmp_msg =~ s/[\*\=]//g;
234         $self->error_message( $tmp_msg );
235     } else {
236         die "unparsable response received from gateway (response $result)".
237             ( $DEBUG ? ": $page" : '' );
238     }
239
240 }
241
242 use vars qw(@oidset);
243 @oidset = ( 'A'..'Z', '0'..'9' );
244 sub generate_order_id {
245     my $self = shift;
246     #generate an order_id if order_number not passed
247     unless (    exists ($self->{_content}{order_id})
248              && defined($self->{_content}{order_id})
249              && length ($self->{_content}{order_id})
250            ) {
251       $self->{_content}{'order_id'} =
252         join('', map { $oidset[int(rand(scalar(@oidset)))] } (1..23) );
253     }
254 }
255
256 sub fields {
257         my $self = shift;
258
259         #order is important to this processor
260         qw(
261           order_id
262           cust_id
263           amount
264           comp_amount
265           txn_number
266           pan
267           expdate
268           crypt_type
269           cavv
270         );
271 }
272
273 sub GetXMLProp {
274         my( $self, $raw, $prop ) = @_;
275         local $^W=0;
276
277         my $data;
278         ($data) = $raw =~ m"<$prop>(.*?)</$prop>"gsi;
279         #$data =~ s/<.*?>/ /gs;
280         chomp $data;
281         return $data;
282 }
283
284 1;
285
286 __END__
287
288 =head1 NAME
289
290 Business::OnlinePayment::eSelectPlus - Moneris eSelect Plus backend module for Business::OnlinePayment
291
292 =head1 SYNOPSIS
293
294   use Business::OnlinePayment;
295
296   ####
297   # One step transaction, the simple case.
298   ####
299
300   my $tx = new Business::OnlinePayment("eSelectPlus");
301   $tx->content(
302       type           => 'VISA',
303       login          => 'eSelect Store ID,
304       password       => 'eSelect API Token',
305       action         => 'Normal Authorization',
306       description    => 'Business::OnlinePayment test',
307       amount         => '49.95',
308       currency       => 'USD', #or CAD for compatibility with previous releases
309       name           => 'Tofu Beast',
310       address        => '123 Anystreet',
311       city           => 'Anywhere',
312       state          => 'UT',
313       zip            => '84058',
314       phone          => '420-867-5309',
315       email          => 'tofu.beast@example.com',
316       card_number    => '4005550000000019',
317       expiration     => '08/06',
318       cvv2           => '1234', #optional
319   );
320   $tx->submit();
321
322   if($tx->is_success()) {
323       print "Card processed successfully: ".$tx->authorization."\n";
324   } else {
325       print "Card was rejected: ".$tx->error_message."\n";
326   }
327   print "AVS code: ". $tx->avs_code. "\n"; # Y - Address and ZIP match
328                                            # A - Address matches but not ZIP
329                                            # Z - ZIP matches but not address
330                                            # N - no match
331                                            # E - AVS error or unsupported
332                                            # R - Retry (timeout)
333                                            # (empty) - not verified
334
335 =head1 SUPPORTED TRANSACTION TYPES
336
337 =head2 CC, Visa, MasterCard, American Express, Discover
338
339 Content required: type, login, password, action, amount, card_number, expiration.
340
341 =head1 PREREQUISITES
342
343   URI::Escape
344   Tie::IxHash
345
346   Net::SSLeay _or_ ( Crypt::SSLeay and LWP )
347
348 =head1 DESCRIPTION
349
350 For detailed information see L<Business::OnlinePayment>.
351
352 =head1 NOTES
353
354 =head2 Note for Canadian merchants upgrading to 0.03
355
356 As of version 0.03, this module now defaults to the US Moneris.  Make sure to
357 pass currency=>'CAD' for Canadian transactions.
358
359 =head2 Note for upgrading to 0.05
360
361 As of version 0.05, the bank authorization code is discarded (AuthCode),
362 so that authorization() and order_number() can return the 2 fields needed
363 for capture.  See also
364 cpansearch.perl.org/src/IVAN/Business-OnlinePayment-3.02/notes_for_module_writers_v3
365
366 =head1 AUTHOR
367
368 Ivan Kohler <ivan-eselectplus@420.am>
369 Randall Whitman L<whizman.com|http://whizman.com>
370
371 =head1 SEE ALSO
372
373 perl(1). L<Business::OnlinePayment>.
374
375 =cut
376