Search code examples
c#.netpaypal

Paypal Rollback / Refund IPN if database update fails?


I am wondering how I should handle a situation where a customer was billed for digital goods, so then the IPN is called and I deliver the digital good. What happens if something goes wrong in the delivery process? How should this case be handled? Is there something I can do to cancel / refund in this case?

I'm basing my IPN code off of a sample I found

protected void Page_Load(object sender, EventArgs e)
{
    //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")
    {
        //UPDATE YOUR DATABASE

        //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")
    {
        //UPDATE YOUR DATABASE
    }
    else
    {  //UPDATE YOUR DATABASE
    }
}

What if my updating of the database fails?


Solution

  • First, I would make sure to use clean SQL statements so that database errors won't occur. If there is a connection error with the database you could return a 500 response and PayPal's IPN system would keep retrying until it receives a successful 200 OK response.

    If you do want to submit a refund based on any failures within the script you could do that via the RefundTransaction API.