< Day Day Up > |
Use PDT to transact payments synchronously and deliver your product or confirmation screen immediatelyand 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:
Your site is now configured for use with PDT.
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:
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 ActionAt 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 }
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 .
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 AfterIf 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 OrderPayPal 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 |
< Day Day Up > |