home quick answers discussions features community help Searchforarticles,questions,tips

Articles » Web Development » E-commerce » General

Article
Browse Code
Bugs / Suggestions
Stats
Revisions (11)
Alternatives
Comments (164)
View this article's
Workspace
Fork this Workspace
Add your own
alternative version
About Article
Type Article
Licence CPOL
First Posted 7 Oct 2009
Views 483,724
Downloads 26,156
Bookmarked 464 times




, +
Related Articles
SAPrefs - Netscape-like
Preferences Dialog
XNA Snooker Club
Baboon Framework : A
Revolutionary WPF Framework
Predrag Tomasevic, 6 Nov 2009 Rate:
Introduction to PayPal for C# - ASP.NET developers
An overview that presents all PayPal integration options, targeted especially at C# developers.
Is your email address OK? You are signed up for our newsletters but your email address is either
unconfirmed, or has not been reconfirmed in a long time. Please click here to have a confirmation
email sent so we can confirm your email address and start sending you newsletters again. Alternatively,
you can update your subscriptions.
Download source - 166 KB
Index
PayPal Introduction
Getting Started with PayPal
Setting up a Test Account
Website Payments Standard (HTML)
PostPayment processing
AutoReturn
Direct Payment (PDT)
Instant Payment Notification (IPN)
PayPal API
Express Checkout
Direct Payment (Website Payments Pro)
Conclusion
History
Introduction
PayPal is probably one of the first things that gets mentioned once you start discussion on online payments. It’s not
so without reason – in 2008, PayPal moved over 60 billion dollars between accounts which is, you’ll agree, a
respectable amount. And also, all trends show that this growth will continue – with huge number of new accounts
(over 184 million accounts in 2008 compared to 96.2 million in 2005), with a new platform named PayPal X, and with
more cool applications that involve paying (like Twitpay), you can bet that PayPal is here to stay. So, how can you join
the whole PayPal Development movement?
Unfortunately, I would say – not so easily. When I first started with PayPal integration - it was hard, really hard. If you
wish to see what I mean, just jump to the PayPal Developer Center. There is no way you’ll easily fish out what you
need from that site if you are a PayPal newbie; simply - there are too many links, too many resources, and too many
mixings of important and not-so-important information. So, how should you start?
Getting Started with PayPal
To those who really want to get into PayPal, and are willing to shell out some buck, I would recommend the Pro
PayPal E-Commerce book - that’s how I eventually got into understanding the concepts behind PayPal integration.
For those who are not so eager to pay – don’t worry, that’s why this article is here... I'll go over most of the stuff that
4.93 (182 votes)
.NET2.0 C#1.0
C#2.0 .NET3.0
C#3.0 .NET3.5
ASP.NET XML
Architect Dev
× Sign up for our free weekly Web Developer Newsletter.
articles
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
1 of 15 7/12/2014 2:53 AM
that will Save You Time and
Effort
WPF: A* search
DNS.NET Resolver (C#)
Windows 7 / VS2010 demo app
Plotting Circular Relationship
Graphs with Silverlight
Window Tabs (WndTabs)
Add-In for DevStudio
WPF: If Carlsberg did MVVM
Frameworks: Part 3 of n
WPF Localization Using RESX
Files
Multi-line InputBox control -
MC++
Namespace extensions - the
undocumented Windows Shell
WTL for MFC Programmers,
Part IX - GDI Classes, Common
Dialogs, and Utility Classes
Open a command prompt
anywhere.
OLE DB - First steps
Creating alternate GUI using
Vector Art
DSLs: A Deep(ish) look
Remoting Management
Console
Nullsoft Winamp Plug-in With
Bitmapped UI, Docking and
Restrictive Resizing
Introduction to D3DImage
The Complete Idiot's Guide to
Writing Shell Extensions - Part
VI
Related Research
How to Apply Changes to Your
DB2 Database with Minimal Risk
Toad Oracle: Discover the Top
10 Most Useful Toad Features
Data Modeling for Effective
Data Warehousing and Business
Intelligence
book covers, but in a more brief and concise manner.
First and foremost - understanding what kinds of integration PayPal offers is, I would say, the most important thing in
order to successfully start your development journey. A common mistake, that happened to me also, is to start at
once with the PayPal API and Express Checkout. I mean it’s natural - we are developers, and when they tell us to
integrate with something, the first thing we look for is the SDK & API… the PayPal API comes up as a result… we say
“That’s it” to ourselves… and start working. The problem is – the majority of payment scenarios can be handled with a
way simpler approach - HTML forms that are part of the Website Payments Standard.
So, without further ado, here is a classification of PayPal integrations:
Website Payments Standard (HTML)
Postpayment Processing
AutoReturn
Payment Data Transfer (PDT)
Instant Payment Notification (IPN)
PayPal API
Express Checkout
Direct Payment (Website Payments Pro)
Payflow Gateway
Items in classification are also ordered in a way I would suggest for everyone to follow. So, if you are new to PayPal –
first learn all of the options that you have with the Website Payments Standard (HTML). Then, if you need to add
some basic post-payment processing, see if Auto-Return or PDT will solve your problem… if not, IPN is a more robust
option you have at your disposal.
The next level would involve the PayPal API and implementing the Express Checkout, which is the most flexible
PayPal integration solution. And finally, if you long for the ability to directly process credit cards on your website,
you’ll pay a monthly fee to PayPal and implement Direct Payment (effectively getting what is called Website
Payments Pro).
The last item from our classification - the Payflow Gateway is, on the other hand, a different beast. It doesn’t “update
the stack” in a way the previously mentioned technologies do. It is a solution aimed specifically at those businesses
that have/want an Internet Merchant Account (IMA) and just need the payment gateway. In order to keep the article
consistent, I’ll skip explaining the details of the Payflow Gateway. However, if you have any questions related to it, feel
free to leave a message in the comments section and I’ll try to answer.
That said, let’s get to setting up a test PayPal account, and then we’ll delve deeper into describing the mentioned
integrations.
Setting up a Test Account
Word of notice – you’ll want to follow this step even if you already have a live PayPal account. There are two reasons
for using test accounts:
you don’t want to test and play with real money
you want to have access to different types of PayPal accounts
Personal account – most people have these; just an account that allows you to use PayPal when paying
for stuff online. Theoretically, you can use a Personal account to accept money; just know that you’ll be
severely constrained – there is a $500 receiving limit per month, and you are only able to accept one
time payments using the Website Payments Standard (HTML). The big advantage of a Personal account
is that you don’t need to pay any transaction fee when receiving money. Note, however, that if you
receive more than $500 in one month, you’ll be prompted to either upgrade to a Premier/Business
account or reject the payment.
Premier account – step up from a personal account; for anyone who wants to run a personal online
business. This type of account has all of the integration options (accepting credit cards, recurring
payments, PayPal API). However, most people skip directly from Personal to Business account as Premier
account has the same transaction fees (in most cases, 2.9% + $0.30 per transaction) while lacking
reporting, multi-user access, and other advanced merchant services of the Business account.
Business account – it has all of the features of the Premier account plus a few more (ability to operate
under your business’s name is one of them). If you are developing a website that needs to accept
payments in 99% of situations, you’ll go with this type of account.
To start, visit the PayPal Sandbox and sign-up for a new account. The process is straightforward, and most developers
should have no trouble finishing it. However, here are the pictures that will help you navigate through the process:
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
2 of 15 7/12/2014 2:53 AM
How to Do a Big Data Project
Signing up for a Sandbox account
Filling in the details of your Sandbox account
Once done with entering the details for your Sandbox account, you'll need to check the email you provided in order
to complete the registration. After that, you'll be able to login and start creating Sandbox PayPal accounts. Clicking
on Test Accounts (menu on the left), and then Create Account: Preconfigured - will get you a form like the one on
the image below:
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
3 of 15 7/12/2014 2:53 AM
Creating a Sandbox test account
Clarification of Account Type radio buttons: by selecting Buyer, you'll create a Personal account, and by selecting
Seller, you'll create a Business account. For testing most integration scenarios, you'll need both accounts, so be sure
to create them. Here is what you should eventually have on your screen after you click on Test Accounts:
Overview of your testing accounts
Checking the radio button next to any of the accounts from the list and clicking on Enter Sandbox Test Site should
bring up the Sandbox PayPal site which will allow you to login and administer your account in the same way as with a
regular PayPal account. The only difference is that you'll have a huge PayPal Sandbox header and text that displays
the email address of your developer account. To see what I'm talking about, check the image below:
Administering a PayPal Sandbox account
Last but not least - in order to use your Sandbox account for testing, you need to be logged in with your developer
account. If you are not logged in and you follow some payment link, you'll get the following screen:
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
4 of 15 7/12/2014 2:53 AM
Login to use the PayPal Sandbox features
Website Payments Standard (HTML)
In this section, I'll provide you with a number of examples that will show how to create your own HTML form for
receiving money over PayPal. You'll see how to use different variables in order to influence payment details. Before
we delve into details, let's take a look at the two most basic variables:
form's action attribute - in most cases, it should be https://www.paypal.com/cgi-bin/webscr. If you are using
Sandbox for testing payments, you'll change it to https://www.sandbox.paypal.com/cgi-bin/webscr -
effectively, you just insert the word sandbox into the URL (this is also true for some other integrations; e.g., the
PayPal API). For upcoming examples, I won't be using the Sandbox URL because most of you would just get
that "Login to use the PayPal Sandbox features" screen (look up for the image).
form's business child - I'll use youremailaddress@yourdomain.com for most examples; if you copy-paste the
code, you'll want to replace that with the email of your PayPal account.
Basic Payment
OK, let’s say you have an opened PayPal account and you just wish to be able to accept a $10 payment for a painting
you are selling through your site. Just insert the following HTML into your page and you are set to go:
Collapse | Copy Code
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="youremailaddress@yourdomain.com" />
<input type="hidden" name="item_name" value="My painting" />
<input type="hidden" name="amount" value="10.00" />
<input type="submit" value="Buy!" />
</form>
Shipping & Handling
The next thing that comes to mind is that you'll wish to add shipping and/or handling fees to your form. It's easy -
just add more parameters:
Collapse | Copy Code
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="business" value="youremailaddress@yourdomain.com" />
<input type="hidden" name="item_name" value="My painting" />
<input type="hidden" name="amount" value="10.00" />
<input type="hidden" name="shipping" value="3.00" />
<input type="hidden" name="handling" value="2.00" />
<input type="submit" value="Buy with additional parameters!" />
</form>
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
5 of 15 7/12/2014 2:53 AM
Donations & Textual Links
If you aren't selling anything but rather accepting donations for some cause - you'll just need to change the value of
the cmd variable to _donations. If we combine this with a common requirement to have a hyperlink instead of a
button - we get the following URL (of course, you can use this method of URL creation for other PayPal payment
types):
https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=youremailaddress@yourdomain.com&
item_name=Save Polar Bears!&amount=10.00
Result:
Save Polar Bears!
Cart System
If you have a bunch of different products to offer and you just want a simple cart system without implementing
anything, PayPal has you covered. Basically, you'll just play with the cmd variable while keeping the rest of the form
same as for the Basic Payment. Let's see how you should do this for two products; one priced at $10 without shipping
fees, and one priced at $5 with $1 shipping fee. We will also need a View Cart button:
Collapse | Copy Code
My Cart Item 1:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="add" value="1">
<input type="hidden" name="business" value="youremailaddress@yourdomain.com">
<input type="hidden" name="item_name" value="My Cart Item 1">
<input type="hidden" name="amount" value="10.00">
<input type="hidden" name="shopping_url"
value="http://www.yourwebsite.com/shoppingpage.html">
<input type="hidden" name="return" value="http://www.yourwebsite.com/success.html">
<input type="hidden" name="cancel_return" value="http://www.yourwebsite.com/cancel.html">
<input type="hidden" name="bn" value="PP-ShopCartBF:x-click-but22.gif:NonHosted">
<input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but22.gif" border="0"
name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1"
height="1">
</form>
My Cart Item 2:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="add" value="1">
<input type="hidden" name="business" value="youremailaddress@yourdomain.com">
<input type="hidden" name="item_name" value="My Cart Item 2">
<input type="hidden" name="amount" value="5.00">
<input type="hidden" name="shipping" value="1.00">
<input type="hidden" name="shopping_url"
value="http://www.yourwebsite.com/shoppingpage.html">
<input type="hidden" name="return" value="http://www.yourwebsite.com/success.html">
<input type="hidden" name="cancel_return" value="http://www.yourwebsite.com/cancel.html">
<input type="hidden" name="bn" value="PP-ShopCartBF:x-click-but22.gif:NonHosted">
<input type="image" src="https://www.paypal.com/en_US/i/btn/x-click-but22.gif" border="0"
name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1"
height="1">
</form>
View Cart:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="paypal">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="display" value="1">
<input type="hidden" name="business" value="youremailaddress@yourdomain.com">
<input type="hidden" name="shopping_url"
value="http://www.yourwebsite.com/shoppingpage.html">
<input type="image" src="https://www.paypal.com/en_US/i/btn/view_cart_02.gif"
name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
</form>
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
6 of 15 7/12/2014 2:53 AM
Recurring Payments
If you are selling a monthly service rather than a product, you'll be interested in the recurring payment options PayPal
provides. Again, it's playing with different variables that have different meaning. Let's say you wish to set a 3 day free
trial after which the user will have to pay you $10.00 per month to keep using the service. The following HTML form
should do the trick:
Collapse | Copy Code
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick-subscriptions"/>
<input type="hidden" name="business" value="youremailaddress@yourdomain.com"/>
<input type="hidden" name="item_name" value="Something"/>
<input type="submit" value="Subscribe!" />
<input type="hidden" name="a1" value="0"/>
<input type="hidden" name="p1" value="3"/>
<input type="hidden" name="t1" value="D"/>
<input type="hidden" name="a3" value="10.00"/>
<input type="hidden" name="p3" value="1"/>
<input type="hidden" name="t3" value="M"/>
<input type="hidden" name="src" value="1"/>
<input type="hidden" name="srt" value="0"/>
<input type="hidden" name="sra" value="1"/>
</form>
HTML Variables & Resources
After reading the previous example, you may be wondering what certain variables do (a1? p1? srt?). Luckily, PayPal
provides an "HTML Variables for Website Payments Standard" page on which you can read about any variable that
you are interested in.
Also, another great resource (to which I wish someone pointed me when I first started with PP integration) is "skier's
PayPal examples". You'll find examples for almost all payment scenarios you can think of - so instead of cluttering
this article with more examples, I'll encourage you to visit that page should you wish to implement some more
advanced PayPal HTML form.
PostPayment Processing
When you setup your PayPal HTML form, the first question you'll probably ask is - after user pays, can I have some
post-payment processing logic? It is not so without reason; there are numerous post-payment scenarios we can think
of - from sending a simple "Thank you" email to updating the site database and allowing user access to restricted
resources for which he paid. Depending on your knowledge and the desired level of robustness for post-processing
logic, there are three ways you can go; and the good thing is you can combine them.
AutoReturn
AutoReturn is the simplest PostPayment processing solution that you have - after the user pays, he is automatically*
redirected to a specified page on your website on which you can display some confirmation text. If you carefully went
through "HTML Variables for Website Payments Standard", you know that you can use a return variable to specify the
AutoReturn URL in the HTML form. If you wish to have the default AutoReturn URL, follow these steps:
Log in to your Premier or Business account 1.
Click the Profile subtab 2.
Click the Website Payment Preferences in the Selling Preferences column 3.
Click the On radio button next to the Auto Return label 4.
Enter the URL where you want your users to return in the text box labeled Return URL 5.
Click the Save button at the bottom of the page 6.
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
7 of 15 7/12/2014 2:53 AM
Providing the AutoReturl URL in your PayPal profile
Know that if you have both AutoReturn URL in your profile and provide a return variable in your HTML form, the
return variable will overwrite the profile URL value.
Now, when your return page is hit, you'll be getting variables that should allow you to customize the page display and
log payment:
tx - Transaction ID
st - Payment status
amt - Payment amount
cc - Currency code
Before closing this section, one more thing. The reason why I've italicized the word "automatically" in the first
sentence is: if the user uses a credit card to pay you, he won't be automatically redirected to your return URL; he'll
rather need to click on the "Return to Merchant" button. If this sounds weird to you, know that you're not alone;
however, because of legal issues, PayPal refused and still refuses to change the way credit card payments are handled
with AutoReturn.
Payment Data Transfer (PDT)
After looking over the list of variables that AutoReturn provides, you probably wondered - can I get more details
about the transaction that occurred? This is exactly where PDT jumps in - building on the AutoReturn functionality.
For that reason, you'll need to enable both AutoReturn and then PDT in your profile; here is how to do that:
Log in to your Premier or Business account 1.
Click the Profile sub tab 2.
Click Website Payment Preferences in the Selling Preferences column 3.
Click the On radio button next to the Auto Return label 4.
Enter the URL of the script that will process the PDT HTTP request sent from PayPal 5.
Under Payment Data Transfer, click the On radio button 6.
Click Save. 7.
After following these steps, you should get a PDT Identity Token that is needed for querying PayPal. If you don't
copy-paste the token after clicking Save, know that you can always see it in your Website Payment Preferences:
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
8 of 15 7/12/2014 2:53 AM
Payment Data Transfer and Identity Token
Now that you have the Identity Token, you can query PayPal for more details after your return URL has been hit. Here
is how things flow when utilizing PDT:
User pays and is redirected to your AutoReturn page, for example: http://www.yourdomain.com
/Thanks.aspx?tx=[TransactionID].
1.
From the code-behind of Thanks.aspx, you'll parse the tx value and make an HTTP POST to
https://www.paypal.com/cgi-bin/webscr with the following parameters: cmd=_notify-synch&tx=[TransactionID]&
at=[PDTIdentityToken]. (If you are using Sandbox, you'll of course make an HTTP POST to
https://www.sandbox.paypal.com/cgi-bin/webscr.)
2.
PayPal will respond to your HTTP POST in the following format: 3.
Collapse | Copy Code
SUCCESS
first_name=Firstname
last_name=Lastname
payment_status=Completed
payer_email=firstname%40lastname.com
payment_gross=50.00
mc_currency=USD
custom=Custom+value+you+passed+with+your+HTML+form
etc.
Do whatever you wish with the data. 4.
Here is how what was said in the previous few lines looks in C# code:
Collapse | Copy Code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
authToken = WebConfigurationManager.AppSettings["PDTToken"];
//read in txn token from querystring
txToken = Request.QueryString.Get("tx");
query = string.Format("cmd=_notify-synch&tx={0}&at={1}",
txToken, authToken);
// Create the request back
string url = WebConfigurationManager.AppSettings["PayPalSubmitUrl"];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = query.Length;
// Write the request back IPN strings
StreamWriter stOut = new StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
stOut.Write(query);
stOut.Close();
// Do the request to PayPal and get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
// sanity check
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
9 of 15 7/12/2014 2:53 AM
Label2.Text = strResponse;
// If response was SUCCESS, parse response string and output details
if (strResponse.StartsWith("SUCCESS"))
{
PDTHolder pdt = PDTHolder.Parse(strResponse);
Label1.Text =
string.Format("Thank you {0} {1} [{2}] for your payment of {3} {4}!",
pdt.PayerFirstName, pdt.PayerLastName,
pdt.PayerEmail, pdt.GrossTotal, pdt.Currency);
}
else
{
Label1.Text = "Oooops, something went wrong...";
}
}
}
In the code I'm attaching with the article, under the PDT directory, you'll see more classes that will help you out in
following the previously mentioned flow.
And, as with AutoReturn, one notice before closing the subject - take a look at the custom variable in PayPal's
response to your HTTP POST. You'll probably want to utilize this variable as it allows you to pass some information
from your payment page to your post-processing page without presenting it to the user. To name one use, in some of
my PayPal implementations, I track the user with it - when he started payment process, and when/if he finished it.
Instant Payment Notification (IPN)
One big shortcoming of PDT is that it is a user-driven process, meaning - if the user closes the browser after
performing a payment and before being redirected to your site, you'll lose the opportunity to run your post
processing logic. That's why you are advised to combine the PDT with IPN for any serious integration with PayPal.
IPN is a back-end mechanism that makes HTTP POSTs to your page, notifying you of important events. It is used not
only for PostPayment processing, but also for things that come after, like handling user cancelation of recurring
payments.
Being a back-end technology, it is somewhat harder to implement and debug than PDT. There are a couple of things
you should be aware of before starting to implement IPN:
IPN messages can be delayed sometimes. I know, I know... that beats the word "Instant" in IPN, but that's how
things are.
There is a known history of problems with the IPN service; two latest incidents happened on October 2
nd
2009
(2 hour delay) and on September 6
th
2009 (6 hour delay).
Whenever you have problems with IPN, be sure to check the Live Status page and see if there is an incident
notification before digging into debugging and changing your script. There is also a similar page for Sandbox
Status.
Before being able to receive IPN messages, you'll need to activate this service; follow these steps:
Log in to your Premier or Business account 1.
Click the Profile sub tab 2.
Click Instant Payment Notification in the Selling Preferences column 3.
Click the 'Edit IPN Settings' button to update your settings 4.
Select 'Receive IPN messages' (Enabled) and enter the URL of your IPN handler 5.
Click Save, and you should get a message that you have successfully activated IPN 6.
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
10 of 15 7/12/2014 2:53 AM
Activating Instant Payment Notification
As with AutoReturn, you can overwrite the IPN handler URL set in the profile in individual forms by adding the
notify_url variable (see the HTML Variables reference). Know that this will influence not only the initial IPN
message but all future messages related to that transaction (they will all go to notify_url).
To handle IPN messages, you'll need to create an HTTP handler somewhere on your website. When a significant
event occurs (e.g., user performs payment), following flow takes place:
PayPal will send an HTTP POST to your IPN handler with a number of variables. 1.
After receiving HTTP POST and parsing it, you need to submit the complete body of the message back to
https://www.paypal.com/cgi-bin/webscr (or https://www.sandbox.paypal.com/cgi-bin/webscr for a Sandbox
account). When you are doing this, be sure to send a message back in the exact format in which you received
it; the only thing you are allowed to do is adding cmd=_notify-validate. This is all done in order to verify that
HTTP POST was authentic and sent from PayPal.
2.
PayPal will respond with either VERIFIED or INVALID. After you receive this response, be sure to send 200 OK to
prevent additional attempts from PayPal to send an IPN. If you don't close the loop with a 200 OK, PayPal will
start resending IPN (starting from 4 seconds and doubling - 8 seconds, 16 seconds, 32 seconds... up to 4 days).
3.
Here is a generic C# IPN handler (for more code, check the zip attached to the article):
Collapse | Copy Code
protected void Page_Load(object sender, EventArgs e)
{
string postUrl = ConfigurationManager.AppSettings["PayPalSubmitUrl"];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postUrl);
//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 ipnPost = strRequest;
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();
// logging ipn messages... be sure that you give write
// permission to process executing this code
string logPathDir = ResolveUrl("Messages");
string logPath = string.Format("{0}\{1}.txt",
Server.MapPath(logPathDir), DateTime.Now.Ticks);
File.WriteAllText(logPath, ipnPost);
//
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
}
else if (strResponse == "INVALID")
{
//log for manual investigation
}
else
{
//log response/ipn data for manual investigation
}
}
If you have received an INVALID response, that could mean two things:
Someone tried to send a malicious message to your IPN handler.
Your implementation isn't perfect.
In case of a malicious message, you're on your own (log IP, take appropriate action), but for imperfect
implementations, visit this IPN troubleshooting topic on PayPal Developer Forums; it is full of useful tips that should
help you solve INVALID responses.
Also, before going online with your IPN handler, be sure to test it thoroughly with the Instant Payment Notification
(IPN) simulator. As an IPN handler will work in the background, you'll want to test it as much as you can before going
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
11 of 15 7/12/2014 2:53 AM
live and relying on its processing.
Another thing you'll want to visit if you are implementing IPN is ScriptGenerator2 page... it can quickly generate an
IPN handler in the language of your choice. Funny thing - they are missing a generator for ASP.NET/C#; for that,
check out the IPN directory in the code-archive I've attached to this article and these Code Samples.
Finally, on PayPal Developer Center, there is this nice page that lists most of the IPN and PDT variables. I'm saying
most because there are some variables missing on it (check comments on this page), but the list is far beyond being
useless.
PayPal API
As said in the introduction, most developers, even if they have no previous experience with PayPal, start directly with
the API. Google search brings up either API Reference or the SDKs and Downloads page and then browsing through
Documentation starts. I don't want to say that there is something wrong with using PayPal API for payments; I want
to say that in most of the cases, it's not necessary to go down that path.
PayPal API is much more than just a mechanism for payment - if you look at the provided API Reference page, you'll
see that there are lots of methods not tied directly to "user performing payment". You can use the API to browse
through the history of your transactions, issue a refund, or update a recurring payments profile. So how do you start
using it?
First and foremost, you'll need to enable API access in your account; follow these steps:
Log in to your Premier or Business account 1.
Click the Profile sub tab 2.
Click the API Access link under the Account Information header 3.
Click the link that says Request API Credentials / View API Certificate 4.
Select either API Signature or API Certificate 5.
Step 5 from activating API Access
I recommend that you select API Signature, and the examples that follow will assume you made this choice. There is
nothing wrong with selecting API Certificate; I just find it more demanding from a setup perspective.
Now that you have credentials to make API calls, how do you perform them? The approach that will work equally well
with all platforms is to download the SDK, target the appropriate API endpoint, and start making HTTP calls with
either Name-Value pairs or SOAP.
However, for .NET developers, I recommend a different approach. Considering that Visual Studio has an awesome
WSDL parser, I urge you to just add a Web Service Reference to https://www.paypal.com/wsdl/PayPalSvc.wsdl. After a
few moments, you'll have an up-to-date class ready to serve you with all the benefits of strong typing - no building of
HTTP requests, no copy-pasting field names, and no cumbersome parsing of responses. You have the same thing
available for Sandbox at: https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl.
Express Checkout
Express Checkout is the most flexible PayPal integration solution. The user is redirected to PayPal just for
authentication and confirmation that he wants to pay for your services, and after that, everything is done on your
website; you'll make calls to the PayPal API in the background. The following picture describes the process (taken
from this page):
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
12 of 15 7/12/2014 2:53 AM
Express Checkout flow
You'll add a PayPal Checkout button that invokes the SetExpressCheckout method of the PayPal API after it
is clicked.
1.
If you are invoking this method for one time payment, it'll be valid if you include only the required fields.
Setting the NOSHIPPING variable to 1 is important if you are selling some online service (it'll help you
skip the Shipping info page).
1.
If you are invoking this method in order to set recurring payments, be sure to set L_BILLINGTYPE0 to
RecurringPayments and L_BILLINGAGREEMENTDESCRIPTION0 to a valid description of your service.
2.
SetExpressCheckout will return a 20 char token that will uniquely identify your transaction. This token is
valid for 3 hours. After you receive it, redirect the user to https://www.paypal.com/cgi-bin
/webscr?cmd=_express-checkout&token=[TOKEN] (you can guess what the URL for Sandbox is, right?).
2.
The user will review payment information, and if everything is OK, enter the login credentials. After this, PayPal
will redirect him to the URL you specified with RETURNURL when you called SetExpressCheckout.
3.
When your RETURNURL is hit, you need to invoke the GetExpressCheckoutDetails method and see the
details of the actual transaction; verify that everything is in order.
4.
Now, all that is left is to commit the transaction. Depending on what you did in step 1, there are two things
that can be done.
5.
For one time payments, you'll just invoke DoExpressCheckoutPayment and forward the appropriate
variables.
1.
For recurring payments, you'll invoke the CreateRecurringPayments method. It is required that you
include the DESC field and match it to the value entered in L_BILLINGAGREEMENTDESCRIPTION0 when
you called SetExpressCheckout.
2.
In a nutshell - that's it. Again, I have provided code examples that follow the previously specified flow in the archive
accompanying this article (under the API directory). If you wish, you can also use the PayPal Express Checkout
Integration Wizard for generating the reference code.
Direct Payment (Website Payments Pro)
Most developers aren't aware that the PayPal platform can be used for just Credit Card processing. This part of the
PayPal API is called Direct Payment, and when combined with Express Checkout (which only services customers with
PayPal accounts), you get what is referred to as Website Payments Pro on the PayPal Developer Center.
To be able to call methods that are part of Direct Payment (DoDirectPayment and CreateRecurringPayments),
you first need to satisfy some conditions:
Have a Business account that is based in US, UK, or Canada 1.
Oblige that you'll implement both Express Checkout and Direct Payment on your website 2.
Submit application for Website Payments Pro through your PayPal account and have it approved 3.
Pay monthly fee (currently $30 per month) 4.
After you have a Website Payments Pro account in place, calling Direct Payment methods is pretty straightforward - if
in doubt, either visit the API Reference page, or look at the code attached to this article. Just know that if you try to
call any Direct Payment method on an account that doesn't have Pro enabled, you'll get an error with code 10501
(this is one of the most common problems reported in the Sandbox forum).
Lastly, once you start dealing with credit cards, you'll need to take care of PCI Compliance; here is a nice forum thread
that provides more information on that.
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
13 of 15 7/12/2014 2:53 AM
Predrag Tomasevic
Chief Technology Officer Atama
Group
United States
http://www.linkedin.com/in/ptomasevic

Bitcoin wallet: 1ARXmh58S6aRiZPCbneDCzrB1HUU6PLmDQ

Add a Comment or Question

Search this forum Go
Conclusion
My hope is that this article gave you good overview of PayPal integration options. If it did that, I'll be at peace - as
once you have an understanding of the concepts laid out in this article, you'll easily fetch the needed details from the
provided links. Sure, there are some topics we haven't touched, like Encrypted Website Payments, PayPal API
Certificates, or Payflow Gateway, but I think you can tackle even that on your own once you fully understand all
things written here.
If you get stuck on anything, I suggest that you first visit the PayPal Developer Community and ask your question in
the appropriate forum. A number of great, knowledable developers monitor those forums, and it's highly probable
that you'll receive an answer to almost any PayPal issue within an hour. I also have an account on that site (lepipele)
and try to answer questions whenever I have time; so feel free to send me a private message if you drop by or run
into trouble.
History
November 5
th
, 2009 - Updated links because of PayPal X restructuring
October 1
st
, 2009 - Initial version of the article.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
About the Author
Article Top
Comments and Discussions
Profile popups Spacing Relaxed Noise Medium Layout Normal Per page 25 Update
First Prev Next
Member 10663514
12-Mar-14 4:12
SergioAmorim
18-Feb-14 6:03
code is not working
Skier's Paypal samples
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
14 of 15 7/12/2014 2:53 AM
Permalink | Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 6 Nov 2009
Article Copyright 2009 by Predrag Tomasevic
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid
Member 10275938
7-Feb-14 9:29
vk0489
20-Jan-14 11:47
praveenpk
15-Jan-14 0:19
Member 10491581
28-Dec-13 4:30
Member 10399961
13-Nov-13 15:02
LcSila13
21-Oct-13 10:16
Sampath Lokuge
27-Jul-13 5:15
Member 10164600
20-Jul-13 5:37
Rohan Leuva
18-Apr-13 5:52
Kashif.Scholion
21-Jan-13 16:58
Punit Belani
21-Jan-13 3:49
Punit Belani
21-Jan-13 3:48
Punit Belani
21-Jan-13 3:47
Pankaj_Upadhyay
23-Nov-12 6:44
Member 9566577
21-Nov-12 6:52
Member 8351252
11-Nov-12 1:29
B.Sudhir
9-Oct-12 0:28
Member 9171128
28-Sep-12 20:18
Raghu KT
15-Sep-12 5:52
Raghu KT
15-Sep-12 5:38
@amitgajjar
15-Sep-12 3:48
Member 1078262
8-Aug-12 7:25
juanjosei
20-Nov-12 10:25
Last Visit: 31-Dec-99 23:00 Last Update: 11-Jul-14 11:31 Refresh 1 2 3 4 5 6 7 Next »
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
IPN vs PDT which is before
Error when using the INE Handler and PayPal API & Express
Checkout
PayPal for C# - ASP.NET developers currency Code
implementation
Very helpful Article
Downloading history from code
Excelent article!
My vote of 5
Please update AutoReturn parameters as they have changed
My vote of 5
My Gratitude to your Wonderful Post which Helps me a lot.
Thanks
My vote of 5
Subsciption EOT error
Nice Work.....
My vote of 5!
There is complete PayPal API C# .Net Wrapper
IPN Doesn't work at all
PAYPAL integrate in ASP.NET webpages
My vote of 5
My vote of 5
My vote of 5
.net soap api work for sandbox but don't work for regular
account
Re: .net soap api work for sandbox but don't work for regular
account
Introduction to PayPal for C# - ASP.NET developers - CodeProject http://www.codeproject.com/Articles/42894/Introduction-to-PayPal-for-...
15 of 15 7/12/2014 2:53 AM