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 https://developer.paypal.com/ and create Paypal account to be testing

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

1) Buyer account
2) Seller account

output


After Click Preconfigured create account for buyer and seller like below
output

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

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Paypal Integartion</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table width="700" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="60">
<b>Paypal Integration in ASP.NET</b>
</td>
</tr>
<tr>
<td height="40" align="center">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3">
<RowStyle ForeColor="#000066" />
<Columns>
<%-- <asp:TemplateField HeaderText="Product image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Width="80" Height="60" ImageUrl='<%#Eval("path")%>' />
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Product Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("pname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product Description">
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#Eval("pdesc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product price">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%#Eval("price") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Buy Now">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/images/buyNow.png"
Width="80" Height="40" CommandName="buy" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<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" />
</asp:GridView>
</td>
</tr>
</table>
<!-- PayPal Logo -->
<table border="0" cellpadding="10" cellspacing="0" align="center">
<tr>
<td align="center">
</td>
</tr>
<tr>
<td align="center">
<a href="#" onclick="javascript:window.open('https://www.paypal.com/cgi-bin/webscr?cmd=xpt/Marketing/popup/OLCWhatIsPayPal-outside','olcwhatispaypal','toolbar=no,
location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=400, height=350');">
<img src="https://www.paypal.com/en_US/i/bnr/horizontal_solution_PPeCheck.gif" border="0"
alt="Solution Graphics"></a>
</td>
</tr>
</table>
<!-- PayPal Logo -->
</div>
</form>
</body>
</html>

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
dt.Columns.Add("pname");
dt.Columns.Add("pdesc");
dt.Columns.Add("price");

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

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

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

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

GridView1.DataSource = dt;
GridView1.DataBind();
}
}


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() + "')";
sqlcon.Open();
sqlcmd = new SqlCommand(query, sqlcon);
sqlcmd.ExecuteNonQuery();
sqlcon.Close();

//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
Response.Redirect("Processing.aspx");
}
}
}

Processing.aspx


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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Pay Pal Checkout Confirmation</title>
</head>
<body>
<form id="Paypal" name="Paypal" action="https://www.sandbox.paypal.com/cgi-bin/webscr"
method="post">
<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" />

</form>
</body>
</html>


Processing.aspx.cs


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
Response.Write("</table>");
}
}
}


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

<appSettings>
<add key ="token" value ="PW1BDVNqVPVanwduF_Tb2Ey91aT1Uhx1kL7HPc-7e8S-6AnUwSSHyasolSe"/>
<add key ="paypalemail" value ="nravin_1335778770_biz@gmail.com"/>

<!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->
<add key="PayPalSubmitUrl" value="https://www.sandbox.paypal.com/cgi-bin/webscr"/>

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

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

</appSettings>

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 https://developer.paypal.com/ 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 paypal.com after hosted it
After user click Buy now in the gridview redirect to confirmation page show to details
output

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
output

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

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
output

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
output

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

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 http://www.xyz.com 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#

Conclusion

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


Attachments

  • 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 anilgbabu@gmail.com and try another option.

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

    Processing.aspx also not working

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

    ANIL,

    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: Gold   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
    Please.....

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