Pages

Monday 9 December 2013

Paypal Integration with Asp.Net

How to Integrate Paypal with Asp.Net


In this article I will explain thoroughly all the requirements and techniques for integrating PayPal in your web application.
Nowadays PayPal is the most popular payment gateway worldwide because it is totally free to integrate and PayPal does not charge anything for opening an account, you will pay PayPal when you get paid. And the amount is also lower than other payment gateways. 

First of all you need to Create a paypal account. After creating an account, you need to open Paypal Developer and need to create 2 sandbox test account. One is for merchant and another is for buyer (1 merchant account will be provided to you by default).

Website Payment Standard (HTML)


In this section, I'll provide you a basic 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>

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 standards page on which you can read about any variable that you are interested in.

Post Payment 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 isautomatically* 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 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

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:

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:
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 tohttps://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 (query string parameters):
1.       SUCCESS
1.       first_name=Firstname
2.     last_name=Lastname
3.     payment_status=Completed
4.     payer_email=firstname%40lastname.com
5.     payment_gross=50.00
6.     mc_currency=USD
7.     custom=Custom+value+you+passed+with+your+HTML+form etc.
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...";
        }
    }
}

By,
Akash Roy,
CEO, JPR Infoserve,
http://jprinfoserve.com

No comments:

Post a Comment