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

1.Introduction  2.Code and Explanation  3.Download Source Code  4.Comments


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.
Personal Details
First Name
Last Name
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..

// 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.
// Add request-specific fields to the request string.
$nvpStr =	"&PAYMENTACTION=$paymentType&AMT=$amount&CREDITCARDTYPE=$creditCardType&ACCT=$creditCardNumber".
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.
// 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.

// 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('');
	$API_Password = urlencode('QFZCWN5HZM8VBG7Q');
	$API_Signature = urlencode('A-IzJhZZjhg29XQ2qnhapuwxIDzyAZQ92FRP5dqBzVesOkzbdUONzmOU');
	$API_Endpoint = "";
	if("sandbox" === $environment || "beta-sandbox" === $environment) {
		$API_Endpoint = "https://api-3t.$";
	$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.
	// 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_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.
	// 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.

	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.
echo '<pre>';
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.
    [TIMESTAMP] => 2011%2d05%2d02T14%3a57%3a49Z
    [CORRELATIONID] => 1cbb3c7e41a85
    [ACK] => Success
    [VERSION] => 51%2e0
    [BUILD] => 1824201
    [AMT] => 1%2e00
    [AVSCODE] => X
    [CVV2MATCH] => M
    [TRANSACTIONID] => 5HE739037S988281B

    [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
// 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;

Download Source Code

The zip file contains the html form and the php payment script. These are the basic files you need.
Click here to download the paypal payment gateway direct payment method code

That is all folks. Enjoy.

By -

Comments, Suggestions, Objections, ...