Thursday, June 7, 2012

Paypal IPN and PDT in ASP.net

To support a customer who needs to process payments through Paypal, I created a small code package that encapsulates the functionality necessary for the operations used in Paypal's Payment Data Transfer (PDT) and Instant Payment Notification (IPN). This way, the code is reusable for future projects within Rubicite. I'm sharing it on Github, so that it can save some time for the rest of the world: https://github.com/jgb146/Paypal-util

Most of the functionality involved is derived from various tutorials in Paypal's documentation, but this way everything is encapsulated into a single pdt_hander object, or a single ipn_handler object (depending on which technology you're using). The resulting object automatically takes the steps required for confirming the contents with Paypal, and then provides you with access to your payment information through a Dictionary.

To use either component, simply instantiate the object and provide the required information. For PDT, that means including the transaction ID that Paypal sent, your PDT ID token, and an optional boolean to indicate whether or not you are using Paypal's sandbox. For IPN, the only parameter to include is an optional boolean to indicate whether or not you are using Paypal's sandbox. Use looks roughly like this:

IPN:
protected void Page_Load(object sender, EventArgs e)
{
    processIpnPost();
            
    Response.Clear();
    Response.StatusCode = 200;
    Response.Write("");
    Context.ApplicationInstance.CompleteRequest();
}

public void processIpnPost()
{//process the IPN post
    
    //use ipn_handler util to get response and load into a dictionary
    PayPalUtil.ipn_handler ipn_handler = new PayPalUtil.ipn_handler();
    Dictionary dic_ipnResponse = ipn_handler.dic_data;
    
    //deal with invalid responses
    if (dic_ipnResponse["response"] != "VERIFIED")
        return;

    //---Insert code to use dic_ipnResponse to process the transaction
}

PDT:
protected void Page_Load(object sender, EventArgs e)
{
    ProcessTransaction();
}

protected void ProcessTransaction()
{
    //deal with unspecified transactions
    if ((Request["tx"] == null) || (Request["tx"] == ""))
    { 
        InvalidTransaction();
        return; //stop processing; 
    }
                
    //use the transactionID in the GET to request & process PDT data
    my_pdt_handler = new PayPalUtil.pdt_handler(Request["tx"], PDT_ID_Token);

    //deal with invalid responses
    if (my_pdt_handler.dic_data["response"] != "VERIFIED")
    { 
        InvalidTransaction(Request["tx"], my_pdt_handler.dic_data);
        return; //stop processing; 
    }

    //---Insert code to use my_pdt_handler.dic_data to process the transaction           
}

protected void InvalidTransaction(String pStr_transactionID = "", Dictionary pDic_data = null)
{//invalid transaction -> handle however you feel is best

}

No comments:

Post a Comment