Paypal PDT (Sample code for validating transaction when auto return from Paypal)

This post is continue of my previous post:
» Auto Return users from Paypal on successful payment and introduction to PDT

In previous post, we have successfully completed setting up the Paypal Auto Return and Payment Data Transfer (PDT) features on Paypal. In this post, we will be adding up transaction validation code to our return url so that, we can finally give access to the users into our members area.

Below I am listing the whole process being followed from when the user clicks buy now button to when they are given access to members area.

  • First of all, user clicks on the buy now button and is taken to the paypal for payment. Paypal displays the lists of available methods of payment so that user can pay for the item they want to purchase.
  • After successful payment, user is redirected to the return URL setup in Paypal, with certain parameters appended to the URL. If you haven’t setup/enable the Paypal Auto Return and Payment Data Transfer option in your Paypal Business Account, then click here to read my previous post on Auto Return users from Paypal on successful payment and introduction to PDT
  • Return URL is where we have the transaction validation code. As paypal redirects the user with certain parameters, as tx=, amount, quantity, etc. our script, would validate these locally and then send a request to Paypal for confirmation. While requesting paypal, we will need PDT Identity Token from paypal to verify which I am going to explain in more details below.
  • As the request is send to Paypal, Paypal verifies the request and responds back with the complete transaction details. Transaction details consists of each and every attributes which we need to validate again with our script to avoid fraudulent transactions.
  • Once validation succeeds, we can show user with success message, create member and redirect them to members area, or anything the payment was made for.

Paypal PDT Identity Token

Paypal PDT Token is an access token that uniquely identifies your account. Like any other access token, this is required to request Paypal for any transaction details within your account, and to prevent any non authenticated users from requesting the details.

If you have gone through my previous post, you might have already known how this token is generated. On Website Payment Preferences page, after you enable Auto Return and Payment Data Transfer and click save, you will be redirected to My Profile page with a message as on screenshot below:
paypa-pdt-identity-token

which displays the PDT Identity token. You can access this token anytime from your PDT section on Website Payment Preference page.

Below, is the sample code in PHP for validating transaction using this PDT identity token:

Sample code in PHP for Paypal PDT Transaction Validation

Once payment is successful, user is redirected to Return URL with certain parameters appended to the URL with transaction id. Grab this transaction id from URL and validate transaction by communicating with Paypal and execute script to process order.

// defining some constants
define("USE_SANDBOX", 1);
define("PDT_TOKEN", "your PDT Identity Token");
define("VERIFY_EMAIL", 'Your email for Business Paypal');
define("VERIFY_CURRENCY", 'Currency to be verified');
define("VERIFY_AMOUNT", 'Amount to be verified');


function alreadyExist($txid){
	// check if this transaction id has already been processed	
}

function processOrder(){
	// process the Order
	// create member or get users access to item what they had paid for	
}
if(isset($_GET['tx']) && ($_GET['tx'])!=null && ($_GET['tx'])!= "") {
	
	$txn_id = $GET['tx'];
	$request = 'cmd=_notify-synch';
	$auth_token = PDT_TOKEN;
	$request .= "&tx=$txn_id&at=$auth_token";
	
	// post back to PayPal system to validate
	$header .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
	$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
	$header .= "Host: www.paypal.com\r\n";
	$header .= "Content-Length: " . strlen($request) . "\r\n";
	$header .= "Connection: close\r\n\r\n";
	
	if(USE_SANDBOX == true)
		$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30); 
	else
		$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
	
	if (isset($fp) && $fp) {
		fputs ($fp, $header . $req);
		// read the body data
		$res = '';
		$headerdone = false;
		while (!feof($fp)) {
			$line = fgets ($fp, 1024);
			if (strcmp($line, "\r\n") == 0) {
				// read the header
				$headerdone = true;
			}
			else if ($headerdone) {
				// header has been read. now read the contents
				$res .= $line;
			}
		}
		
		// parse the data
		$lines = explode("\n", $res);
		
		$response = array();
	
		if (strcmp ($lines[1], "SUCCESS") == 0) {
	
			for ($i=1; $i<count($lines);$i++){
				list($key,$val) = explode("=", $lines[$i]);
				$response[urldecode($key)] = urldecode($val);
			}
	
			$itemName = $response["item_name"];
			$amount = $response["payment_gross"];
			$email = $response["receiver_email"];
			$userEmailPaypalId = $response["payer_email"];
			$paymentStatus = $response["payment_status"];
			$TxId = $response["txn_id"];
			$currency = $response["mc_currency"];
			
			// check the payment_status is Completed, receiver email is your paypal account, currency and amount are correct
			if($paymentStatus=="Completed" && $email == VERIFY_EMAIL && $currency == VERIFY_CURRENCY && $amount == VERIFY_AMOUNT) {
				// check that txn_id has not been previously processed			
				if(!alreadyExist($TxId)){					
					// process the order
					processOrder();
				}
			}
		} 
	}
	fclose ($fp);
} else {
    // Display appropriate error message
}

Leave a Reply

Your email address will not be published. Required fields are marked *