Skip to content

Instantly share code, notes, and snippets.

@devfred
Last active October 12, 2015 05:48
Show Gist options
  • Save devfred/3980454 to your computer and use it in GitHub Desktop.
Save devfred/3980454 to your computer and use it in GitHub Desktop.
csharp: Simple Handler that listens for PayPal Instant Payment Notifications
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
public class PayPalIPN : IHttpHandler
{
/**
This property says if the http runtime can reuse the current
instance of the http handler while serving another request
@property {bool} IsReusable
**/
public bool IsReusable { get {return false;} }
/**
This property will be used to avoid passing the context between functions
@property {HttpContext} MyContext
**/
private HttpContext MyContext;
/**
This method processes the http request from start
to finish and is responsible for processing and input and producing output
@function ProcessRequest
@parameter{HttpContext} context
**/
public void ProcessRequest (HttpContext context) {
//Post back to either sandbox or live
string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
strRequest += "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
//req.Proxy = proxy;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED")
{
//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
//process payment
}
else if (strResponse == "INVALID")
{
//log for manual investigation
}
else
{
//log response/ipn data for manual investigation
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment