How to integrate PayPal in ASP.NET using cart option ?

In this article I am going to explain about how to integrate PayPal in ASP.NET with cart option. Most of shopping cart website are using this paypal cart option technique to add more product details to collect total cash from user.

Description :

In my previous Paypal Integration in ASP.NET article I was explained in detailed about paypal integration with buy now option. In that article I have passed all item details thorugh query string. But not able to send more than one item in that concept.

But here in this article I have explained in details about buy more than one item in shopping cart. Here I have used Paypal Add to Cart Option. After user select item show in confirmation page then finally pass that values to paypal using hidden field instead of query string (my previous article)

Store order details after user select produce in to the website

create table purchase(pname nvarchar(50),pdesc nvarchar(50),price nvarchar(50),uname nvarchar(50))

Create PayPal Account in SandBox to testing

Go to and create Paypal account to be testing

After create new account Login into the website. Now click on the Test accounts Right side and create two sub accounts

1) Buyer account
2) Seller account


After Click Preconfigured create account for buyer and seller like below

After enter all details click Create account button. Now those two accounts are displayed in your test accounts like Business, Personal

That's fine now open visual studio and write coding to display product details and provide option to user buy our product through paypal.

Client side

In client side I have displayed some product in grid view if user click that product buy button then redirect to PayPal sandox site

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
<title>Paypal Integartion</title>
<form id="form1" runat="server">
<table width="700" align="center" cellpadding="0" cellspacing="0">
<td height="60">
<b>Paypal Integration in ASP.NET</b>
<td height="40" align="center">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
<RowStyle ForeColor="#000066" />
<%-- <asp:TemplateField HeaderText="Product image">
<asp:Image ID="Image1" runat="server" Width="80" Height="60" ImageUrl='<%#Eval("path")%>' />
<asp:TemplateField HeaderText="Product Name">
<asp:Label ID="Label1" runat="server" Text='<%#Eval("pname") %>'></asp:Label>
<asp:TemplateField HeaderText="Product Description">
<asp:Label ID="Label2" runat="server" Text='<%#Eval("pdesc") %>'></asp:Label>
<asp:TemplateField HeaderText="Product price">
<asp:Label ID="Label3" runat="server" Text='<%#Eval("price") %>'></asp:Label>
<asp:TemplateField HeaderText="Buy Now">
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/buyNow.png"
Width="80" Height="40" CommandName="buy" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
<FooterStyle BackColor="White" ForeColor="#000066" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<!-- PayPal Logo -->
<table border="0" cellpadding="10" cellspacing="0" align="center">
<td align="center">
<td align="center">
<a href="#" onclick="'','olcwhatispaypal','toolbar=no,
location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=400, height=350');">
<img src="" border="0"
alt="Solution Graphics"></a>
<!-- PayPal Logo -->

Server side

In server side I collect which product user selected and send price, tax details to Paypal

using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataRow dr;

protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
//Add some column to datatable display some products

//Add rows with datatable and bind in the grid view
dr = dt.NewRow();
dr["pname"] = "Laptop";
dr["pdesc"] = "Professional laptop";
dr["price"] = "$100";

dr = dt.NewRow();
dr["pname"] = "Laptop";
dr["pdesc"] = "Personal Laptop";
dr["price"] = "$120";

dr = dt.NewRow();
dr["pname"] = "CPU";
dr["pdesc"] = "Comptuter accessories";
dr["price"] = "$40";

dr = dt.NewRow();
dr["pname"] = "Desktop";
dr["pdesc"] = "Home PC";
dr["price"] = "$150";

GridView1.DataSource = dt;

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
if (e.CommandName == "buy")
ImageButton ib = (ImageButton)e.CommandSource;
int index = Convert.ToInt32(ib.CommandArgument);
GridViewRow row = GridView1.Rows[index];

//Get each Column label value from grid view and store it in label
Label l1 = (Label)row.FindControl("Label1");
Label l2 = (Label)row.FindControl("Label2");
Label l3 = (Label)row.FindControl("Label3");

//After user clik buy now button store that details into the sql server "purchase" table for reference
string query = "";
query = "insert into purchase(pname,pdesc,price,uname) values('" + l1.Text + "','" + l2.Text + "','" + l3.Text.Replace("$","") + "','" + Session["user"].ToString() + "')";
sqlcmd = new SqlCommand(query, sqlcon);

//Temporarly i store some value you can store in login user address name city in the below variables
string username = "Ravindran";
string city="Trichy";
string state = "Tamilnadu";

//Store these selected value in the session temporarly
Session["user"] = username;
Session["city"] = city;
Session["state"] = state;
Session["itname"] = l1.Text;
Session["amount"] = l3.Text;

//Now redirct to confirmation page


In this page I have show selected product details for confirmation and store selected details in hidden file then if user click submit, submit payment info to paypal using form action tag

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Processing.aspx.cs" Inherits="Processing" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
<title>Pay Pal Checkout Confirmation</title>
<form id="Paypal" name="Paypal" action=""
<input type="hidden" name="cmd" value="_cart" />
<input type="hidden" name="upload" value="1" />
<input type="hidden" name="business" value="<%=System.Web.Configuration.WebConfigurationManager.AppSettings["paypalemail"] %>" />
<input type="hidden" name="item_name_1" value="<%=Session["itname"].ToString() %>" />
<input type="hidden" name="quantity_1" value="1" />
<input type="hidden" name="amount_1" value="<%=Session["amount"].ToString() %>" />
<input type="hidden" name="shipping_1" value="5" />
<input type="hidden" name="handling_1" value="5" />
<input type="hidden" name="tax_1" value="5" />
<input type="hidden" name="currency_code" value="USD" />
<input type="hidden" name="return" value="<%=System.Web.Configuration.WebConfigurationManager.AppSettings["SuccessURL"] %>" />
<input type="hidden" name="cancel_return" value="<%=System.Web.Configuration.WebConfigurationManager.AppSettings["FailedURL"] %>" />
<input type="hidden" name="lc" value="test lc country" />
<input type="submit" value="Submit" />



On page load first time to show selected item details in the webpage

public partial class Processing : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
if (!Page.IsPostBack)
Response.Write("<table width='600' border='1'>");
Response.Write("<tr><td height='30' colspan='2'><h2>Confirmation!!! please check your product details</h2></td>");
Response.Write("<tr><td height='30'>User name</td><td>" + Session["user"].ToString() + "</td>");
Response.Write("<tr><td height='30'>City</td><td>" + Session["city"].ToString() + "</td>");
Response.Write("<tr><td height='30'>State</td><td>" + Session["state"].ToString() + "</td>");
Response.Write("<tr><td height='30'>Item Name</td><td>" + Session["itname"].ToString() + "</td>");
Response.Write("<tr><td height='30'>Item Amount</td><td>"+Session["amount"]+"</td>");
Response.Write("<tr><td height='30'>Shipping</td><td>5</td>"); //here i apply shipping charge as 5
Response.Write("<tr><td height='30'>Handling</td><td>5</td>"); //here i apply handling charge as 5
Response.Write("<tr><td height='30'>Tax</td><td>5</td>"); //here i apply tax charge as 5
Response.Write("<tr><td height='30'>Quantity</td><td>1</td>");
//above line i apply quantity default 1 if you want provide textbox value for more quantity and update in front end design hidden field
Response.Write("<tr><td height='30'>Currency</td><td>USD</td>"); //currency is default 5

In web.config file I have set Return Url and PayPal business id etc. like below

<add key ="token" value ="PW1BDVNqVPVanwduF_Tb2Ey91aT1Uhx1kL7HPc-7e8S-6AnUwSSHyasolSe"/>
<add key ="paypalemail" value =""/>

<!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->
<add key="PayPalSubmitUrl" value=""/>

<add key="FailedURL" value="http://localhost:2525/PayPalIntegration/Failed.aspx"/>

<add key="SuccessURL" value="http://localhost:2525/PayPalIntegration/Success.aspx"/>


In the above url are local testing url after hosted in live changed your domain name in this values.

Steps to Execute Details Output

Make sure you are logged in the with your email id in the same browser during testing. Then only working fine to deduct amount etc. correctly. Only Sandbox site we must logged in developer site during testing but not in live after hosted it
After user click Buy now in the gridview redirect to confirmation page show to details

In this confirmation page we keep that values in hidden field to send information to PayPal . after user click submit button redirect to paypal page

Now logged in to the Personal account mean Buyer account. After logged in display like below

Verify Details and click Paynow button. After that amount $ 55 USD deducted from your paypal personal account and increased $55 in seller account.
After click paynow confirmation show your transaction reference no like below

After that automatically redirect to merchant site whatever URL you are configure in web.config file and insert data in the table.
In the test account page select personal account radio button and then click enter sandbox site button below in that page to redirect personal account deails page
Below screen show Personal account detail after paid to seller

The above screen shot clearly shows -$55 deducted from my personal account
Below screen show Business account detail after get amount from buyer

The above screen shot clearly shows $55 amount get from user and total is increased

If you not redirect to your website after payment complete then follow the below steps to set return url in business account.

a. Click on the business test account id and click enter Sandbox test site
b. Choose Profile --> More options in the menu under Selling Preferences choose Website Payment Preferences
c. Select Auto Return on radio button to redirect and enter return URL below like if you don't have any domain just enter any valid domain name like your blog URL etc. because its only for testing
d. Enable on Payment Data Transfer to get payment data return in website and save it.
e. Again go to more option website payment reference and see identity token is generated (under payment data transfer) copy that identity token use it in the website web.config file.

Source code:

Client Side: ASP.NET
Code Behind: C#


I hope this article is help you to know about integrate PayPal add to cart option in your website.


  • Source _code (44018-0650-Source-code.rar)
  • Comments

    Author: ANIL21 Aug 2012 Member Level: Bronze   Points : 1

    why your entered vales dynamically?
    I want to display vales from database

    WHAT IS THIS add key="token" value="PW1BDVNqVPVanwduF_Tb2Ey91aT1Uhx1kL7HPc-7e8S-6AnUwSSHyasolSe"
    I am process same process your steps but getting an Error
    Error is:At this time, we are unable to process your request. Please return to and try another option.

    Author: ANIL21 Aug 2012 Member Level: Bronze   Points : 0

    Processing.aspx also not working

    Author: Ravindran21 Aug 2012 Member Level: Diamond   Points : 3


    Please read that ReadMe.docx attached in that source folder.

    Then create sandbox account and inside that account to create two accounts business (Seller) and personal (buyer). Just replace that seller account id in web.config and change port no in success & failed page as per your port after localhost: word. Then just run that source and test after you understand that process rewrite your code as per your requirement and make sure you logged in sandbox account during testing.

    I am give sample code only so i am using some static data through data table. If you want load data from database then alter that code as per your requirement and used it.

    No need token for shopping cart option leave it.

    Author: ANIL21 Aug 2012 Member Level: Bronze   Points : 0

    Thank you so much

    Guest Author: Vivek Kumar04 Sep 2012

    Thankyou So much Its awesome code for integrating paypal with your websites...........

    Guest Author: sijo12 Sep 2012

    Hello Ravindran,
    Thank you for this wonderful solution to integrate Paypal in to ASP.NET web applications. You have explained a complex solution in a very simplified manner.

    Author: Ravindran12 Sep 2012 Member Level: Diamond   Points : 0

    Thanks Vivek and sijo

    Guest Author: Ilakkiya31 Oct 2012

    Hello Ravindran...
    It's a wonderful article..Thank u very much:)

    Guest Author: Pankaj21 Nov 2012

    Invalid postback or callback argument.
    when i click buy
    What could be the solution

    Guest Author: Abhishek07 Dec 2012

    nice code bro...really helped me alot.....thanks again :)

    Guest Author: Diana29 Jun 2013

    Hi! I'm a student doing a PayPal integration and found this really useful! Thanks for the tip!

    Guest Author: maulesh patel03 Sep 2013

    Really useful information.

    just one concern the UI you show in the screenshot for sandbox is changed now.

    Guest Author: Atul Sharma12 Feb 2014

    Dear Ravindran,
    The code is really very helpful for us
    but now i need to checkout with more than one products using cart
    can you plz help us

    Author: srirama10 Sep 2014 Member Level: Gold   Points : 0

    Dear Ravidran,

    Is it possible to redirect to the Localhost that mentioned in this Article...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: