Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

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

, 29 May 2010
Rate this:
Please Sign up or sign in to vote.
Sample working C# code to carry the IPN

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 suppossedly 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 downnload 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 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 specially checking your account number and may be some extra processing and all of that can be hooked up to the "listener" page . e.g. I needed to add the buyers to a mail list for sending them notifications.

 

License

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

Share

About the Author

becker666
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

 
GeneralMy vote of 5 PinmemberJohn Ristuccia21-May-14 14:59 
QuestionThis helped me, has more than I found on PayPal Pinmembermgp2214-May-12 13:54 
GeneralReason for my vote of 5 good! PinmemberWESTSEYI28-Dec-11 12:34 
GeneralThanks, this was helpful. Anything that improves on the poo... PinmemberRobert Pittenger, MCPD-EAD5-May-11 2:50 
GeneralReason for my vote of 1 This is basically a copy of http://w... Pinmemberyannlh16-Jan-11 14:37 
GeneralRe: Hello Coming down from a tough hike up in the Andes so no... Pinmemberbecker66617-Jan-11 4:38 
GeneralRe: Hello Coming down from a tough hike up in the Andes so no... Pinmembermgp2214-May-12 13:54 
GeneralReason for my vote of 5 Great! Thank you very much for this ... PinmemberFritz Schmidt25-Jan-11 0:22 
GeneralAdded value Pinmemberyannlh16-Jan-11 14:39 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 29 May 2010
Article Copyright 2010 by becker666
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid