Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » User Registration with PayPal

User Registration with PayPal

This article summarizes how to perform a user registration process which requires payment and how to integrate that with PayPal. This sort of process would exist on a web form where you want to charge for registration.

Total page views :  18302
Total downloads :  212
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PayPalSite.zip
 
Become a Sponsor


There has been a lot written about how to handle the IPN return from PayPal so I will not go too deeply into that process, but it seems that there has not been too much written about the initial call to PayPal and that is where I will focus.

This article summarizes how to perform a user registration process which requires payment and how to integrate that with PayPal. This sort of process would exist for instance on a web form where you want to charge for registration.

The problem I set out to solve was to create a web site where I charged some nominal fee for registration. I chose to use PayPal b/c everything had already been set up for you and I did not want to have to worry about ssl and handling credit card information. I understood how to handle things once the PayPal transaction was completed, but I could not figure out how to have a user register, do some database processing, and then if there were some problems with the registration process prevent the user from being forwarded onto PayPal and instead display an error on the registration form such as "Duplicate Email Address" or "UserName already exists". These sorts of scenarios would first require a user to correct them and only after they corrected them, to then be forwarded onto PayPal to pay for the registration.

I first tried downloading the PayPal SDK and using the BuyNowButton. It is an excellent SDK and I was very happy with it, but I could not solve the problem I set out to solve. I tried overloading the OnClick event in my own form, but no matter what it would always forward the user onto PayPal. This is not what I wanted to do. So I took a look at what they were doing and used the same concept for my needs.


The basic premise here is the following:

  1. User comes to the Register.aspx page
  2. User completes form and clicks Submit
  3. The system then performs the relevant checks to ensure that this user has a unique username and email address
  4. if the above condition is true, then forward onto PayPal, if not, then display a message to the user and allow them to correct.

The concept consists of 2 files:

  1. Register.aspx
  2. BuyNow.htm

Register.aspx
--------------------------------------------------------------------

public class Register : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox Email;
protected System.Web.UI.WebControls.TextBox UserName;
protected System.Web.UI.WebControls.TextBox Zip;
protected System.Web.UI.WebControls.Button btnRegister;
protected System.Web.UI.WebControls.Label Message;
protected System.Web.UI.WebControls.TextBox Password;
private void Page_Load(object sender, System.EventArgs e)
{
}
private void btnRegister_Click(object sender, System.EventArgs e)
{
//here is where you would go to the db, perform the necessary checks
//and if there are no errors then you can go to paypal
//One way to handle this, is to insert your user in an INACTIVE status in the db
//and put their UserID into the return url as a parameter. So once they successfully
//make their payment, you can update this userid to an ACTIVE status.
if(!DBErrors)
{
string buyNow = Path.Combine(Server.MapPath("."), "BuyNow.htm");
StreamReader reader =
new StreamReader(@buyNow);
string html = reader.ReadToEnd();
html = String.Format(html, UserID);
HttpResponse resp =
this.Context.Response;
resp.Clear();
resp.Write(html);
resp.Flush();
}
else
{
Message.Text = "There were errors, please try again!";
}
}
private bool DBErrors
{
get { return false; }
}
private int UserID
{
get { return 50; }
}
}

BuyNow.htm
----------------------------------------------------------------------------

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<
html>
<
head>
<
title></title>
<
meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<
meta name=ProgId content=VisualStudio.HTML>
<
meta name=Originator content="Microsoft Visual Studio .NET 7.1">
</
head>
<
body onload="PayPalForm.submit();">
<
form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="PayPalForm">
<
input type="hidden" name="cmd" value="_xclick">
<
input type="hidden" name="business" value="rog_21@yahoo.com">
<
input type="hidden" name="item_name" value="Registration">
<
input type="hidden" name="item_number" value="1001">
<
input type="hidden" name="amount" value="1.99">
<
input type="hidden" name="no_shipping" value="1">
<
input type="hidden" name="return" value="http://www.yourhost.com/IPNHandler.aspx?UserID={0}">
<
input type="hidden" name="cancel_return" value="http://www.yourhost.com">
<
input type="hidden" name="no_note" value="1">
<
input type="hidden" name="currency_code" value="USD">
</
form>
</
body>
</
html>

So as you can see if there are no errors that would prevent a successful registration, load up the BuyNow.htm template and the onLoad event of the <body> will submit the form to PayPal and start the process.

In addition to this I am filling in the UserID in the template with the userID that the database generated when I inserted this user. The reason for this is that the "return" parameter in the template will be used once the user has completed the payment and then clicks continue in PayPal. This will send the client to:

http://www.yourhost.com/IPNHandler.aspx?UserID={0} (the {0} is filled in with the userID from the database). You could then update their status from INACTIVE to ACTIVE. I have included the IPNHandler.aspx code as well.
 

IPHandler
-------------------------------------------------------------------------------

public class IPNHandler : System.Web.UI.Page
{
protected UserController userCtrl = new UserController();
private void Page_Load(object sender, System.EventArgs e)
{
int userID = Convert.ToInt32(Request.Params["UserID"]);
string strFormValues = Request.Form.ToString();
string strNewValue;
string strResponse;
// Create the request back
HttpWebRequest req = (HttpWebRequest) WebRequest.Create(https://www.paypal.com/cgi-bin/webscr);
// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
strNewValue = strFormValues + "&cmd=_notify-validate";
req.ContentLength = strNewValue.Length;
// Write the request back IPN strings
StreamWriter stOut = new StreamWriter (req.GetRequestStream(), System.Text.Encoding.ASCII);
stOut.Write(strNewValue);
stOut.Close();
// Do the request to PayPal and get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
// Confirm whether the IPN was VERIFIED or INVALID. If INVALID, just ignore the IPN
if (strResponse == "VERIFIED")
{
string email = Request.Params["receiver_email"].ToString();
string status = Request.Params["payment_status"].ToString();
string txn_id = Request.Params["txn_id"].ToString();
// check that paymentStatus=Completed
// check that txnId has not been previously processed
// check that receiverEmail is your Primary PayPal email
// check that paymentAmount/paymentCurrency are correct
// process payment
if(status.Equals("Completed"))
{
//we have passed here so we can go ahead and insert their
//payment into the db and change their status to A
if(userID != userCtrl.GetPayment(txn_id))
{
try
{
//record the transaction in the db
userCtrl.InsertPayment(userID, txn_id, DateTime.Now);
//change the user's status to ACTIVE
userCtrl.UpdateUserStatus(userID, 'A', DateTime.Now);
}
catch (ApplicationException ex)
{
}
Response.Redirect("Login.aspx");
}
else
Response.Redirect("Default.aspx");
}
}
else if(strResponse == "INVALID")
{
// log for investigation
}
else
{
// error
}
}
}

The reason I filled in the UserID parameter in the template is so when the user completes their payment, paypal will send them back to IPNHandler.aspx?UserID=123 then we can check if the payment transaction completed successfully and then change the status of the user from 'I' (INACTIVE) to 'A' (ACTIVE)


Login to add your contents and source code to this article
 About the author
 
rogersmith
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PayPalSite.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Click Here for 6 Months Free! Powerful ASP.NET Hosting at your Fingertips!
Become a Sponsor
 Comments
Needed - turnkey step-by-step please by Dale On March 2, 2008
Great code... I am a [dare I admit it] NEWBIE -- there I said it. PERL Guru, SQL DBA but in .net Ima newbie. I have been surfing for a simple set of aspx and .cs files that I can upload to GoDaddy to allow me to set an item in a form (a training class) then let the user go to PayPal and pay. This looks close but as a newbie I need SIMPLE. Like modify your web.config like so. copy this code into directory /xxx/ as xxx.cs, copy this file into directory /yyy/ where yyy is the home directory as xxx.htm. Sadly as a newbie I copied verbatum what you have and execute register.aspx and I get the text displayed. I know I need to have something preceding the "public class Register : System.Web.UI.Page { " but a newbie dosen't know what... I will go and learn and perhaps this is not the forum for clueless folk but those are my two cents. Thanks
Reply | Email | Delete | Modify | 
Paypal Payment by Ankit On April 9, 2009
I am a bit confused as i am new to pay pal could you just elaborate and explain me what you have tried to do with the above example. Will this example register a user of my website with the registration of pay pal as well ??? which means once a user registers on my website on the another side he gets registered for Pay pal also. ??
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.