This article discusses integration of PayPal Payment in ASP.NET 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.
PayPal supports several types of payments:
- Payments for goods in the PayPal cart. PayPal is responsible for all operations supporting the cart in this case. Unfortunately, this option does not provide the maximum flexibility that is required to implement some projects, so the article does not consider this option.
- Recurring billing or subscription. PayPal provides a subscription capability; that means that a definite sum will be periodically transferred from the user's account to the seller's account. The user can unsubscribe anytime. The seller can specify the subscription's period and cost. He also can organize a trial period to let the user assess the quality of services he provides. The trial period can be either paid or free.
- "One click" shopping. Goods are not put into the cart in this case. This method also is used to pay for goods in a cart that was filled without PayPal. That's why this option provides maximum flexibility and full control of the cart.
Let’s start step by step work to integrate PayPal payment :
1. Create PayPal account on PayPal Sandbox: Basically, PayPal provides an environment to developer that how they can integrate PayPal payment in their website. So just open URL: https://developer.paypal.com/ and click on SignUp option.
2. Create buyer (Personal Account) and one seller account (Business Account) PayPal account.
3. Having a valid PayPal API Token Key
4. Having PayPal business account email id
5. Create New Page on ASP.NET project and copy this script :
On ASPX PAGE:
<%@PageTitle="Home Page"Language="C#"MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Default.aspx.cs"Inherits="_Default"%>
<asp:ContentID="HeaderContent"runat="server"ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:ContentID="BodyContent"runat="server"ContentPlaceHolderID="MainContent">
<div>
<tablewidth="700"align="center"cellpadding="0"cellspacing="0">
<tr>
<tdheight="60">
<b>Paypal Integration in ASP.NET</b>
</td>
</tr>
<tr>
<tdheight="40"align="center">
<asp:GridViewID="gvPayPal"runat="server"AutoGenerateColumns="False"OnRowCommand="gvPayPal_RowCommand"
BackColor="#DEBA84"BorderColor="#DEBA84"BorderStyle="None"BorderWidth="1px"
CellPadding="3"CellSpacing="2">
<RowStyleForeColor="#8C4510"BackColor="#FFF7E7"/>
<Columns>
<asp:TemplateFieldHeaderText="Product Name">
<ItemTemplate>
<asp:LabelID="lblName"runat="server"Text='<%#Eval("prodName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateFieldHeaderText="Product Description">
<ItemTemplate>
<asp:LabelID="lblDescription"runat="server"Text='<%#Eval("prodDesc") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateFieldHeaderText="Product price">
<ItemTemplate>
<asp:LabelID="lblProductPrice"runat="server"Text='<%#Eval("prodPrice") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateFieldHeaderText="Buy Now">
<ItemTemplate>
<asp:ImageButtonID="ImageButton1"runat="server"ImageUrl="~/images/buy.png"
Width="64"Height="64"CommandName="buy"CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyleBackColor="#F7DFB5"ForeColor="#8C4510"/>
<PagerStyleForeColor="#8C4510"HorizontalAlign="Center"/>
<SelectedRowStyleBackColor="#738A9C"Font-Bold="True"ForeColor="White"/>
<HeaderStyleBackColor="#A55129"Font-Bold="True"ForeColor="White"/>
<SortedAscendingCellStyleBackColor="#FFF1D4"/>
<SortedAscendingHeaderStyleBackColor="#B95C30"/>
<SortedDescendingCellStyleBackColor="#F1E5CE"/>
<SortedDescendingHeaderStyleBackColor="#93451F"/>
</asp:GridView>
</td>
</tr>
</table>
<!-- PayPal Logo -->
<tableborder="0"cellpadding="10"cellspacing="0"align="center">
<tr>
<tdalign="center">
</td>
</tr>
<tr>
<tdalign="center">
<astyle="cursor:pointer;"title="Paypal payment gateway center"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');">
<imgsrc="https://www.paypal.com/en_US/i/bnr/horizontal_solution_PPeCheck.gif"border="0"
alt="Solution Graphics"></a>
</td>
</tr>
</table>
<!-- PayPal Logo -->
</div>
</asp:Content>
On CS PAGE :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
publicpartialclass_Default : System.Web.UI.Page
{
SqlConnection Con = newSqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
SqlCommand cmd = newSqlCommand();
SqlDataAdapter da = newSqlDataAdapter();
DataTable dt = newDataTable();
DataRow dr;
protectedvoid Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Add some column to datatable display some products information
dt.Columns.Add("prodName");
dt.Columns.Add("prodDesc");
dt.Columns.Add("prodPrice");
//Add rows with datatable and bind in the grid view
dr = dt.NewRow();
dr["prodName"] = "MindStick Cleaner";
dr["prodDesc"] = "Cleans all system dummy data";
dr["prodPrice"] = "$100.00";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["prodName"] = "MindStick DataConverter";
dr["prodDesc"] = "Helps to import export data in different format";
dr["prodPrice"] = "$120.00";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["prodName"] = "MindStick SurveyManager";
dr["prodDesc"] = "Helps creating survey page with specified format dll";
dr["prodPrice"] = "$140.00";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["prodName"] = "MindStick TeraByte Importer";
dr["prodDesc"] = "Data transfer utility";
dr["prodPrice"] = "$30.00";
dt.Rows.Add(dr);
gvPayPal.DataSource = dt;
gvPayPal.DataBind();
}
}
protectedvoid gvPayPal_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "buy")
{
ImageButton ib = (ImageButton)e.CommandSource;
int index = Convert.ToInt32(ib.CommandArgument);
GridViewRow row = gvPayPal.Rows[index];
//Get each Column label value from grid view and store it in label
Label pName = (Label)row.FindControl("lblName");
Label pDescription = (Label)row.FindControl("lblDescription");
Label pPrice = (Label)row.FindControl("lblProductPrice");
//Here store that person name who are going to make transaction
Session["user"] = "Arun Singh";
// make query string to store logged in user information in sql server table
string query = "";
query = "insert into purchase(pname,pdesc,price,uname) values('" + pName.Text + "','" + pDescription.Text + "','" + pPrice.Text.Replace("$", "") + "','" + Session["user"].ToString() + "')";
Con.Open();
cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
Con.Close();
//Pay pal process Refer for what are the variable are need to send http://www.paypalobjects.com/IntegrationCenter/ic_std-variable-ref-buy-now.html
string redirectUrl = "";
//Mention URL to redirect content to paypal site
redirectUrl += "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" + ConfigurationManager.AppSettings["paypalemail"].ToString();
//First name I assign static based on login details assign this value
redirectUrl += "&first_name=Arun_Seller";
//Product Name
redirectUrl += "&item_name=" + pName.Text;
//Product Amount
redirectUrl += "&amount=" + pPrice.Text;
//Business contact paypal EmailID
redirectUrl += "&business=arunse_1358772383_biz@gmail.com";
//Shipping charges if any, or available or using shopping cart system
redirectUrl += "&shipping=5";
//Handling charges if any, or available or using shopping cart system
redirectUrl += "&handling=5";
//Tax charges if any, or available or using shopping cart system
redirectUrl += "&tax=5";
//Quantiy of product, Here statically added quantity 1
redirectUrl += "&quantity=1";
//If transactioin has been successfully performed, redirect SuccessURL page- this page will be designed by developer
redirectUrl += "&return=" + ConfigurationManager.AppSettings["SuccessURL"].ToString();
//If transactioin has been failed, redirect FailedURL page- this page will be designed by developer
redirectUrl += "&cancel_return=" + ConfigurationManager.AppSettings["FailedURL"].ToString();
Response.Redirect(redirectUrl);
}
}
}
On DESIGN PAGE :
USE [MyDatabase]
GO
/****** Object: Table [dbo].[purchase] Script Date: 01/27/2013 09:26:07 ******/
SETANSI_NULLSON
GO
SETQUOTED_IDENTIFIERON
GO
SETANSI_PADDINGON
GO
CREATETABLE [dbo].[purchase](
[Id] [int] IDENTITY(1,1)NOTNULL,
[PName] [nvarchar](100)NULL,
[PDesc] [nvarchar](100)NULL,
[Price] [money] NULL,
[Uname] [varchar](50)NULL,
CONSTRAINT [PK_purchase] PRIMARYKEYCLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX =OFF,STATISTICS_NORECOMPUTE =OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS =ON,ALLOW_PAGE_LOCKS =ON)ON [PRIMARY]
)ON [PRIMARY]
GO
SETANSI_PADDINGOFF
GO
On web.config file:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<addname="ApplicationServices"connectionString="data source=Arun-PC;Integrated Security=true; Initial Catalog= MyDatabase; User Id= Arun-PC; Password= mindstick;"providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<compilationdebug="true"targetFramework="4.0"/>
<authenticationmode="Forms">
<forms loginUrl="~/Account/Login.aspx"timeout="2880"/>
</authentication>
<membership>
<providers>
<clear/>
<addname="AspNetSqlMembershipProvider"type="System.Web.Security.SqlMembershipProvider"connectionStringName="ApplicationServices"enablePasswordRetrieval="false"enablePasswordReset="true"requiresQuestionAndAnswer="false"requiresUniqueEmail="false" maxInvalidPasswordAttempts="5"minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0"passwordAttemptWindow="10"applicationName="/"/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<addname="AspNetSqlProfileProvider"type="System.Web.Profile.SqlProfileProvider"connectionStringName="ApplicationServices"applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<addname="AspNetSqlRoleProvider"type="System.Web.Security.SqlRoleProvider"connectionStringName="ApplicationServices"applicationName="/"/>
<addname="AspNetWindowsTokenRoleProvider"type="System.Web.Security.WindowsTokenRoleProvider"applicationName="/"/>
</providers>
</roleManager>
</system.web>
<appSettings>
<addkey="token"value="(insert your paypal API Signature)"/>
<addkey="paypalemail"value="(insert with paypal login email id)"/>
<!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->
<addkey="PayPalSubmitUrl"value="https://www.sandbox.paypal.com/cgi-bin/webscr"/>
<addkey="FailedURL"value="http://localhost:49666/PayPalIntegration/Failed.aspx"/> <!--Failed Page URL-->
<addkey="SuccessURL"value="http://localhost:49666/Default.aspx"/> <!--Success Page URL-->
</appSettings>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
6. Run the project to see the result.
Look no further! You have found the answer. ASPHostPortal.com is your ASP.NET 4.5 hosting home! We understand that as .NET developer, you need to find good .NET hosting that provide reliable and cheap .NET hosting. ASPHostPortal.com supports the latest .NET framework, .NET 4.5, as well as past frameworks like .NET 4, .NET 3.5, and .NET 2.0. All of our .NET hosting comes with FREE Trial Hosting. If the service does not meet your expectations, simply cancel before the end of the free trial period. No Risk!! Why wait longer?