[ic] PayFlow Pro

Tom Tucker tom at ttucker.com
Sat Mar 22 10:26:23 EST 2008


On Mar 21, 2008, at 4:34 PM, Davor Ocelic wrote:

> On Fri, 21 Mar 2008 15:49:29 -0500
> Tom Tucker <tom at ttucker.com> wrote:
>
>> How about I contribute the module I wrote to work with this API
>> about 1 yr ago?
>>
>> To whom should I send it?
>
> Just attach the module and send it to the -users list.
>
> -doc

Hacked from the Signio.pm.

I also have the
     "Website Payments Pro Payflow Edition Developer’s Guide"
     "Website Payments Pro Payflow Edition – Express Checkout and  
Direct Payment Simulator Guide"
PDF files. I don't think I can attach them to a message to the list.

Code is messy, but functional (at least for me).

Tom

# Vend::Payment::PayPal - Interchange support for Verisign/PayPal  
Payflow Pro
#                         HTTPS POST
#
#
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public
# License along with this program; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA  02111-1307  USA.

package Vend::Payment::PayPal;

=head1 NAME

Vend::Payment::PayPal - Interchange support for Verisign/PayPal  
Payflow Pro
                         HTTPS POST

=head1 SYNOPSIS

     &charge=paypal

         or

     [charge mode=paypal param1=value1 param2=value2]

=head1 PREREQUISITES

     The following Perl modules:
        LWP
        Crypt::SSLeay
        Data::Dumper
        Digest::MD5 qw(md5_base64)
        HTTP::Request
        HTTP::Headers

     OpenSSL

=head1 VERISIGN SOFTWARE SETUP

PayPal's Payflow Pro HTTPS POST does NOT require the proprietary  
binary-only
shared library that was used for the Verisign Payflow Pro service.

=head1 DESCRIPTION

The Vend::Payment::PayPal module implements the paypal() payment routine
for use with Interchange. It is compatible on a call level with the  
other
Interchange payment modules -- in theory (and even usually in  
practice) you
could switch from CyberCash to PayPal with a few configuration file  
changes.

To enable this module, place this directive in F<interchange.cfg>:

     Require module Vend::Payment::PayPal

This I<must> be in interchange.cfg or a file included from it.

NOTE: Make sure CreditCardAuto is off (default in Interchange demos).

The mode can be named anything, but the C<gateway> parameter must be set
to C<paypal>. To make it the default payment gateway for all credit
card transactions in a specific catalog, you can set in F<catalog.cfg>:

     Variable   MV_PAYMENT_MODE  paypal

It uses several of the standard settings from Interchange payment. Any  
time
we speak of a setting, it is obtained either first from the tag/call  
options,
then from an Interchange order Route named for the mode, then finally a
default global payment variable. For example, the C<id> parameter would
be specified by:

     [charge mode=paypal id=YourPayflowProID]

or

     Route paypal id YourPayflowProID

or with only PayflowPro as a payment provider

     Variable MV_PAYMENT_ID      YourPayflowProID

The active settings are:

=over 4

=item id

Your account ID, supplied by VeriSign when you sign up.
Global parameter is MV_PAYMENT_ID.

=item secret

Your account password, selected by you or provided by Verisign when  
you sign up.
Global parameter is MV_PAYMENT_SECRET.

=item partner

Your account partner, selected by you or provided by Verisign when you
sign up. Global parameter is MV_PAYMENT_PARTNER.

=item vendor

Your account vendor, selected by you or provided by Verisign when you
sign up. Global parameter is MV_PAYMENT_VENDOR.

=item transaction

The type of transaction to be run. Valid values are:

     Interchange         Payflow Pro
     ----------------    -----------------
	sale                S
	auth                A
	credit              C
	void                V
	settle              D (from previous A trans)

Default is C<sale>.

=back

The following should rarely be used, as the supplied defaults are
usually correct.

=over 4

=item remap

This remaps the form variable names to the ones needed by Verisign. See
the C<Payment Settings> heading in the Interchange documentation for  
use.

=item host

The payment gateway host to use. Default is C<payflow.verisign.com>, and
C<test-payflow.verisign.com> when in test mode.

=item check_sub

Name of a Sub or GlobalSub to be called after the result hash has been
received from Verisign. A reference to the modifiable result hash is
passed into the subroutine, and it should return true (in the Perl truth
sense) if its checks were successful, or false if not.

This can come in handy since, strangely, Verisign has no option to  
decline
a charge when AVS or CSC data come back negative. See Verisign knowledge
base articles vs2365, vs7779, vs12717, and vs22810 for more details.

If you want to fail based on a bad AVS check, make sure you're only
doing an auth -- B<not a sale>, or your customers would get charged on
orders that fail the AVS check and never get logged in your system!

Add the parameters like this:

	Route  paypal  check_sub  avs_check

This is a matching sample subroutine you could put in interchange.cfg:

	GlobalSub <<EOR
	sub avs_check {
		my ($result) = @_;
		my ($addr, $zip) = @{$result}{qw( AVSADDR AVSZIP )};
		return 1 if $addr eq 'Y' or $zip eq 'Y';
		return 1 if $addr eq 'X' and $zip eq 'X';
		return 1 if $addr !~ /\S/ and $zip !~ /\S/;
		$result->{RESULT} = 112;
		$result->{RESPMSG} = "The billing address you entered does not match  
the cardholder's billing address";
		return 0;
	}
	EOR

That would work equally well as a Sub in catalog.cfg. It will succeed if
either the address or zip is 'Y', or if both are unknown. If it fails,
it sets the result code and error message in the result hash using
Verisign's own (otherwise unused) 112 result code, meaning "Failed AVS
check".

Of course you can use this sub to do any other post-processing you
want as well.

=back

=head2 Troubleshooting

Try the instructions above, then enable test mode. A test order should  
complete.

Then move to live mode and try a sale with the card number C<4111 1111
1111 1111> and a valid future expiration date. The sale should be  
denied,
and the reason should be in [data session payment_error].

If it doesn't work:

=over 4

=item *

Make sure you "Require"d the module in interchange.cfg:

     Require module Vend::Payment::PayPal_POST

=item *

Make sure the Verisign C<libpfpro.so> shared library was available to
PFProAPI.xs when you built and installed the PFProAPI.pm module, and  
that
you haven't moved C<libpfpro.so> since then.

If you're not using the PFProAPI Perl interface, make sure the Verisign
C<pfpro> or C<pfpro-file> executable is available either in your path or
in /path_to_interchange/lib.

=item *

Check the error logs, both catalog and global.

=item *

Make sure you set your account ID and secret properly.

=item *

Try an order, then put this code in a page:

     <XMP>
     [calc]
         my $string = $Tag->uneval( { ref => $Session- 
 >{payment_result} });
         $string =~ s/{/{\n/;
         $string =~ s/,/,\n/g;
         return $string;
     [/calc]
     </XMP>

That should show what happened.

=item *

If all else fails, consultants are available to help with
integration for a fee. You can find consultants by asking on the
C<interchange-biz at icdevgroup.org> mailing list.

=back

=head1 SECURITY CONSIDERATIONS

Because this library may call an executable, you should ensure that no
untrusted users have write permission on any of the system directories
or Interchange software directories.

=head1 BUGS

There is actually nothing *in* Vend::Payment::PayPal_POST. It changes  
packages
to Vend::Payment and places things there.

=head1 AUTHORS

	Cameron Prince <cameronbprince at yahoo.com>
	Mark Johnson <mark at endpoint.com>
	Mike Heins <mike at perusion.com>
	Jon Jensen <jon at icdevgroup.org>

=cut

package Vend::Payment;

my $Modules_found;
BEGIN {
     eval {
         use LWP;
         use Data::Dumper;
         use Digest::MD5 qw(md5_base64);
         use HTTP::Request;
         use HTTP::Headers;
         require Crypt::SSLeay;
         $Modules_found = 1;
     };
     if ($Modules_found) {
         print STDERR "Required modules for PayPal Pay Flow Pro HTTPS  
found.\n";
     }
     else {
         print STDERR "Required modules for PayPal Pay Flow Pro HTTPS  
NOT found.\n";
         die;
     }
}

sub paypal {
     my ($user, $amount) = @_;
::logDebug(qq{paypal called (Modules_found=$Modules_found)\n} .
     ::uneval($user));

     my $opt;
     my $secret;
     if(ref $user) {
         $opt = $user;
         $user = $opt->{id} || undef;
         $secret = $opt->{secret} || undef;
     }
     else {
         $opt = {};
     }

     my %actual;
     if($opt->{actual}) {
         %actual = %{$opt->{actual}};
     }
     else {
         %actual = map_actual();
     }

     if(! $user  ) {
         $user    =  charge_param('id')
                         or return (
                             MStatus => 'failure-hard',
                             MErrMsg => errmsg('No account id'),
                             );
     }
#::logDebug("paypal user $user");

     if(! $secret) {
         $secret    =  charge_param('secret')
                         or return (
                             MStatus => 'failure-hard',
                             MErrMsg => errmsg('No account password'),
                             );
     }

#::logDebug("paypal OrderID: |$opt->{order_id}|");

     my $server;
     my $port;
     if(! $opt->{host} and charge_param('test')) {
         $server = 'pilot-payflowpro.verisign.com';
     }
     else {
         # We won't read from MV_PAYMENT_SERVER because that would  
rarely
         # be right and might often be wrong
         $server  =   $opt->{host}  || 'pilot-payflowpro.verisign.com';
     }

     my $uri = "https://" . $server . "/transaction";

     $actual{mv_credit_card_exp_month} =~ s/\D//g;
     $actual{mv_credit_card_exp_month} =~ s/^0+//;
     $actual{mv_credit_card_exp_year} =~ s/\D//g;
     $actual{mv_credit_card_exp_year} =~ s/\d\d(\d\d)/$1/;

     $actual{mv_credit_card_number} =~ s/\D//g;

     my $exp = sprintf '%02d%02d',
                         $actual{mv_credit_card_exp_month},
                         $actual{mv_credit_card_exp_year};

     my %type_map = (
         qw/
                         sale          S
                         auth          A
                         authorize     A
                         void          V
                         settle        D
                         settle_prior  D
                         credit        C
                         mauthcapture  S
                         mauthonly     A
                         mauthdelay    D
                         mauthreturn   C
                         S             S
                         C             C
                         D             D
                         V             V
                         A             A
         /
     );

     my $transtype = $opt->{transaction} ||  
charge_param('transaction') || 'A';

     $transtype = $type_map{$transtype}
         or return (
                 MStatus => 'failure-hard',
                 MErrMsg => errmsg('Unrecognized transaction: %s',  
$transtype),
             );


     my $orderID = $opt->{order_id};
     $amount = $opt->{total_cost} if ! $amount;

     if(! $amount) {
         my $precision = $opt->{precision} ||  
charge_param('precision') || 2;
         my $cost      = Vend::Interpolate::total_cost();
         $amount = Vend::Util::round_to_frac_digits($cost, $precision);
     }

     my %varmap = ( qw/
                         ACCT        mv_credit_card_number
                         CVV2        mv_credit_card_cvv2
                         ZIP            b_zip
                         STREET        b_address
                         SHIPTOZIP    zip
                         EMAIL        email
                         COMMENT1    comment1
                         COMMENT2    comment2
         /
     );

     my %query = (
                     AMT         => $amount,
                     EXPDATE     => $exp,
                     TENDER      => 'C',
                     PWD         => $secret,
                     USER        => $user,
                     TRXTYPE        => $transtype,
     );

     $query{PARTNER} = $opt->{partner} || charge_param('partner');
     $query{VENDOR}  = $opt->{vendor}  || charge_param('vendor');
     $query{ORIGID} = $orderID if $orderID;

     #$orderID ||= gen_order_id($opt);
     # We want a unique ORIGID for each call
     $orderID = gen_order_id();
#::logDebug("paypal AUTH gen_order_id: " . $orderID);

     for (keys %varmap) {
         $query{$_} = $actual{$varmap{$_}};
     }
#::logDebug("paypal query: " . ::uneval(\%query));

     my $timeout = $opt->{timeout} || 10;
     $timeout =~ s/\D//g
         and die "Bad timeout value, security violation.";
     $port =~ s/\D//g
         and die "Bad port value, security violation.";
     $server =~ s/[^-\w.]//g
         and die "Bad server value, security violation.";

     my $result = {};
     my $decline;

     my @query;
     for my $key (keys %query) {
         my $val = $query{$key};
         $val =~ s/["\$\n\r]//g;
#        if($val =~ /[&=]/) {
             my $len = length($val);
             $key .= "[$len]";
#        }
         push @query, "$key=$val";
     }
     my $string = join '&', @query;

     my $resultstr = call_payflow($uri, $orderID, $string);

     %$result = split /[&=]/, $resultstr;

     if (
         $result->{RESULT} and
         my $check_sub_name = $opt->{check_sub} ||  
charge_param('check_sub')
     ) {
         my $check_sub = $Vend::Cfg->{Sub}{$check_sub_name}
             || $Global::GlobalSub->{$check_sub_name};
         if (ref $check_sub eq 'CODE') {
             $decline = ! $check_sub->($result);
#::logDebug(qq{paypal called check_sub sub=$check_sub_name decline= 
$decline});
         }
         else {
             logError("paypal: non-existent check_sub routine %s.",  
$check_sub_name);
         }
     }

     my %result_map = ( qw/
         MStatus               ICSTATUS
         pop.status            ICSTATUS
         order-id              PNREF
         pop.order-id          PNREF
         pop.auth-code         AUTHCODE
         pop.avs_code          AVSZIP
         pop.avs_zip           AVSZIP
         pop.avs_addr          AVSADDR
     /
     );

     # Test if the transaction request went through
     # (not the transaction results)
     #
     if ($result{RESULT}) {
         $result->{ICSTATUS} = 'failed';
         my $msg = errmsg("Charge AUTH error: %s Reason: %s. Please  
call in your order or try again.",
             $result->{RESULT},
             $result->{RESPMSG},
         );
         $result->{MErrMsg} = $result{'pop.error-message'} = $msg;
#::logDebug(qq{paypal decline=$result{RESULT}  
result: } . ::uneval($result));
         return %result;
     }

     # Okay, the transaction occured, did the CSC match?
     #
     elsif (
         defined $actual{mv_credit_card_cvv2} &&
         $result->{CVV2MATCH} ne "Y"
     ) {
         $result->{ICSTATUS} = 'failed';
         my $msg = errmsg("CSC not valid for card number.");
         $result->{MErrMsg} = $result{'pop.error-message'} = $msg;
#::logDebug(qq{paypal CVV2 failed result: } . ::uneval($result));
     }

     # Make sure AVS Address matched
     #
     elsif ( $result->{AVSADDR} ne "Y" ) {
         $result->{ICSTATUS} = 'failed';
         my $msg = errmsg("Billing Address not valid for card number  
(" .
             $result->{AVSADDR} . ").");
         $result->{MErrMsg} = $result{'pop.error-message'} = $msg;
#::logDebug(qq{paypal $result{'MErrMsg'}: } . ::uneval($result));
     }

     # Make sure AVS Zip matched
     #
     elsif ( $result->{AVSZIP} ne "Y" ) {
         $result->{ICSTATUS} = 'failed';
         my $msg = errmsg("Billing Zip/Postal code not valid for card  
" .
             "number (" . $result->{AVSZIP} . ").");
         $result->{MErrMsg} = $result{'pop.error-message'} = $msg;
#::logDebug(qq{paypal $result{'MErrMsg'} : } . ::uneval($result));
     }

     else {

         # Perform the Delayed Capture
         #
         $orderID = gen_order_id();
#::logDebug("paypal CAPTURE gen_order_id: " . $orderID);
#        $string =~ s/TRXTYPE=A/TRXTYPE=D/;
#        $string =~ s/ORIGID=$orderID/ORIGID=$result{PNREF}/;
         $query{'TRXTYPE'} = "D";
         $query{ORIGID} = $result->{PNREF};
#::logDebug("paypal query: " . ::uneval(\%query));

         @query = ();
         for my $key (keys %query) {
             my $val = $query{$key};
             $val =~ s/["\$\n\r]//g;
#            if($val =~ /[&=]/) {
                 my $len = length($val);
                 $key .= "[$len]";
#            }
             push @query, "$key=$val";
         }
         my $string = join '&', @query;

         $resultstr = call_payflow($uri, $orderID, $string);

         %$result = split /[&=]/, $resultstr;

         if ($result->{RESULT}) {
             $result->{ICSTATUS} = 'failed';
             my $msg = errmsg("Charge CAPTURE error: %s Reason: %s.  
Please call in your order or try again.",
                 $result->{RESULT},
                 $result->{RESPMSG},
             );
             $result->{MErrMsg} = $result{'pop.error-message'} = $msg;
#::logDebug(qq{paypal CAPTURE error: $result->{RESULT}  
result: } . ::uneval($result));
             return %result;
         }

         $result->{ICSTATUS} = 'success';

     }

     for (keys %result_map) {
         $result->{$_} = $result->{$result_map{$_}}
             if defined $result->{$result_map{$_}};
     }

#::logDebug(qq{paypal result: } . ::uneval($result));
     return %$result;

     sub call_payflow {

         my @query;
         my ($uri, $orderID, $string) = @_;

#::logDebug(qq{--------------------\nPosting to PayPal: \n\t$orderID\n 
\t$uri "$string"});

         ## defaults:
         my $method = 'POST';

         ## these are the necessary headers that you must set:
         #
         my $headers = HTTP::Headers->new(
             'Content-Type'                        => 'text/namevalue',
             'X-VPS-Request-Id'                    => $orderID,
             'X-VPS-Timeout'                       => '30',
             'X-VPS-VIT-Client-Architecture'       => 'x86',
             'X-VPS-VIT-Client-Certification-ID'   =>  
'32fc94951a56a8a2d9b19101989dd392',     ##  Enter your Client  
Certification ID supplied to you.
             'X-VPS-VIT-Client-Type'               => 'Perl',
             'X-VPS-VIT-Client-Version'            => '0.1-dev',
             'X-VPS-VIT-Integration-Product'       =>  
'Payment::VeriSign',  ## Name of your application, cart, etc.
             'X-VPS-VIT-Integration-Version'       => '0.01',  ## Used  
in conjunction with Integration-Product.
             'X-VPS-VIT-OS-Name'                   => 'Linux/ 
Interchange',  ## Operating System
             'X-VPS-VIT-OS-Version'                => 'RHL 7.2/5.4'   
## Version of Operating System.
         );

         ## Now we build and execute our first request:
         my $request = HTTP::Request->new($method, $uri, $headers,  
$string);
         my $ua = LWP::UserAgent->new;
         $ua->agent('Payment::PayPal');
         my $response = $ua->request($request);
         my $results = $response->content;

#::logDebug(qq{PayPal response:\n\t$results\n--------------------});

         return $results;
     }
}

*verisign = \&paypal;

package Vend::Payment::PayPal_POST;

1;




More information about the interchange-users mailing list