Click here to Skip to main content
15,850,214 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (19 votes)
29 May 2010CPOL3 min read 98.1K   37   12
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#.


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.


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 Language="C#" Option="Explicit"  runat="server">
void Send_download_link (string from,  string to, string subject, string body)   
   {  // 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 = "";
	string strLive = "";
	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);
	StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
	string strResponse = streamIn.ReadToEnd();
	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 ("",  
                 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
		//log response/ipn data for manual investigation
}  // --- end of page load --

<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

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., 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.


  • 29th May, 2010: Initial version


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer (Senior) BSC Inc
United States United States

Becker Cuéllar is an independent developer(C#/C++/J2ME/VB/perl) on the Washington DC corridor and focuses on developing/integrating web interfaces with Databases(MSSQL, MySQL, Oracle, Sybase), with mobile devices, scripting(perl/php/javascript) and with MS and Linux(RHE) based backends. Aditionally a full Mobile architect/developer for custom applications for Windows Mobile NETCF , Blackberry J2ME, Android, PalmOS and iPhone.

You'll find him traveling and hiking somewhere on this planet when not working on a project or on a road course race track tweaking his engine and attempting to improve his lap times.

Comments and Discussions

QuestionWhere's the code? Pin
soraco27-Jan-16 10:27
soraco27-Jan-16 10:27 
Questionset up IPN page Pin
HHugu1324-Apr-15 1:44
HHugu1324-Apr-15 1:44 
Questionpaypal recurring payment ipn notification on second transcation Pin
Member 1018961610-Dec-14 20:00
professionalMember 1018961610-Dec-14 20:00 
GeneralMy vote of 5 Pin
John Ristuccia21-May-14 15:59
John Ristuccia21-May-14 15:59 
QuestionThis helped me, has more than I found on PayPal Pin
mgp2214-May-12 14:54
mgp2214-May-12 14:54 
GeneralReason for my vote of 5 good! Pin
WESTSEYI28-Dec-11 13:34
WESTSEYI28-Dec-11 13:34 
GeneralThanks, this was helpful. Anything that improves on the poo... Pin
Robert Pittenger, MCPD-EAD5-May-11 3:50
Robert Pittenger, MCPD-EAD5-May-11 3:50 
GeneralReason for my vote of 1 This is basically a copy of http://w... Pin
yannlh16-Jan-11 15:37
yannlh16-Jan-11 15:37 
GeneralRe: Hello Coming down from a tough hike up in the Andes so no... Pin
becker66617-Jan-11 5:38
becker66617-Jan-11 5:38 
GeneralRe: Hello Coming down from a tough hike up in the Andes so no... Pin
mgp2214-May-12 14:54
mgp2214-May-12 14:54 
GeneralReason for my vote of 5 Great! Thank you very much for this ... Pin
Fritz Schmidt25-Jan-11 1:22
Fritz Schmidt25-Jan-11 1:22 
GeneralAdded value Pin
yannlh16-Jan-11 15:39
yannlh16-Jan-11 15:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.