- include most of the patches from Frédéric Brière at fbriere.net
[Business-OnlinePayment-PayflowPro.git] / PayflowPro.pm
1 package Business::OnlinePayment::PayflowPro;
2
3 use strict;
4 use vars qw($VERSION $DEBUG);
5 use Carp qw(carp croak);
6 use CGI;
7 use Digest::MD5;
8 use Business::OnlinePayment::HTTPS 0.06;
9
10 use base qw(Business::OnlinePayment::HTTPS);
11
12 $VERSION = '0.07_06';
13 $VERSION = eval $VERSION;
14 $DEBUG   = 0;
15
16 # return current request_id or generate a new one if not yet set
17 sub request_id {
18     my $self = shift;
19     if ( ref($self) ) {
20         $self->{"__request_id"} = shift if (@_); # allow value change/reset
21         $self->{"__request_id"} = $self->_new_request_id()
22           unless ( $self->{"__request_id"} );
23         return $self->{"__request_id"};
24     }
25     else {
26         return $self->_new_request_id();
27     }
28 }
29
30 sub _new_request_id {
31     my $self = shift;
32     my $md5  = Digest::MD5->new();
33     $md5->add( $$, time(), rand(time) );
34     return $md5->hexdigest();
35 }
36
37 sub debug {
38     my $self = shift;
39
40     if (@_) {
41         my $level = shift || 0;
42         if ( ref($self) ) {
43             $self->{"__DEBUG"} = $level;
44         }
45         else {
46             $DEBUG = $level;
47         }
48         $Business::OnlinePayment::HTTPS::DEBUG = $level;
49     }
50     return ref($self) ? ( $self->{"__DEBUG"} || $DEBUG ) : $DEBUG;
51 }
52
53 # cvv2_code: support legacy code and but deprecate method
54 sub cvv2_code { shift->cvv2_response(@_); }
55
56 sub set_defaults {
57     my $self = shift;
58     my %opts = @_;
59
60     # standard B::OP methods/data
61     #$self->server("payflow.verisign.com");
62     $self->server("payflowpro.verisign.com");
63     $self->port("443");
64     $self->path("/transaction");
65
66     $self->build_subs(qw( 
67                           partner vendor
68                           client_certification_id client_timeout
69                           headers test_server
70                           cert_path
71                           order_number avs_code cvv2_response
72                           response_page response_code response_headers
73                      ));
74
75     # module specific data
76     if ( $opts{debug} ) {
77         $self->debug( $opts{debug} );
78         delete $opts{debug};
79     }
80
81     # HTTPS Interface Dev Guide: must be set but will be removed in future
82     $self->client_certification_id("ClientCertificationIdNotSet");
83
84     # required: 45 secs recommended by HTTPS Interface Dev Guide
85     $self->client_timeout(45);
86
87     $self->test_server( "pilot-payflowpro.verisign.com" );
88 }
89
90 sub _map_fields {
91     my ($self) = @_;
92
93     my %content = $self->content();
94
95     #ACTION MAP
96     my %actions = (
97         'normal authorization' => 'S',    # Sale transaction
98         'credit'               => 'C',    # Credit (refund)
99         'authorization only'   => 'A',    # Authorization
100         'post authorization'   => 'D',    # Delayed Capture
101         'void'                 => 'V',    # Void
102     );
103
104     $content{'action'} = $actions{ lc( $content{'action'} ) }
105       || $content{'action'};
106
107     # TYPE MAP
108     my %types = (
109         'visa'             => 'C',
110         'mastercard'       => 'C',
111         'american express' => 'C',
112         'discover'         => 'C',
113         'cc'               => 'C',
114
115         #'check'            => 'ECHECK',
116     );
117
118     $content{'type'} = $types{ lc( $content{'type'} ) } || $content{'type'};
119
120     $self->transaction_type( $content{'type'} );
121
122     # stuff it back into %content
123     $self->content(%content);
124 }
125
126 sub _revmap_fields {
127     my ( $self, %map ) = @_;
128     my %content = $self->content();
129     foreach ( keys %map ) {
130         $content{$_} =
131           ref( $map{$_} )
132           ? ${ $map{$_} }
133           : $content{ $map{$_} };
134     }
135     $self->content(%content);
136 }
137
138 sub expdate_mmyy {
139     my $self       = shift;
140     my $expiration = shift;
141     my $expdate_mmyy;
142     if ( defined($expiration) and $expiration =~ /^(\d+)\D+\d*(\d{2})$/ ) {
143         my ( $month, $year ) = ( $1, $2 );
144         $expdate_mmyy = sprintf( "%02d", $month ) . $year;
145     }
146     return defined($expdate_mmyy) ? $expdate_mmyy : $expiration;
147 }
148
149 sub submit {
150     my ($self) = @_;
151
152     $self->_map_fields();
153
154     my %content = $self->content;
155
156     if ( $self->transaction_type() ne 'C' ) {
157         croak( "PayflowPro can't (yet?) handle transaction type: "
158               . $self->transaction_type() );
159     }
160
161     my $expdate_mmyy = $self->expdate_mmyy( $content{"expiration"} );
162     my $zip          = $content{'zip'};
163     $zip =~ s/[^[:alnum:]]//g;
164
165     $self->server( $self->test_server ) if $self->test_transaction;
166
167     my $vendor  = $self->vendor;
168     my $partner = $self->partner;
169
170     $self->_revmap_fields(
171
172         # BUG?: VENDOR B::OP:PayflowPro < 0.05 backward compatibility.  If
173         # vendor not set use login although test indicate undef vendor is ok
174         VENDOR => $vendor ? \$vendor : 'login',
175         PARTNER  => \$partner,
176         USER     => 'login',
177         PWD      => 'password',
178         TRXTYPE  => 'action',
179         TENDER   => 'type',
180         ORIGID   => 'order_number',
181         COMMENT1 => 'description',
182         COMMENT2 => 'invoice_number',
183
184         ACCT    => 'card_number',
185         CVV2    => 'cvv2',
186         EXPDATE => \$expdate_mmyy,    # MM/YY from 'expiration'
187         AMT     => 'amount',
188
189         FIRSTNAME   => 'first_name',
190         LASTNAME    => 'last_name',
191         NAME        => 'name',
192         EMAIL       => 'email',
193         COMPANYNAME => 'company',
194         STREET      => 'address',
195         CITY        => 'city',
196         STATE       => 'state',
197         ZIP         => \$zip,          # 'zip' with non-alnums removed
198         COUNTRY     => 'country',
199     );
200
201     my @required = qw( TRXTYPE TENDER PARTNER VENDOR USER PWD );
202     if ( $self->transaction_type() eq 'C' ) {    # credit card
203         if (   $content{'action'} =~ /^[CDV]$/
204             && defined( $content{'ORIGID'} )
205             && length( $content{'ORIGID'} ) )
206         {
207             push @required, qw(ORIGID);
208         }
209         else {
210
211             # never get here, we croak above if transaction_type ne 'C'
212             push @required, qw(AMT ACCT EXPDATE);
213         }
214     }
215     $self->required_fields(@required);
216
217     my %params = $self->get_fields(
218         qw(
219           VENDOR PARTNER USER PWD TRXTYPE TENDER ORIGID COMMENT1 COMMENT2
220           ACCT CVV2 EXPDATE AMT
221           FIRSTNAME LASTNAME NAME EMAIL COMPANYNAME
222           STREET CITY STATE ZIP COUNTRY
223           )
224     );
225
226     # get header data
227     my %req_headers = %{ $self->headers || {} };
228
229     # get request_id from %content if defined for ease of use
230     if ( defined $content{"request_id"} ) {
231         $self->request_id( $content{"request_id"} );
232     }
233
234     unless ( defined( $req_headers{"X-VPS-Request-ID"} ) ) {
235         $req_headers{"X-VPS-Request-ID"} = $self->request_id();
236     }
237
238     unless ( defined( $req_headers{"X-VPS-VIT-Client-Certification-Id"} ) ) {
239         $req_headers{"X-VPS-VIT-Client-Certification-Id"} =
240           $self->client_certification_id;
241     }
242
243     unless ( defined( $req_headers{"X-VPS-Client-Timeout"} ) ) {
244         $req_headers{"X-VPS-Client-Timeout"} = $self->client_timeout();
245     }
246
247     my %options = (
248         "Content-Type" => "text/namevalue",
249         "headers"      => \%req_headers,
250     );
251
252     my ( $page, $resp, %resp_headers ) =
253       $self->https_post( \%options, \%params );
254
255     $self->response_code( $resp );
256     $self->response_page( $page );
257     $self->response_headers( \%resp_headers );
258
259     # $page should contain name=value[[&name=value]...] pairs
260     my $cgi = CGI->new("$page");
261
262     # AVS and CVS values may be set on success or failure
263     my $avs_code;
264     if ( defined $cgi->param("AVSADDR") or defined $cgi->param("AVSZIP") ) {
265         if ( $cgi->param("AVSADDR") eq "Y" && $cgi->param("AVSZIP") eq "Y" ) {
266             $avs_code = "Y";
267         }
268         elsif ( $cgi->param("AVSADDR") eq "Y" ) {
269             $avs_code = "A";
270         }
271         elsif ( $cgi->param("AVSZIP") eq "Y" ) {
272             $avs_code = "Z";
273         }
274         elsif ( $cgi->param("AVSADDR") eq "N" or $cgi->param("AVSZIP") eq "N" )
275         {
276             $avs_code = "N";
277         }
278         else {
279             $avs_code = "";
280         }
281     }
282
283     $self->avs_code($avs_code);
284     $self->cvv2_response( $cgi->param("CVV2MATCH") );
285     $self->result_code( $cgi->param("RESULT") );
286     $self->order_number( $cgi->param("PNREF") );
287     $self->error_message( $cgi->param("RESPMSG") );
288     $self->authorization( $cgi->param("AUTHCODE") );
289
290     # RESULT must be an explicit zero, not just numerically equal
291     if ( $cgi->param("RESULT") eq "0" ) {
292         $self->is_success(1);
293     }
294     else {
295         $self->is_success(0);
296     }
297 }
298
299 1;
300
301 __END__
302
303 =head1 NAME
304
305 Business::OnlinePayment::PayflowPro - Payflow Pro backend for Business::OnlinePayment
306
307 =head1 SYNOPSIS
308
309   use Business::OnlinePayment;
310   
311   my $tx = new Business::OnlinePayment(
312       'PayflowPro',
313       'vendor'  => 'your_vendor',
314       'partner' => 'your_partner',
315       'client_certification_id' => 'GuidUpTo32Chars',
316   );
317   
318   # See the module documentation for details of content()
319   $tx->content(
320       type           => 'VISA',
321       action         => 'Normal Authorization',
322       description    => 'Business::OnlinePayment::PayflowPro test',
323       amount         => '49.95',
324       invoice_number => '100100',
325       customer_id    => 'jsk',
326       name           => 'Jason Kohles',
327       address        => '123 Anystreet',
328       city           => 'Anywhere',
329       state          => 'GA',
330       zip            => '30004',
331       email          => 'ivan-payflowpro@420.am',
332       card_number    => '4111111111111111',
333       expiration     => '12/09',
334       cvv2           => '123',
335       order_number   => 'string',
336       request_id     => 'unique_identifier_for_transaction',
337   );
338   
339   $tx->submit();
340   
341   if ( $tx->is_success() ) {
342       print(
343           "Card processed successfully: ", $tx->authorization, "\n",
344           "order number: ",                $tx->order_number,  "\n",
345           "CVV2 response: ",               $tx->cvv2_response, "\n",
346           "AVS code: ",                    $tx->avs_code,      "\n",
347       );
348   }
349   else {
350       my $info = "";
351       $info = " (CVV2 mismatch)" if ( $tx->result_code == 114 );
352       
353       print(
354           "Card was rejected: ", $tx->error_message, $info, "\n",
355           "order number: ",      $tx->order_number,         "\n",
356       );
357   }
358
359 =head1 DESCRIPTION
360
361 This module is a back end driver that implements the interface
362 specified by L<Business::OnlinePayment> to support payment handling
363 via the PayPal's Payflow Pro Internet payment solution.
364
365 See L<Business::OnlinePayment> for details on the interface this
366 modules supports.
367
368 =head1 Standard methods
369
370 =over 4
371
372 =item set_defaults()
373
374 This method sets the 'server' attribute to 'payflowpro.verisign.com'
375 and the port attribute to '443'.  This method also sets up the
376 L</Module specific methods> described below.
377
378 =item submit()
379
380 =back
381
382 =head1 Unofficial methods
383
384 This module provides the following methods which are not officially
385 part of the standard Business::OnlinePayment interface (as of 3.00_06)
386 but are nevertheless supported by multiple gateways modules and
387 expected to be standardized soon:
388
389 =over 4
390
391 =item L<order_number()|/order_number()>
392
393 =item L<avs_code()|/avs_code()>
394
395 =item L<cvv2_response()|/cvv2_response()>
396
397 =back
398
399 =head1 Module specific methods
400
401 This module provides the following methods which are not currently
402 part of the standard Business::OnlinePayment interface:
403
404 =head2 client_certification_id()
405
406 This gets/sets the X-VPS-VITCLIENTCERTIFICATION-ID which is REQUIRED
407 and defaults to "ClientCertificationIdNotSet".  This is described in
408 Website Payments Pro HTTPS Interface Developer's Guide as follows:
409
410 "A random globally unique identifier (GUID) that is currently
411 required. This requirement will be removed in the future. At this
412 time, you can send any alpha-numeric ID up to 32 characters in length.
413
414 NOTE: Once you have created this ID, do not change it. Use the same ID
415 for every transaction."
416
417 =head2 client_timeout()
418
419 Timeout value, in seconds, after which this transaction should be
420 aborted.  Defaults to 45, the value recommended by the Website
421 Payments Pro HTTPS Interface Developer's Guide.
422
423 =head2 debug()
424
425 Enable or disble debugging.  The value specified here will also set
426 $Business::OnlinePayment::HTTPS::DEBUG in submit() to aid in
427 troubleshooting problems.
428
429 =head2 expdate_mmyy()
430
431 The expdate_mmyy() method takes a single scalar argument (typically
432 the value in $content{expiration}) and attempts to parse and format
433 and put the date in MMYY format as required by PayflowPro
434 specification.  If unable to parse the expiration date simply leave it
435 as is and let the PayflowPro system attempt to handle it as-is.
436
437 =head2 request_id()
438
439 It is recommended that you specify your own unique request_id for each
440 transaction in %content.  A request_id is REQUIRED by the PayflowPro
441 processor.  If a request_id is not set, then Digest::MD5 is used to
442 attempt to generate a request_id for a transaction.
443
444 =head2 Deprecated methods
445
446 The following methods are deprecated and may be removed in a future
447 release.  Values for vendor and partner should now be set as arguments
448 to Business::OnlinePayment->new().  The value for cert_path was used
449 to support passing a path to PFProAPI.pm (a Perl module/SDK from
450 Verisign/Paypal) which is no longer used.
451
452 =over 4
453
454 =item vendor()
455
456 =item partner()
457
458 =item cert_path()
459
460 =item cvv2_code()
461
462 =back
463
464 =head1 Settings
465
466 The following default settings exist:
467
468 =over 4
469
470 =item server
471
472 payflowpro.verisign.com or pilot-payflowpro.verisign.com if
473 test_transaction() is TRUE
474
475 =item port
476
477 443
478
479 =back
480
481 =head1 Handling of content(%content)
482
483 The following rules apply to content(%content) data:
484
485 =head2 action
486
487 If 'action' matches one of the following keys it is replaced by the
488 right hand side value:
489
490   'normal authorization' => 'S', # Sale transaction
491   'credit'               => 'C', # Credit (refund)
492   'authorization only'   => 'A', # Authorization
493   'post authorization'   => 'D', # Delayed Capture
494   'void'                 => 'V',
495
496 If 'action' is 'C', 'D' or 'V' and 'order_number' is not set then
497 'amount', 'card_number' and 'expiration' must be set.
498
499 =head2 type
500
501 If 'type' matches one of the following keys it is replaced by the
502 right hand side value:
503
504   'visa'               => 'C',
505   'mastercard'         => 'C',
506   'american express'   => 'C',
507   'discover'           => 'C',
508   'cc'                 => 'C',
509
510 The value of 'type' is used to set transaction_type().  Currently this
511 module only supports a transaction_type() of 'C' any other values will
512 cause Carp::croak() to be called in submit().
513
514 Note: Payflow Pro supports multiple credit card types, including:
515 American Express/Optima, Diners Club, Discover/Novus, Enroute, JCB,
516 MasterCard and Visa.
517
518 =head1 Setting Payflow Pro parameters from content(%content)
519
520 The following rules are applied to map data to Payflow Pro parameters
521 from content(%content):
522
523       # PFP param => $content{<key>}
524       VENDOR      => $self->vendor ? \( $self->vendor ) : 'login',
525       PARTNER     => \( $self->partner ),
526       USER        => 'login',
527       PWD         => 'password',
528       TRXTYPE     => 'action',
529       TENDER      => 'type',
530       ORIGID      => 'order_number',
531       COMMENT1    => 'description',
532       COMMENT2    => 'invoice_number',
533
534       ACCT        => 'card_number',
535       CVV2        => 'cvv2',
536       EXPDATE     => \( $month.$year ), # MM/YY from 'expiration'
537       AMT         => 'amount',
538
539       FIRSTNAME   => 'first_name',
540       LASTNAME    => 'last_name',
541       NAME        => 'name',
542       EMAIL       => 'email',
543       COMPANYNAME => 'company',
544       STREET      => 'address',
545       CITY        => 'city',
546       STATE       => 'state',
547       ZIP         => \$zip, # 'zip' with non-alphanumerics removed
548       COUNTRY     => 'country',
549
550 The required Payflow Pro parameters for credit card transactions are:
551
552   TRXTYPE TENDER PARTNER VENDOR USER PWD ORIGID
553
554 =head1 Mapping Payflow Pro transaction responses to object methods
555
556 The following methods provides access to the transaction response data
557 resulting from a Payflow Pro request (after submit()) is called:
558
559 =head2 order_number()
560
561 This order_number() method returns the PNREF field, also known as the
562 PayPal Reference ID, which is a unique number that identifies the
563 transaction.
564
565 =head2 result_code()
566
567 The result_code() method returns the RESULT field, which is the
568 numeric return code indicating the outcome of the attempted
569 transaction.
570
571 A RESULT of 0 (zero) indicates the transaction was approved and
572 is_success() will return '1' (one/TRUE).  Any other RESULT value
573 indicates a decline or error and is_success() will return '0'
574 (zero/FALSE).
575
576 =head2 error_message()
577
578 The error_message() method returns the RESPMSG field, which is a
579 response message returned with the transaction result.
580
581 =head2 authorization()
582
583 The authorization() method returns the AUTHCODE field, which is the
584 approval code obtained from the processing network.
585
586 =head2 avs_code()
587
588 The avs_code() method returns a combination of the AVSADDR and AVSZIP
589 fields from the transaction result.  The value in avs_code is as
590 follows:
591
592   Y     - Address and ZIP match
593   A     - Address matches but not ZIP
594   Z     - ZIP matches but not address
595   N     - no match
596   undef - AVS values not available
597
598 =head2 cvv2_response()
599
600 The cvv2_response() method returns the CVV2MATCH field, which is a
601 response message returned with the transaction result.
602
603 =head1 COMPATIBILITY
604
605 As of 0.07, this module communicates with the Payflow gateway directly
606 and no longer requires the Payflow Pro SDK or other download.  Thanks
607 to Phil Lobbes for this great work.
608
609 =head1 AUTHORS
610
611 Ivan Kohler <ivan-payflowpro@420.am>
612
613 Phil Lobbes E<lt>phil at perkpartners.comE<gt>
614
615 Based on Business::OnlinePayment::AuthorizeNet written by Jason Kohles.
616
617 =head1 SEE ALSO
618
619 perl(1), L<Business::OnlinePayment>, L<Carp>, and the PayPal
620 Integration Center Payflow Pro resources at
621 L<https://www.paypal.com/IntegrationCenter/ic_payflowpro.html>
622
623 =cut