Word of caution, 2017 update

I've wrote this article almost 8 years ago. Be aware that lots of things changed. While integrations described here will still work in most cases, PayPal technology and dev support have been steadily declining during last few years. Most importantly - PayPal customer support right now is worse than it ever was. Basically the issue with PayPal is that your funds can be frozen at any point of time without any solid reason. And when that happens there is no one to talk to. I have personally experienced this on several projects, where well funded, legit startups I advised got their PayPal account frozen.

Few years ago (before 2012) you could at least talk with decision makers and get account unblocked using common sense. Now it seems that most sane people left PayPal and when you get account blocked nobody will take time to openly talk with you. Here are few well documented horror stories where people had large amounts of money blocked for most curious reasons:

Now, I am all for companies protecting themselves. If PayPal is processing credit cards for purchases on your site and suddenly traffic picks up, they are exposed. If people start requesting refunds they need to have option of paying that money back. If you withdrew money from PayPal to bank and won't cooparate - they are vurnerable.

But I have no idea how PayPal operations team makes jump from that to we are completely shutting down your account - DEAL WITH IT. I mean they are basically signing death sentances to businesses. What if company had recurring payments on the account? What if company needs to issue refunds to customers for something? What if you were using PayPal not only for accepting payments but for sending money and paying contractors?

Right now, for every client I am working with I request that they sign waiver if they require me to do PayPal integration. I highly advise you to do the same. And if you have any questions regarding this topic - feel free to leave comment, I'll try to help.

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 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:

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:

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:

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:

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:

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):

Result:

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:

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:

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

Click the Profile subtab

Click the Website Payment Preferences in the Selling Preferences column

Click the On radio button next to the Auto Return label

Enter the URL where you want your users to return in the text box labeled Return URL

Click the Save button at the bottom of the page

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

Click the Profile sub tab

Click Website Payment Preferences in the Selling Preferences column

Click the On radio button next to the Auto Return label

Enter the URL of the script that will process the PDT HTTP request sent from PayPal

Under Payment Data Transfer, click the On radio button

Click Save.

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:

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

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

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.

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:

Click Save, and you should get a message that you have successfully activated IPN

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

PayPal will send an HTTP POST to your IPN handler with a number of variables.

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.

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

Here is a generic C# IPN handler (for more code, check the zip attached to the article):

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

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:

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):

Express Checkout flow

You'll add a PayPal Checkout button that invokes the SetExpressCheckout method of the PayPal API after it is clicked.

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

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.

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.

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.

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.

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.

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.

Oblige that you'll implement both Express Checkout and Direct Payment on your website

Submit application for Website Payments Pro through your PayPal account and have it approved

Pay monthly fee (currently $30 per month)

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.

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.

Firstly thankyou for the code example as it is helping very much. I run the code using the api credentials that come with the code and everything works great.

However after changing it to use the credentials that i setup, it runs through the paypal phase and i get a receipt number and everything looks good. The problem comes when i click on the return to site hyperlink and i get a error on the success page. Here is the parameters of return link. I notice that there is no tx value. Can you help? What is going wrong?

I would like to use the Express Checkout approach. I created default ASP.NET solution and added web service reference pointing to https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl. Could you please tell me how am I supposed to call SetExpressCheckout method? All I see in IntelliSens are just classes with fields. I can't see any methods to call.

HI,
I need to know how to get the details of several variables from Paypal
like: 'payment_status', 'txn_id'..etc after the request is VERIFIED.

// Its given in your code, but commented without details
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
}

If i have to read the .txt file(messages) or 'strResponse' holds all values?

Send me few lines on getting these values so that i may update some database fields once user successfully paid the amount.

Hi Predrag Tomasevic,
Thanks for such a wonderful article. This is the only article on the web i ever found useful to integrate PayPal.
I need your help on processing after payments.
I build a website (ASP.Net/ C# v3.5) where users can register and select payment plan (different names & different cost) & pay via Paypal (using Website Payments Standard).
I need to get the proper response from PayPal (Success/ Failure, Transaction ID) along with InvoiceID(passed to PayPal as 'INVOICE' hidden variable) to do some database updation on successful payments (Membership activation & printable receipt with their membership details).
I have done all settings as given to my PayPal Account(Autoreturn & PDT, IPN).

Please suggest what should be the best & quick way to do so (IPN or PDT).

If i need to use IPN to get all details as given in your sample, tell me how can i get the values of the Variables?
If the strResponse(as in your code) is like querystring having all variables with '&' as seperator means can i get the values as:
string payStatus = Request.Querystring["payment_status"].ToString();
If we can do it via some other method?

Also tell ne how can i get InvoiceID & CompanyID (As passed on HTML Form)?
(if CUSTOM variable contains both)?