PayPal Hacks. 100 Industrial-Strength Tips and Tools Free Open Book

PayPal Hacks. 100 Industrial-Strength Tips and Tools

Previous Section  < Day Day Up >  Next Section

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";



try{

 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( ),

                 System.Text.Encoding.ASCII);

 

 stOut.Write(strPassValue);

 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

 //wrong

}

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){

   theField=thisLine.Substring(0,thisLine.IndexOf("="));

   theValue=thisLine.Remove(0,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:

item_number=HTHTKEPO

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:

item_number1=HTHTKEPO

item_number2=DREGFEF

item_number3=ERTRTDFD

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



}else{

 string itemTag="item_number";

 string thisItem="";



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

  thisItem = itemTag + i.ToString( );

  productNumber = GetPDTValue(thisItem);

  

  if(productNumber!=""){



4. //process shopping cart item here



  }else{



   //no more items found; exit the loop

   break;



  }

 }

}

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

    Previous Section  < Day Day Up >  Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


         Main Menu
    PayPal Hacks
    Table of Contents
    Copyright
    Credits
    Preface
    Chapter 1. Account Management
    Chapter 2. Making Payments
    Chapter 3. Selling with PayPal
    Chapter 4. Payment Buttons
    Chapter 5. Storefronts and Shopping Carts
    Chapter 6. Managing Subscriptions
    Chapter 7. IPN and PDT
    Introduction: Hacks #65-86
    What IPN and PDT Are
    How IPN Works
    Advantages of PDT
    Hack 65 Receive Instant Payment Notifications
    Hack 66 Troubleshoot Instant Payment Notifications
    Hack 67 Send a Purchase Confirmation Email with IPN
    Day Day Up
    Hack 69 Use IPN with eBay Listings
    Hack 70 Track Your eBay Products with IPN
    Hack 71 Deliver Digital Goods with IPN
    Hack 72 Deliver Digital Goods with a Return Page
    Hack 73 Implement Price Checking with IPN
    Hack 74 Provide an Order Summary with IPN
    Hack 75 Upsell Your Customers
    Hack 76 Enable Multiple IPN Pages
    Hack 77 Use Mass Pay to Create an Affiliate System
    Hack 78 Manage Your Inventory with IPN
    Hack 79 Display Donation Goals on Your Web Site
    Hack 80 Display a Recent Donor List
    Hack 81 Capture Customer Information with IPN
    Hack 82 Insert Payment Details into a Database with IPN
    Hack 83 Insert Cart Details into a Database
    Hack 84 Track Google Referrals
    Hack 85 Process Payments like a Credit Card with PDT
    Hack 86 Synchronizing PDT and IPN
    Chapter 8. The PayPal Web Services API
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele