Wednesday, 4 June 2014

Paypal Integration in ASP.NET using C#

It is very general requirement for e-commerce websites, we need to use payment gateways to implement Online Shopping in our website, which is very common functionality needed in any new website we are building in the current era of technology.
I am going to represent how we can integrate PayPal in to a website creating in ASP.NET using C#. Below steps we need to do for integration except the coding part.
1.      We need to create a test account on https://www.sandbox.paypal.com/in/webapps/mpp/home
2.      Now create an application on sandbox which will provide you app key and secret, which we need in code.
3.      Create two accounts on for buyer and one for merchant.
4.      Use the below written code to implement PayPal.

.aspx page's code is ::
  <div>  
       <table>  
         <tr>  
           <td>Price</td>  
           <td>  
             <asp:TextBox ID="txtPrice" runat="server"></asp:TextBox></td>  
         </tr>  
          <tr>  
           <td>Qunatity</td>  
           <td>  
             <asp:TextBox ID="txtQunatity" runat="server"></asp:TextBox></td>  
         </tr>  
         <tr>  
           <td>Shipping</td>  
           <td>  
             <asp:TextBox ID="txtShipping" runat="server"></asp:TextBox></td>  
         </tr>  
         <tr>  
           <td>Item Name</td>  
           <td>  
             <asp:TextBox ID="txtItemName" runat="server"></asp:TextBox></td>  
         </tr>  
         <tr>  
           <td colspan="2">  
             <asp:Button ID="btnSubmit" runat="server" Text="Pay  
               Now" OnClick="btnSubmit_Click" /></td>  
         </tr>  
       </table>  
     </div>  



.aspx.cs file's code is ::

 using System;  
 using System.Collections.Generic;  
 using System.Configuration;  
 using System.Linq;  
 using System.Web;  
 using System.Web.UI;  
 using System.Web.UI.WebControls;  
 public partial class _Default : System.Web.UI.Page  
 {  
   protected void Page_Load(object sender, EventArgs e)  
   {  
   }  
   protected void btnSubmit_Click(object sender, EventArgs e)  
   {  
     Session["pType"] = "att";  
     String rooturl = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].Replace("www.", string.Empty);  
     String SuccessURL = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].Replace("www.", string.Empty) + "/Success.aspx";  
     String FailedURL = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"].Replace("www.", string.Empty) + "/Failed.aspx";  
     Boolean IsPaypalAccountlive = Convert.ToBoolean(ConfigurationManager.AppSettings["IsPaypalAccountlive"].ToString());  
     string paypal_testing = ConfigurationManager.AppSettings["paypal_testing"].ToString();  
     string paypal_live = ConfigurationManager.AppSettings["paypal_live"].ToString();  
     string business_account = ConfigurationManager.AppSettings["business_account"].ToString();  
     string IPN_page = ConfigurationManager.AppSettings["IPN"].ToString();  
     Int32 qty = 0;  
     qty = Convert.ToInt32(txtQunatity.Text.Trim());  
     if (IsPaypalAccountlive == false)  
     {  
       Response.Redirect(paypal_testing + "?cmd=_xclick&business=" + business_account + "&item_name=" + txtItemName.Text.Trim() + "&quantity=" + qty + "&amount=" + Convert.ToDecimal(txtPrice.Text.Trim()) + "&no_shipping=2&return=" + SuccessURL + "&notify_url=" + rooturl + "/" + IPN_page + "&paypal='true'" + "&p=success" + "&cancel_return=" + FailedURL + " &custom=" + /*this.UserInfo.UserID + "_" + this.PortalId +*/"1_1" + "&no_note=10&shipping=0&currency_code=AUD&lc=US&bn=PP-BuyNowBF&charset=UTF-8");  
     }  
     else if (IsPaypalAccountlive == true)  
     {  
       Response.Redirect(paypal_live + "?cmd=_xclick&business=" + business_account + "&item_name=" + txtItemName.Text.Trim() + "&quantity=" + qty + "&amount=" + Convert.ToDecimal(txtPrice.Text.Trim()) + "&no_shipping=2&return=" + SuccessURL + "&notify_url=" + rooturl + "/" + IPN_page + "&paypal='true'" + "&p=success" + "&cancel_return=" + FailedURL + " &custom=" + /*this.UserInfo.UserID + "_" + this.PortalId +*/"1_1" + "&no_note=10&shipping=0&currency_code=AUD&lc=US&bn=PP-BuyNowBF&charset=UTF-8");  
     }  
     Session.Remove("AttendeeFee");  
     Session.Remove("AttendeeList");  
     Session.Remove("ServiceName");  
   }  
 }  


Here is the code of web.config file:
 <appSettings>  
    <add key="business_account" value="*****"/>  
   <add key="paypal_live" value="https://www.paypal.com/cgi-bin/webscr"/>  
   <add key="paypal_testing" value="https://www.sandbox.paypal.com/cgi-bin/webscr"/>  
   <add key="IsPaypalAccountlive" value="false"/>  
   <add key="IPN" value="ipnpal.aspx"/>  
  </appSettings>   

here is the IPN page's code:

Page Load code of IPN Page




IPN Page is used to verify the status of the Payment, it is verified by PayPal it self weather the payment has completed successfully or not.
 public int UserID_prop { get; set; }  
   public static int orderid = 0;  
   protected void Page_Load(object sender, EventArgs e)  
   {  
     //Post back to either sandbox or live  
     string PaypalURL = string.Empty;  
     string IsPaypalAccountlive = ConfigurationManager.AppSettings["IsPaypalAccountlive"].ToString();  
     string paypal_testing = ConfigurationManager.AppSettings["paypal_testing"].ToString();  
     string paypal_live = ConfigurationManager.AppSettings["paypal_live"].ToString();  
     if (IsPaypalAccountlive == "false")  
     {  
       //PaypalURL = "https://www.sandbox.paypal.com/cgi-bin/webscr";  
       PaypalURL = paypal_testing;  
     }  
     else  
     {  
       //PaypalURL = "https://www.paypal.com/cgi-bin/webscr";  
       PaypalURL = paypal_live;  
     }  
     HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PaypalURL);  
     //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);  
     string strResponse_copy = strRequest; //Save a copy of the initial info sent by PayPal  
     strRequest += "&cmd=_notify-validate";  
     req.ContentLength = strRequest.Length;  
     //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();  
     //Send mail with strResponse <br> strResponse_copy  
     string strtestcopy = strResponse_copy + "<br />" + strResponse;  
     streamIn.Close();  
     if (strResponse == "VERIFIED")  
     {  
       //check the payment_status is Completed  
       //check that txn_id has not been previously processed  
       //check that receiver_email is your Primary PayPal email  
       //check that payment_amount/payment_currency are correct  
       //process payment  
       // pull the values passed on the initial message from PayPal  
       NameValueCollection these_argies = HttpUtility.ParseQueryString(strResponse_copy);  
       //string user_email = these_argies["payer_email"];  
       string pay_stat = these_argies["payment_status"];  
       string amount = these_argies["amount"];  
       String[] split_values = these_argies["custom"].ToString().Split('_');  
       if (pay_stat.Equals("Completed"))  
       {  
         try  
         {  
           Response.Write("Sucess");  
         }  
         catch (Exception ex)  
         {  
           Response.Write(ex.Message);  
         }  
       }  
       // more checks needed here specially your account number and related stuff  
     }  
     else if (strResponse == "INVALID")  
     {  
       //log for manual investigation  
     }  
     else  
     {  
       //log response/ipn data for manual investigation  
     }  
   }  

That's all.