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