ADVERTISEMENT


Breaking News

Recent Posts

Thursday, June 26, 2014

Paypal payment gateway direct payment method integration NVP (Name Value Pairs) made easy with code

Introduction

A basic code and explanation for paypal direct payment using name value pairs NVP. For a complete list of other paypal payment methods click here or download the samples from paypal here. By default this code connects to the sandbox url of paypal. You can change that to the live url after experimenting. You need to get api username, api password and api signature from merchant to whom the users will pay. Here paypal had provided with a testing username, password and signature which i have used in the code as given by paypal. The procedure is very simple. The below form will be submitted to a php file. That script will store the post data into variables and will create a query string including the authentication credentials. Then we connect to the paypal server and will post the request data using CURL. The response is converted into an array and is parsed to find whether the payment is a success. Please note that when success the server gives a transaction id which we shall store it in the database for furtuer references of that payment through the admin panel though the client can access all his transactions through his paypal login. - See more at: http://vikku.info/programming/payment-gateway/paypal-direct-payment-integration-NVP-made-easy.htm#sthash.AXWQQyXo.dpuf

Personal Details
 
First Name
Last Name
Email
Address
City
State/Zip
 eg. NY 
Payment Details
 
Card Type
Cardholder Name
Card Number
Expiration [ mm / yyyy ]
  
CVV Number

Code and Explanation

You can also copy the html part of the code by viewing the source code of this page. Since the html code is very simple to copy i did not provide the html code here. In the zip file you can find both the html and the php script.
Assign all post data to its respective variables..
- See more at: http://vikku.info/programming/payment-gateway/paypal-direct-payment-integration-NVP-made-easy.htm#sthash.AXWQQyXo.dpuf.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// DoDirectPayment NVP example; last modified 08MAY23.
 
$environment = 'sandbox';   // or 'beta-sandbox' or 'live'
 
// Set request-specific fields.
//$paymentType = urlencode($_POST['Authorization']);                // or 'Sale'
$paymentType =  'Sale';
$firstName =urlencode($_POST['firstname']);
$lastName = urlencode($_POST['lastname']);
$creditCardType = urlencode($_POST['cardtype']);
$creditCardNumber = urlencode($_POST['cardnumber']);
$expDateMonth = $_POST['cardmonth'];
// Month must be padded with leading zero
$padDateMonth = urlencode(str_pad($expDateMonth, 2, '0', STR_PAD_LEFT));
 
$expDateYear = urlencode($_POST['cardyear']);
$cvv2Number = urlencode($_POST['cardcvv']);
$address1 = urlencode($_POST['address']);
$address2 = '';
$city = urlencode($_POST['city']);
$state = urlencode($_POST['state']);
$zip = urlencode($_POST['zip']);
$country = 'US';    // US or other valid country code
$amount = '1.00';   //actual amount should be substituted here
$currencyID = 'USD';// or other currency ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')
Make a query string from the above post data which will be posted to the gateway in the following function.
?
1
2
3
4
// Add request-specific fields to the request string.
$nvpStr =   "&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
            "&EXPDATE=$padDateMonth$expDateYear&CVV2=$cvv2Number&FIRSTNAME=$firstName&LASTNAME=$lastName".
            "&STREET=$address1&CITY=$city&STATE=$state&ZIP=$zip&COUNTRYCODE=$country&CURRENCYCODE=$currencyID";
and we call the function PPHttpPost with the post string as argument. This function is included to seperate the code from the actual request CURL code. Just like that. No other purpose. Just readability. The function returns an array with the data from the payment gateway. The key ACK holds whether the process was a success or a failure. Now let us see what is in that function PPHttpPost.
?
1
2
3
         
// Execute the API operation; see the PPHttpPost function above.
$httpParsedResponseAr = PPHttpPost('DoDirectPayment', $nvpStr);
Now the above associative array which is the actual key value pairs which the payment gateway understands is converted into a query string. The query string which is to be posted to the payment gateway is stored in $post_string.
In this function we append the key value pairs of the username, password and signature to the post data query string which we already created.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// here the variable $methodName_ holds the string 'DoDirectPayment' and $nvpStr_ holds the query string from the post data.
 
function PPHttpPost($methodName_, $nvpStr_) {
    global $environment;
 
    // Set up your API credentials, PayPal end point, and API version.
    $API_UserName = urlencode('sdk-three_api1.sdk.com');
    $API_Password = urlencode('QFZCWN5HZM8VBG7Q');
    $API_Signature = urlencode('A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU');
    $API_Endpoint = "https://api-3t.paypal.com/nvp";
    if("sandbox" === $environment || "beta-sandbox" === $environment) {
        $API_Endpoint = "https://api-3t.$environment.paypal.com/nvp";
    }
    $version = urlencode('51.0');
     
    // Set the API operation, version, and API signature in the request.
    $nvpreq = "METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";
    
Now we connect and post the data to the payment gateway using the following curl functions. The line where this code is $httpResponse = curl_exec($ch); will fetch the response and stores in the variable $httpResponse.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Set the curl parameters.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $API_Endpoint);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
// Turn off the server and peer verification (TrustManager Concept).
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
// Set the request as a POST FIELD for curl.
curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
// Get response from the server.
$httpResponse = curl_exec($ch);
 
if(!$httpResponse) {
    exit("$methodName_ failed: ".curl_error($ch).'('.curl_errno($ch).')');
}
We now convert the string returned from the payment gateway into an array using the explode function and foreach.
?
1
2
3
4
5
6
7
8
9
10
// Extract the response details.
$httpResponseAr = explode("&", $httpResponse);
 
$httpParsedResponseAr = array();
foreach ($httpResponseAr as $i => $value) {
    $tmpAr = explode("=", $value);
    if(sizeof($tmpAr) > 1) {
        $httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];
    }
}
Here if some thing had gone wrong like connection interrupted or timeout then we end up inside the following if condition which means we got an invalid data from the payment gateway. If the response is good then we return the array to the code where it was called and that is where we call the function PPHttpPost.
?
1
2
3
4
5
if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {
    exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");
}
 
return $httpParsedResponseAr;
According to the key ACK in the return array we determine whether the payment was successful or not. So if the key ACK of the returned array holds success the you know what to do. Just do print_r and find the return values of the payment gateway and use it according to your need. You can store the transaction id from the response for furture reference about the payment.
?
1
2
3
4
5
6
7
echo '<pre>';
print_r($_POST);
if("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
    exit('Direct Payment Completed Successfully: '.print_r($httpParsedResponseAr, true));
} else  {
    exit('DoDirectPayment failed: ' . print_r($httpParsedResponseAr, true));
}
Here is a sample of a success response and a failure response code from the payment gateway.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Array
(
    [TIMESTAMP] => 2011%2d05%2d02T14%3a57%3a49Z
    [CORRELATIONID] => 1cbb3c7e41a85
    [ACK] => Success
    [VERSION] => 51%2e0
    [BUILD] => 1824201
    [AMT] => 1%2e00
    [CURRENCYCODE] => USD
    [AVSCODE] => X
    [CVV2MATCH] => M
    [TRANSACTIONID] => 5HE739037S988281B
)
 
Array
(
    [TIMESTAMP] => 2011%2d05%2d02T14%3a59%3a36Z
    [CORRELATIONID] => 184ff2d4c696
    [ACK] => Failure
    [VERSION] => 51%2e0
    [BUILD] => 1824201
    [L_ERRORCODE0] => 10527
    [L_SHORTMESSAGE0] => Invalid%20Data
    [L_LONGMESSAGE0] => This%20transaction%20cannot%20be%20processed%2e%20Please%20enter%20a%20valid%20credit%20card%20number%20and%20type%2e
    [L_SEVERITYCODE0] => Error
    [AMT] => 1%2e00
    [CURRENCYCODE] => USD
)
// It says This transaction cannot be processed. Please enter a valid credit card number.
 This happened when i entered an invalid sample card number.
 In sandbox mode the data which i had pouplated in the form is given by paypal to test a success result;

Click Here to Download source code

No comments:

Post a Comment

Designed By Published.. Blogger Templates