Tuesday 15 July 2014

How to integrate PayPal in ASP.NET 3.5?

How to integrate PayPal in ASP.NET 3.5?

Description :


In this article I am going to deeply explain about PayPal integration, testing with Sandbox developer paypal account.

First I have create table like below to store purchaser detail

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

Now ,Create PayPal Account in SandBox for 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
images

After Click Pre configured create account for buyer and seller like below
images

After enter all details click Create account button. Now those two accounts are displayed in your test accounts like Business, Personal 
images
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");

            //here i temporary use my name as logged in user you can create login page after only make an order
            Session["user"] = "ravi";

            //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();

            //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=ravindran";

            //City i assign static based on login user detail you change this value
            redirecturl += "&city=chennai";

            //State i assign static based on login user detail you change this value
            redirecturl += "&state=tamilnadu";

            //Product Name
            redirecturl += "&item_name=" + l1.Text;

            //Product Amount
            redirecturl += "&amount=" + l3.Text;           

            //Business contact id
            //redirecturl += "&business=nravindranmcaatgmail.com";

            //Shipping charges if any
            redirecturl += "&shipping=5";

            //Handling charges if any
            redirecturl += "&handling=5";

            //Tax amount if any
            redirecturl += "&tax=5";
            
            //Add quatity i added one only statically 
            redirecturl += "&quantity=1";

            //Currency code 
            redirecturl += "¤cy=USD";

            //Success return page url
            redirecturl += "&return=" + ConfigurationManager.AppSettings["SuccessURL"].ToString();

            //Failed return page url
            redirecturl += "&cancel_return=" + ConfigurationManager.AppSettings["FailedURL"].ToString();

            Response.Redirect(redirecturl);
        }
    }
}
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. Web page is look like here
Webpage

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 PayPal  images  Now logged in to the Personal account mean Buyer account. After logged in display like below images  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 like below images After that automatically redirect to merchant site whatever URL you are configure in web.config file and insert transaction 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 images  The above screen shot clearly shows -$55 deducted from my personal account  Below screen show Business account detail after get amount from buyer images  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. 


Conclusion

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


 

0 comments:

Post a Comment