Paypal #IPN in C#- the basics.
After you get a payment from paypal, you can simply redirect the user back to your website in order to record the purchase in your database, but this has serious problems, one is that customers can often close their browser after payment so you don’t record the payment, or a cheeky customer might try bypassing paypal and go straight to your order processing “thank you” page, and might get your service for free.
Paypal IPN gets around both of these problems, one is that it doesn’t matter if the user closes the browser, it will get called anyway. Secondly, it can’t be called manually, since the IPN payload gets verified against Paypal, so that it can’t be faked.
What is Paypal IPN?
It’s simply the parameter notify_url is set to a url on your server, and you include this parameter in the /webscr url in the “buy now” button. This url gets called by Paypal’s servers. You add &cmd=_notify-validate to the post data, and post it back to paypal for validation. If paypal returns “VERIFIED” then you can provide whatever service you need to the customer. – There are some other security checks you can do here too, to make sure the user is paying in the expected currency, and the expected amount.
And here’s the code (Adapted from Paypal’s VB.NET version):
var param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
var strRequest = Encoding.ASCII.GetString(param);
strRequest = strRequest + “&cmd=_notify-validate”;
var strLive = “https://www.paypal.com/cgi-bin/webscr”;
var req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = “POST”;
req.ContentType = “application/x-www-form-urlencoded”;
req.ContentLength = strRequest.Length;
var streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
var streamIn = new StreamReader(req.GetResponse().GetResponseStream());
var strResponse = streamIn.ReadToEnd();
var ipn = Request.Form.AllKeys.ToDictionary(k => k, k => Request[k]);
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//log for manual investigation
//Response wasn’t VERIFIED or INVALID, log for manual investigation