Hack 65 Receive Instant Payment Notifications

figs/moderate.gif figs/hack65.gif

Set up the IPN system to have PayPal automatically send transaction details to your server to process immediately after receiving a payment.

PayPal makes it easy for merchants to accept payments by placing payment buttons on their web sites. While this system can be sufficient to initiate transactions, it does nothing to help process payments once they're made. IPN fills this gap.

PayPal's IPN feature sends a behind-the-scenes server-to-server post to a page of your choice, almost instantly after a customer clicks the Pay button and completes the transaction at the PayPal web site.

To begin using IPN, log into PayPal, click Profile, and then click Instant Payment Notification Preferences to see the screen shown in Figure 7-1. Turn on the feature by checking the box, and then specify the URL of the script on your server that you would like to receive the transaction details.

Figure 7-1. Using the Instant Payment Notification Preferences page to enable IPN and specify the location of your transaction-processing script

The address you specify will never be seen by your customers and should contain only Common Gateway Interface (CGI) code or dynamic server technology, such as PHP, JSP, Perl, or ASP (explained later in this hack).

7.5.1 The Code

Here is the sample IPN code, which is available from the PayPal web site. It's written in VBScript for Active Server Pages (ASP), which means you need a server capable of handling Microsoft Active Server Pages. If you'd rather develop your IPN script in Perl, PHP, or JSP, you can get the corresponding sample code at http://www.paypal.com, but the concepts discussed here will be the same, regardless of the platform you're using (see the "Database Coding and Platform Choices" section of the Preface for further information).



Dim Item_name, Item_number, Payment_status, Payment_amount

Dim Txn_id, Receiver_email, Payer_email

Dim objHttp, str

' read post from PayPal system and add 'cmd'

str = Request.Form & "&cmd=_notify-validate"

' post back to PayPal system to validate

set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")

objHttp.open "POST", "https://www.paypal.com/cgi-bin/webscr", false

objHttp.setRequestHeader "Content-type", "application/x-www-form-urlencoded"

objHttp.Send str

' assign posted variables to local variables1.

1. Item_name = Request.Form("item_name")

Item_number = Request.Form("item_number")

Payment_status = Request.Form("payment_status")

Payment_amount = Request.Form("mc_gross")

Payment_currency = Request.Form("mc_currency")

Txn_id = Request.Form("txn_id")

Receiver_email = Request.Form("receiver_email")

2.  Payer_email = Request.Form("payer_email")

' Check notification validation

if (objHttp.status <> 200 ) then

 ' HTTP error handling

elseif (objHttp.responseText = "VERIFIED") then

3.  if Payment_status = "Completed" Then

4.  ' check that Txn_id has not been previously processed

  ' check that Receiver_email is your Primary PayPal email

5.  if Receiver_email = "youremail@yourisp.com" Then 'Email is correct

  ' check that Payment_amount/Payment_currency are correct

6.  ' process payment

  end If

7.  end If

elseif (objHttp.responseText = "INVALID") then

 ' log for manual investigation


 ' error

end if

set objHttp = nothing


7.5.2 Running the Code

The first section of code with which to be concerned, from line 1 to line 2, retrieves the values passed to you by PayPal and assigns them to variables. Field formats and descriptions for the 50 supported variables can be found in the Integration Guide, available at https://www.paypal.com/ipn.

The next section, from line 3 to 7, contains code to check the transaction and process the order. Simply replace the commented lines of pseudocode with your own code.

Now, you'll need to complete several steps to process a transaction. The first If/Then statement (line 3) checks to see if the Payment_status variable has a value of Completed.

Next, you'll need to check that the transaction ID has not been previously processed (line 4). One way to accomplish this is to record the txn_id value into a database [Hack #54] . Then, query the table, pull the results into a recordset named rsCheck, and then check to see whether the record exists:

' check that Txn_id has not been previously processed:

connStore = "DRIVER={Microsoft Access Driver (*.mdb)};


set rsCheck = Server.CreateObject("ADODB.Recordset")

rsCheck.ActiveConnection = connStore

rsCheck.Source = "SELECT txn_id FROM tblOrders WHERE txn_id = 

                '" & txn_id & "'"

rsCheck.Open( )

If rsCheck.EOF And rsCheck.BOF Then 'Not a duplicate, continue processing

 ' check that Receiver_email is your Primary PayPal email

 ' check that Payment_amount/Payment_currency are correct

 ' process payment

End If

See the "Database Coding and Platform Choices" section of the Preface for the additional information needed to put this SQL statement to work with this and the other hacks in this book.

You might want to process pending payments (typically from eChecks) so that you can automatically notify customers that there will be a delay in fulfilling the order. If the payment_status value is Pending, you can record the pending payment into your database table, but you will also need to adjust your duplicate transaction query to ignore the pending transactions you would otherwise be recording. Pending payments ultimately post two notifications to your IPN script: one when the purchase is made (with a status of Pending) and a second when the payment has cleared (with a status of Completed).

Finally, the check on line 5 compares the recipient's email address with your address to ensure that the IPN was not spoofed. You also want to make sure that the price has not been tampered with [Hack #73] When all is said and done, replace line 6 with your own server logic to process the order.