PayPal


PayPal Integration with ASP .NET


In this article I will explain how to integrate your website developed in ASP .Net to PayPal. There are two ways of achieving this purpose. One you can redirect user to PayPal website where he/she makes the payment and then returns to your website. Second is user pays on your website and PayPal receives the payment through backend processing without user leaving your website. Both these methods are explained below:

Introduction
PayPal is probably one of the first things that get 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.
Setting up a Test Account
Since you do not want to test and play with real money, you will need to create a test account. You can create a test account from PayPal Developer Website


Signing up for 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:



Receive Payment on PayPal

Website


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

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


Post Payment Processing
AutoReturn
AutoReturn is the simplest Post Payment 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 sub tab
  • 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


Also insert these lines in your web.config file
<appSettings>
            <add key="contentPath" value="C:\Inetpub\wwwroot\PaypalCSharp\data!fldr\"/>
            <add key="websiteUrl" value="http://localhost/Guest"/>
            <add key="paypalAccount" value="tousee@keystone-services.com"/>
            <add key="taxRate" value="7.25"/>
            <add key="com.paypalobjects.www.PayPalSvc" value="https://api.sandbox.paypal.com/2.0/"/>
      </appSettings>

Here websiteUrl denotes your website where paypal is going to return.



Receive Payment from your own

Website


Drop four dropdownlist controls on your page, 8 textbox controls, three labels controls and one button control.
Name the textboxes ccNumberTextBox, CVVcodeTextBox, amountTextBox, firstnameTextBox, lastnameTextBox, addressTextBox, cityTextBox, regionTextBox, postalTextBox and labels errcodeLabel, successLabel, errLabel.


You code should look something like this:

<form id="form1" runat="server" >
        <asp:DropDownList ID="cctypeDdl" runat="server">
            <asp:ListItem>VISA</asp:ListItem>
            <asp:ListItem Value="MasterCard">Master Card</asp:ListItem>
            <asp:ListItem>Discover</asp:ListItem>
            <asp:ListItem Selected="True" Value="AMEX">AmericanExpress</asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="expdateDropDown" runat="server">
            <asp:ListItem Selected="True">08</asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="yeardropdown" runat="server">
            <asp:ListItem>2011</asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList ID="countryDropDown" runat="server">
            <asp:ListItem Selected="True">United States</asp:ListItem>
        </asp:DropDownList>
        <asp:TextBox ID="ccNumberTextBox" runat="server"></asp:TextBox>
        <asp:TextBox ID="CVVcodeTextBox" runat="server"></asp:TextBox>
        <asp:TextBox ID="amountTextBox" runat="server"></asp:TextBox>
        <asp:TextBox ID="firstnameTextBox" runat="server"></asp:TextBox>
        <asp:TextBox ID="lastnameTextBox" runat="server"></asp:TextBox>
        <asp:TextBox ID="addressTextBox" runat="server"></asp:TextBox>
        <asp:TextBox ID="cityTextBox" runat="server"></asp:TextBox>
        <asp:TextBox ID="regionTextBox" runat="server"></asp:TextBox>
        <asp:TextBox ID="postalTextBox" runat="server"></asp:TextBox>
        <asp:Label ID="errcodeLabel" runat="server" style="z-index: 100; left: 198px; position: absolute; top: 346px"></asp:Label>
        <asp:Label ID="successLabel" runat="server" style="z-index: 103; left: 361px; position: absolute; top: 266px"></asp:Label>
        <asp:Label ID="errLabel" runat="server" style="z-index: 102; left: 477px; position: absolute; top: 347px"></asp:Label>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </form>



In the Click Event of the button in .cs file, write the following code

Replace these API Credentials with your own information.
//API Credentials (3-token)
        string strUsername = "Your UserName";
        string strPassword = "Your Password";
        string strSignature = "Your Signaure";
//Give your user name and other required information as Paypal will mind if i give my own username and password
        string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature;

        string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";
        string strAPIVersion = "2.3";

        string strNVP = strCredentials + "&METHOD=DoDirectPayment" +
        "&CREDITCARDTYPE=" + cctypeDdl.Text +
        "&ACCT=" + ccNumberTextBox.Text +
        "&EXPDATE=" + expdateDropDown.Text + yeardropdown.Text +
        "&CVV2=" + CVVcodeTextBox.Text +
        "&AMT=" + amountTextBox.Text +
        "&FIRSTNAME=" + firstnameTextBox.Text +
        "&LASTNAME=" + lastnameTextBox.Text +
        //"&EMAIL= touseef@keystone-services.com" +
        //"&IPADDRESS= 66.135.205.14" +
        "&STREET=" + addressTextBox.Text +
        "&CITY=" + cityTextBox.Text +
        "&STATE=" + regionTextBox.Text +
        "&COUNTRY=" + countryDropDown.Text +
        "&ZIP=85225" + postalTextBox.Text +
        "&COUNTRYCODE=US" +
        "&PAYMENTACTION=Sale" +
        "&VERSION=" + strAPIVersion;

        try
        {
            //Create web request and web response objects, make sure you using the correct server (sandbox/live)
            HttpWebRequest wrWebRequest = (HttpWebRequest)WebRequest.Create(strNVPSandboxServer);
            wrWebRequest.Method = "POST";
            StreamWriter requestWriter = new StreamWriter(wrWebRequest.GetRequestStream());
            requestWriter.Write(strNVP);
            requestWriter.Close();

            // Get the response.
            HttpWebResponse hwrWebResponse = (HttpWebResponse)wrWebRequest.GetResponse();
            StreamReader responseReader = new StreamReader(wrWebRequest.GetResponse().GetResponseStream());

            //and read the response
            string responseData = responseReader.ReadToEnd();
            responseReader.Close();

            string result = Server.UrlDecode(responseData);

            string[] arrResult = result.Split('&');
            Hashtable htResponse = new Hashtable();
            string[] responseItemArray;
            foreach (string responseItem in arrResult)
            {
                responseItemArray = responseItem.Split('=');
                htResponse.Add(responseItemArray[0], responseItemArray[1]);
            }

            string strAck = htResponse["ACK"].ToString();

            if (strAck == "Success" || strAck == "SuccessWithWarning")
            {
                string strAmt = htResponse["AMT"].ToString();
                string strCcy = htResponse["CURRENCYCODE"].ToString();
                string strTransactionID = htResponse["TRANSACTIONID"].ToString();
                //ordersDataSource.InsertParameters["TransactionID"].DefaultValue = strTransactionID;

                string strSuccess = "Thank you, your order for: $" + strAmt + " " + strCcy + " has been processed.";
                successLabel.Text = strSuccess;
            }
            else
            {
                string strErr = "Error: " + htResponse["L_LONGMESSAGE0"].ToString();
                string strErrcode = "Error code: " + htResponse["L_ERRORCODE0"].ToString();
                errLabel.Text = strErr;
                errcodeLabel.Text = strErrcode;
                return;
            }
        }
        catch (Exception ex)
        {
            // do something to catch the error, like write to a log file.
            Response.Write("error processing");
        }


Note:

In all above cases for the live website, replace sandbox.paypal.com with paypal.com.