Thursday, November 24, 2011

Paypal Integration In Asp.Net With IPN handler


Step 1:  Go to this link https://developer.paypal.com/ and create a test Account.



Step 2:  After Creating your SandBox Test Account Click On  Create a preconfigured account   link just like in below Pics.

Step 3:   Now You Need to Create two Account One for Buyer And another one for seller.
You can change your password for test account.

During account creation add some  Account Balance in Account Balance Section of Above Figure.

Step 4: Repeat this procedure for Seller Account as well.

After Creating Your test Account Click On Test Accounts Link on Side Bar. You can see your test Accounts
Just like below image.



Step 5  Now You have created two Test Account  successfully.
Step 6
Now You have to do Asp.net work.
1)Create a Web Form Add some field into it for carrying Amount  for example.
<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Amount
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="PayNow" OnClick="Button1_Click" /></div>
    </form>
</body>
</html>


Add this Code On Code Behind File.
sing System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session["totalShoppingAmt"] = TextBox1.Text;
        Session["orderID"] = string.Format("{0:d7}", (DateTime.Now.Ticks / 10) % 10000000);
        Response.Redirect("sendpayment.aspx");
    }
}

Now You Need to create one mor form which will handle this request. Called SendPayment.aspx
Add This Code to that file.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sendpayment.aspx.cs" Inherits="sendpayment" %>

<!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>Untitled Page</title>
</head>
<body>
<!--form action for live transaction https://www.paypal.com/cgi-bin/webscr-->
    <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" id="form1"
        name="form1">
        <input type="hidden" name="cmd" value="_xclick" />
        <input type="hidden" name="business" value="Your Business Account Email" /><!--Paypal or sandbox Merchant account -->
        <input type="hidden" name="item_name" value="<%=Session["orderID"]%>_Books"/>
        <input type="hidden" name="item_number" value="InvoiceId" />
        <input type="hidden" name="rm" value="2" />
        <input type="hidden" name="amount" value="<%=Session["totalShoppingAmt"]%>" />
        <input type="hidden" name="return" value="Return Url just like an thanks Page" /><!--this page will be your redirection page thanks.aspx -->
        <input type="hidden" name="cancel_return" value="Cancel Url if payer cancel the payment" /> <!--  Cancel.apsx-- >
        <input type="hidden" name="currency_code" value="USD" />
        <input type="hidden" name="notify_url" value="http://domainname/paypal.aspx" /><!--this should be your domain web page where you going to receive all your transaction variables  Make sure this will be active domain not local host it will handle your Ipn Details. Return by paypal  -->
    </form>

    <script language="javascript" type="text/javascript">
    document.form1.submit();  
    </script>

</body>
</html>
You don’t need to add some code in code behind file dor this. Sendpayment.aspx
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class sendpayment : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Now Thanks.aspx will be just like this.
%@ Page Language="C#" AutoEventWireup="true" CodeFile="thanks.aspx.cs" Inherits="thanks" %>

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Thankyou
   
    </div>
    </form>
</body>
</html>
Thanks.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class thanks : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Cancel</div>
    </form>
</body>
</html>
Cancel.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class cancel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Now you need to Create a Ipn Handler Page for processing post payment data return by paypal.

Create a Page called Paypal.aspx.

And add following code on code Behind Page.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using System.Net;


public partial class paypal : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

//Post back to either sandbox or live
string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
// string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);

//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(param);
 strRequest += "&cmd=_notify-  validate";
req.ContentLength = strRequest.Length;

//for proxy
//WebProxy proxy = new WebProxy(new Uri("http://url:port#"));
//req.Proxy = proxy;

//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();


if (strResponse == "VERIFIED")
{

}
else if (strResponse == "INVALID")
{

}
else
{

 

}
}
}

This Page Will be Processed at back end andyou can update the payment Status and data given by paypal to your database.

Note : For Making IPN  workable you need to configure some settings to your Paypal business Account.

i) Login into your Paypal Business Account

ii) Go To profile Sub Tab
iii) Click on Instant Payment Notification Preferences Under Selling Preferences Tab.


 iv) After that Click On Edit Setting's Section in Below Image.



 v) Now Enter Your Notification Url Please make sure this will be of Live Server It will not work on your localhost. in below Image.


 And Make Sure IPN Enabled Radio Button is Checked. Click On Save.

vi) Now Agian Go To Profile Sub Tab And Click On Website Payment Preferences.
vii) Now Make it Auto return Url On. and Enter Your url for thanks Page. Here Paypal will return back after making your payment.
Now Please Upload all these files to a live server that can be accessed through web. and run your files. For Testing purpose i create a Textfile on Your solution called TextFile.txt.During Payment testing i will write the data returned by paypal in this file you can change it and update your database in live scenerio.
Now You will be able to make payment and Use ipn .

For any clarification or query you Can contact me at sharmapankaj133@gmail.com
Or You Can Ping me on Skype     pankajs_ugsw.


                                    @@@@@@@....Happy Coding...@@@@@@







8 comments:

  1. I follow all the steps completely, I get success page after successful payment. But it is not calling notify url. Whatever code I written in notify page is not working actually not calling. And please explain related to cmd parameter.

    ReplyDelete
  2. How To Catch Success Mrssage From Paypal

    ReplyDelete
  3. Plz Some One Help Me How To Catch Success Mrssage From Paypal

    ReplyDelete
    Replies
    1. You will get that status on Ipn Handler Page(Please make sure this will be on on some live domain or staging server. localhost url will not work.).

      Delete
  4. You will get that status on Ipn Handler Page(Please make sure this will be on on some live domain or staging server. localhost url will not work.).

    ReplyDelete
  5. Want to know if there is anything to be done to make notify_url work for localhost.I have the given the notify_url as localhost url and return as localhost.It is returing to the return url after payment but i need the payment info in my notifyurl page.I want to debug the page.Can you help me out.

    ReplyDelete
  6. As women, especially as married female entrepreneurs, we often struggle with making money because we believe that we can't increase our Trey Songz Net Worth or manage our money very effectively. And if we're currently carrying debt we tend to think that we're doomed to be in debt for the rest of our lives, because we don't feel competent about getting out of debt. If you have been struggling with debt for a while, it's likely you hold the belief that you are powerless to change your situation.

    ReplyDelete