Hack 85 Process Payments like a Credit Card with PDT

figs/moderate.gif figs/hack85.gif

Use PDT to transact payments synchronously and deliver your product or confirmation screen immediately?and without waiting for the IPN postback.

As explained in the introduction to this chapter, PDT is one of two technologies (along with IPN) that are used to send transaction information back to your server. PDT has the distinct advantage of allowing you to provide a seamless transition from payment to delivery of goods.

To use PDT with your web site, you must first configure some options in your PayPal Profile:

  1. Log into PayPal and click the My Account tab.

  2. Click Profile and then click the Website Payment Preferences link.

  3. Change the Auto Return option to On.

    It's vital that you turn on the Auto Return option. Without it, PDT won't work at all.

  4. Enter a return URL: the address of a page (or more specifically, a script) on your site that can process the information sent back to it from PayPal and display an order summary to each customer. Details of this page follow.

  5. Change the Payment Data Transfer option to On.

Your site is now configured for use with PDT.

When you save your PDT preferences, an identity token is generated and appears with a message at the top of the Website Payment Preferences page. In future visits, your identity token appears in the Payment Data Transfer section, below the On and Off options. Eventually, you will need to pass this identity token, along with the transaction token, to PayPal in order to confirm that a payment is complete.

When a transaction has completed, PayPal redirects the customer to the URL you specify, with the following transaction parameters (among others) appended to the URL:

Transaction number (tx)

The most important of the parameters sent back by PayPal. Use this in the next section to get the full set of transaction information.

Status (st)

The status of the transaction, normally set to Completed.

Amount of sale (amt)

The dollar (or whatever currency used) amount of the sale.

Currency (cc)

The three-digit currency code indicating the currency used for the sale.

Once PayPal has sent this information to your site (e.g., the URL supplied in the return URL parameter), the rest is up to you and your web site in terms of how to record the transaction and fulfill the order. In the next section, you'll see how this is done.

7.25.1 PDT in Action

At this point, all that's left is to make sure you have a PDT handling page for the return trip. This example is written in C# for Microsoft ASP.NET.

The first order of business for the handling page (PDTHandler.aspx) is to grab the transaction number from the URL:

String strTransactionID=Request.QueryString["tx"].ToString( );

This is where the identity token comes into play. You'll need to POST a form request and send the identity token and the transaction ID back to PayPal, as well as set a command parameter (cmd) to notify-synch. The result of this exchange will be the full PDT suite of information. To do this programmatically using C#, open a request against PayPal's server, and then place the response into a string variable:

string sOut = "";

string MyIDToken = "MyIdentityToken";

string transactionID = Request.QueryString["tx"].ToString( );

string sCmd = "_notify-synch";

string serverURL = "https://www.paypal.com/cgi-bin/webscr";


 string strFormValues = Request.Form.ToString( );

 string strPassValue;

 string strResponse;

 // Create the request back

 HttpWebRequest req = (HttpWebRequest) WebRequest.Create(serverURL);

 // Set values for the request back

 req.Method = "POST";

 req.ContentType = "application/x-www-form-urlencoded";

 //Append the transaction ID, ID Token, and command

 //to the form 

 strPassValue = strFormValues + 

           "&cmd = _notify-synch&at = "+MyIDToken+"&tx = "+transactionID;


 req.ContentLength = strPassValue.Length;

 // Write the request back IPN strings

 StreamWriter stOut = new StreamWriter (req.GetRequestStream( ),




 stOut.Close( );

 // Do the request to PayPal and get the response

 StreamReader stIn = new StreamReader(req.GetResponse( ).GetResponseStream( ));


 strResponse = stIn.ReadToEnd( );


 stIn.Close( );

 sOut= Server.UrlDecode(strResponse);

} catch(Exception x){

 //if there is an error with the PDT response,

 //you will need to handle it here, making sure you trap

 //the raw PDT (if received) as well as the transactionID

 //etc so you can query PayPal again should anything go



You can only query PayPal for the PDT response a limited number of times per transaction. After five unsuccessful responses from PayPal, you will no longer be able to query for the transaction details. This limit has been imposed for PayPal performance and security reasons. For more mission-critical applications, or if your server's connection to the Internet is flaky, you might want to employ IPN as well.

The data you receive in the PDT response is a grouping of name=value pairs, with the first parameter set to either SUCCESS or FAILURE.

To see the full output of the PDT, refer to the Payment Data Transfer Manual, available at https://www.paypal.com/pdt.

Once the PDT response is placed into a string variable, loop through the string and pull out the data you need to record the order:

string GetPDTValue(string key){

 1.  String [] PDTbits=PDT.Split('\n');

 string theField="";

 string theValue="";

 string thisLine="";

 string sOut="";

2.  for(int i=0;i< PDTbits.Length;i++){

  thisLine=PDTbits[i].ToString( );

3.  if(thisLine.IndexOf("=")>-1){



4.  if(theField==key){

    sOut = theValue;




 return sOut;


The PDT data is sent back in a single string using a linefeed as the record delimiter. On line 1, the split routine is used to assemble an array from these records. Then, the script loops (line 2) through the array, looking for the key=value pairs (line 3). When the specified key is found (line 4), the return variable, sOut, is set with the key name.

Using this GetPDTValue function, you can pull out any individual values you need to record the order into your database and prepare a nice receipt page for the customer (one of the tasks you must perform when you use PDT). For the full list of PDT parameters, refer to the Payment Data Transfer Manual.

7.25.2 Tracking Your Users: Before and After

If you decide to personalize the shopping experience for each customer, it is important to know who is buying what from your site. If you have any kind of customer login, you need to pass this information to PayPal so that you'll know who your customers are when they return to your site.

A great way to track your user before and after the PayPal transaction is to send along the user's identifier in the custom parameter [Hack #28] . To do so, use the following code, where user_ID is some identifying number or string assigned to the particular customer (usually an integer key from a database):

<input type=hidden name="custom" value="user_ID">

When this value is returned to you in the PDT response, you can retrieve it using the GetPDTValue from the previous section:

string strCustomerID=GetPDTValue("custom");

You could also use HTTP cookies to do this, but the custom field is more reliable, because it won't break if the customer has configured her browser to reject cookies.

7.25.3 Retrieving the Order

PayPal sends the items purchased in a simple numbered sequence. For a single-item purchase, PayPal returns a simple parameter called item_number:


When a customer purchases more than one item, PayPal adds an integer value to the end of each parameter to identify the item number, like this:




The values to the right of the equals signs correspond to the product IDs you send PayPal, presumably taken from your database (these could be SKU codes, product names, or whatever). See [Hack #45] to use PDT with PayPal's Shopping Cart, or check out [Hack #50] if you're using your own shopping cart system.

The following code retrieves the details of an order:

string productNumber=GetPDTValue("item_number");

1.  if(productNumber!=""){

 //only one item purchased

2.  //process order here


 string itemTag="item_number";

 string thisItem="";

3. for(int i =0; i < 1000; i++){

  thisItem = itemTag + i.ToString( );

  productNumber = GetPDTValue(thisItem);



4. //process shopping cart item here


   //no more items found; exit the loop





Since the item_number field is present if only a single item was ordered, the first check (line 1) redirects the code if the field exists. Otherwise, the code proceeds to the next section, which begins a loop (line 3) to look for multiple items in the Shopping Cart. Either way, you must add code (on lines 2 and 4 to retrieve the quantity and other details from the PDT data string using the same GetPDTValue function.

?Rob Conery