Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Setting up PayPal Instant Payment Notification (IPN) with C#

0.00/5 (No votes)
29 May 2010 1  
Sample working C# code to carry the IPN
This article is a summary of how to set up this Instant Payment Notification (IPN) to get full control on my website along with my working code in C#.

Introduction

I wanted to sell some PDA Apps out of my web site and use the PayPal Buy Now button, easy enough, after the transaction was completed by PayPal, an extra email is to be sent to the buyer with a link for the download. Of course, I needed some specific MIME types, although there are some processors that supposedly do this for a fee. I couldn't get a good answer from them regarding the MIME types and file updating policies.
So I decided to look into the PayPal developers site and they had some samples on how to set up this Instant Payment Notification (IPN). It was not so hard and I get the full control on my website. Here is the summary with my working code in C#, using a different backend is similar and just as simple.

Overview

To complete this, definitely the PayPal sandbox is needed so that the code can be debugged and it is free from the PayPal developers link. Create a buyer and a seller account and debug away.

In essence, when the Buy Now button is clicked, PayPal does its processing and at the end, it sends an email to both parties. For the case of fully automated selling electronic media, what is needed is an email with a link for the particular download to be sent to the buyer after this successful transaction. With IPN, this can be implemented on your website and it is very straightforward, all they need is a "listener". When a transaction for an item you have listed occurs, they send this listener a message of the transaction with all of the basic info like buyer/seller/item information as a set of URL query variables (e.g., payer_email=jdoe@mailcom&item_name=killer_App ...), the listener then replies back these parameters passed with an extra token and finally PayPal answers back with a VERIFIED message if it all went well or a failure message.

This is the link with the list of the URL query vars-like from PayPal.

The Listener in C#

Implementing this listener in C# is straightforward if your website hosting has support for .NET. The code below is a modification of the sample from PayPal with the addition of some basic function to carry out the email and of course how to send it after a successful interchange. To make it simpler, it is changed to script mode so all you need is just drop the page on your web site, no need for compiling the project and all of that plus scripting mode is faster. Set the URL of your listener on your PayPal profile as explained in the next section. You may need to do some extra processing once the whole process is verified like checking for certain parameters on your local DB, but those are just fine details.

Let's say we call this file ipn_pal.aspx:

<!--
	OK enough of this VB balloney, let's get real although C# is not real it is close
	let's use it here to handle it
-->
<%@ Page Language="C#"    %>
<%@ Import Namespace =  "System"%>
<%@ Import Namespace =  "System.IO"%>
<%@ Import Namespace =  "System.Text"  %>
<%@ Import Namespace =  "System.Net"  %>
<%@ Import Namespace =  "System.Web"  %>
<%@ Import Namespace =	"System.Net.Mail" %>
 
<script Language="JavaScript">
//Some JavaScript you may need goes here
</script>
 
<script Language="C#" Option="Explicit"  runat="server">
 
void Send_download_link (string from,  string to, string subject, string body)   
{		
   try
   {  // Construct a new e-mail message 
      SmtpClient client = new SmtpClient (smtpClient);
      client.Send (from, to, subject, body);
   } 
   catch (SmtpException ex)
   {
      debuggy.Text = "Send_download_link: " + ex.Message;
         
   } 
} // --- end of Send_download_link --

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);
	string strResponse_copy = strRequest;  //Save a copy of the initial info sent by PayPal
	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

	        // pull the values passed on the initial message from PayPal
	
		  NameValueCollection these_argies = HttpUtility.ParseQueryString(strResponse_copy);
		  string user_email = these_argies["payer_email"];
		  string pay_stat = these_argies["payment_status"];
		  //.
                  //.  more args as needed look at the list from paypal IPN doc
                  //. 
                 
                if(pay_stat.Equals("Completed") )
		{
			Send_download_link ("yours_truly@mycompany.com",  
                 user_email, "Your order",
                 "Thanks for your order this the download link ... blah blah blah" );
		}				
		
		// more checks needed here specially your account number and related stuff
	}
	else if (strResponse == "INVALID")
	{
		//log for manual investigation
	}
	else
	{
		//log response/ipn data for manual investigation
	}
}  // --- end of page load --

</script>
	
<html>
<head runat="server" />
<title>IPN PayPal</title>
<asp:label id="debuggy" runat="server"/>
<h2> my test page</h2>
Load this first to check the syntax of your page
</body>
</html>		 

The sendmail here is the simplest. Your website setting may or may not allow this, but it is not a show stopper.

Enabling IPN on your PayPal and Pointing to the Listener

In your Paypal Account, go to Home->Profile. You will see in the Selling Preferences column a link for the Instant Payment Notification. Enable it and set the Notification URL (listener) to the path on your website, e.g., http://mycoolwebsite.com/ ipn_pal.aspx. That is it.

Final Thoughts

As you can see, it is straightforward. Of course, a bunch of tests should be carried out with the sandbox Seller/Buyer accounts to make sure the flow is proper. Also, more basic checks are needed, especially checking your account number and may be some extra processing and all of that can be hooked up to the "listener" page. For example, I needed to add the buyers to a mail list for sending them notifications.

History

  • 29th May, 2010: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here