Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Introduction to PayPal for C# - ASP.NET developers

0.00/5 (No votes)
3 Feb 2017 6  
An overview that presents all PayPal integration options, targeted especially at C# developers.

Index

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:

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

Signing up for sandbox account

Signing up for a Sandbox account

Filling in details of your 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

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

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 PayPal Sandbox account

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

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:

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

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

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:

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:

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>

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:

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

  1. Log in to your Premier or Business account
  2. Click the Profile subtab
  3. Click the Website Payment Preferences in the Selling Preferences column
  4. Click the On radio button next to the Auto Return label
  5. Enter the URL where you want your users to return in the text box labeled Return URL
  6. Click the Save button at the bottom of the page

Providing AutoRetremoved removed in your PayPal profile

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:

  1. Log in to your Premier or Business account
  2. Click the Profile sub tab
  3. Click Website Payment Preferences in the Selling Preferences column
  4. Click the On radio button next to the Auto Return label
  5. Enter the URL of the script that will process the PDT HTTP request sent from PayPal
  6. Under Payment Data Transfer, click the On radio button
  7. 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

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:

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.
  1. User pays and is redirected to your AutoReturn page, for example: http://www.yourdomain.com/Thanks.aspx?tx=[TransactionID].
  2. 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.)
  3. PayPal will respond to your HTTP POST in the following format:
  4. Do whatever you wish with the data.

Here is how what was said in the previous few lines looks in C# 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
        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 2nd 2009 (2 hour delay) and on September 6th 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:

  1. Log in to your Premier or Business account
  2. Click the Profile sub tab
  3. Click Instant Payment Notification in the Selling Preferences column
  4. Click the 'Edit IPN Settings' button to update your settings
  5. Select 'Receive IPN messages' (Enabled) and enter the URL of your IPN handler
  6. Click Save, and you should get a message that you have successfully activated IPN

Activating Instant Payment Notification

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:

  1. PayPal will send an HTTP POST to your IPN handler with a number of variables.
  2. 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.
  3. 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):

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

  1. Log in to your Premier or Business account
  2. Click the Profile sub tab
  3. Click the API Access link under the Account Information header
  4. Click the link that says Request API Credentials / View API Certificate
  5. Select either API Signature or API Certificate

Step 5 from activating API Access

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

Step 5 from activating API Access

Express Checkout flow
  1. 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).
    2. 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?).
  3. 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.
  4. 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.
  5. 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.
    1. For one time payments, you'll just invoke DoExpressCheckoutPayment and forward the appropriate variables.
    2. 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.

To be able to call methods that are part of Direct Payment (DoDirectPayment and CreateRecurringPayments), you first need to satisfy some conditions:

  1. Have a Business account that is based in US, UK, or Canada
  2. Oblige that you'll implement both Express Checkout and Direct Payment on your website
  3. Submit application for Website Payments Pro through your PayPal account and have it approved
  4. 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.

History

  • November 5th, 2009 - Updated links because of PayPal X restructuring
  • October 1st, 2009 - Initial version of the article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here