Payment Gateway Integration With ASP.NET MVC

Introduction 

 
In this article we will learn how to integrate the PayU Money Payment gateway with our Asp.net MVC project. Along with that we will also learn how to use PayU Money, and what MerchantID, SaltID and many more are. So let's start our journey.
 
Prerequisite
 
Please install the latest version of Visual Studio before reading this article.
 

Procedure

 
Click here to see the  PayU Money website. You just have to create a new account or log in to it. Now switch to test mode from live mode because we are creating the project for testing purposes. You can also link your bank account with this and do the transaction with your project. All procedures we are doing here will be the same, you just have to choose the live option.
 
 
See that you got your unique Merchant ID and Salt ID. It is so useful for integrating your project with PayU. 
 
 
You can also find lots of information in the DeveloperGuide section.
 
Now we will go in Visual Studio and start creating a demo project. If you don't know about how to create a project in MVC just see my Previous article
 
Let's start our project In ASP.NET MVC. So follow the steps to create a new project in Visual Studio.
  1. Click On Create New Project
  2. Write ASP.NET in Searchbar
  3. Select ASP.NET Web Application
  4. Give a name to your project (My Project Name:"PayUmoneytry")
Now Add two Controllers and model class in it.
 
 
Add model (DemoModel) as you can see in the image.
  1. public class DemoModel  
  2.    {  
  3.        [Required]  
  4.        public string FirstName { getset; }  
  5.        [Required]  
  6.        public string Amount { getset; }  
  7.        [Required]  
  8.        public string Phone { getset; }  
  9.        [Required]  
  10.        public string ProductInfo { getset; }  
  11.        public string Email { getset; }  
  12.    }  
 Now Add View for Demo Controller
  1. @model PayUmoneytry.Models.DemoModel  
  2. @{  
  3.     ViewBag.Title = "Demo";  
  4. }  
  5.   
  6. <h2>PayUMoney Form MVC</h2>  
  7. @using (Html.BeginForm())  
  8. {  
  9.     <div style="margin-left:20px">    
  10.         @Html.Label("Amount")<br 
  11.         @Html.TextBox("txtamount")<br />
  12.         @Html.Label("First Name")<br />  
  13.         @Html.TextBox("txtfirstname")<br />  
  14.         @Html.ValidationMessageFor(model => model.firstName, " "new { @class = "text-danger" })  
  15.         @Html.Label("Email Id")<br />  
  16.         @Html.TextBox("txtemail")<br />  
  17.         @Html.ValidationMessageFor(model => model.email, " "new { @class = "text-danger" })  
  18.         @Html.Label("Product Information")<br />  
  19.         @Html.TextArea("txtprodinfo")<br />  
  20.         @Html.Label("Phone")<br />  
  21.         @Html.TextBox("txtphone")<br />   
  22.         <button type="submit">Submit</button>  
  23.     </div>  
  24.   
  25.   
  26. }  
Add method in democontroller.
  1. [HttpGet]  
  2. public ActionResult Demo()  
  3. {  
  4.     return View();  
  5. }  
  6. [HttpPost]  
  7. public void Demo(FormCollection form)  
  8. {  
  9.     try  
  10.     {  
  11.         string firstName = form["txtfirstname"].ToString();  
  12.         string amount = form["txtamount"].ToString();  
  13.         string productInfo = form["txtprodinfo"].ToString();  
  14.         string email = form["txtemail"].ToString();  
  15.         string phone = form["txtphone"].ToString();  
  16.         string surl = "http://localhost:55447/Return/Return";  //Change the success url here depending upon the port number of your local system.
  17.         string furl = "http://localhost:55447/Return/Return";  //Change the failure url here depending upon the port number of your local system.
  18.          
  19.         
  20.   
  21.   
  22.         RemotePost myremotepost = new RemotePost();  
  23.         //Add your MarchantID;  
  24.         string key = "add your MarchantID";  
  25.         //Add your SaltID;  
  26.         string salt = "add your SaltID";  
  27.   
  28.         //posting all the parameters required for integration.  
  29.   
  30.         myremotepost.Url = "https://sandboxsecure.payu.in/_payment";  
  31.         myremotepost.Add("key""4ptctt6n");  
  32.         string txnid = Generatetxnid();  
  33.         myremotepost.Add("txnid", txnid);  
  34.         myremotepost.Add("amount", amount);  
  35.         myremotepost.Add("productinfo", productInfo);  
  36.         myremotepost.Add("firstname", firstName);  
  37.         myremotepost.Add("phone", phone);  
  38.         myremotepost.Add("email", email);  
  39.         myremotepost.Add("surl""http://localhost:55447/Return/Return");//Change the success url here depending upon the port number of your local system.  
  40.         myremotepost.Add("furl""http://localhost:55447/Return/Return");//Change the failure url here depending upon the port number of your local system.  
  41.         myremotepost.Add("service_provider""payu_paisa");  
  42.         string hashString = key + "|" + txnid + "|" + amount + "|" + productInfo + "|" + firstName + "|" + email + "|||||||||||" + salt;  
  43.         string hash = Generatehash512(hashString);  
  44.         myremotepost.Add("hash", hash);  
  45.   
  46.         myremotepost.Post();  
  47.     }  
  48.     catch(Exception exp)  
  49.     {  
  50.         throw;  
  51.     }  
  52.       
  53.   
  54. }  
surl and furl change according to your code. surl = Success url. After successfuly completing your transaction it will redirect to this url.
furl = Fail url. If transaction fails then it will redirect to this url.
 
Also add this method into your Democontroller.
  1. private string Generatetxnid() {  
  2.     Random rnd = new Random();  
  3.     string strHash = Generatehash512(rnd.ToString() + DateTime.Now);  
  4.     string txnid1 = strHash.ToString().Substring(0, 20);  
  5.   
  6.     return txnid1;  
  7. }  
  8.   
  9. private string Generatehash512(string text) {  
  10.     byte[] message = Encoding.UTF8.GetBytes(text);  
  11.   
  12.     UnicodeEncoding UE = new UnicodeEncoding();  
  13.     byte[] hashValue;  
  14.     SHA512Managed hashString = new SHA512Managed();  
  15.     string hex = "";  
  16.     hashValue = hashString.ComputeHash(message);  
  17.     foreach(byte x in hashValue) {  
  18.         hex += String.Format("{0:x2}", x);  
  19.     }  
  20.     return hex;  
  21. }  
  22. public class RemotePost {  
  23.     private System.Collections.Specialized.NameValueCollection Inputs = new System.Collections.Specialized.NameValueCollection();  
  24.   
  25.   
  26.     public string Url = "";  
  27.     public string Method = "post";  
  28.     public string FormName = "form1";  
  29.   
  30.     public void Add(string name, string value) {  
  31.         Inputs.Add(name, value);  
  32.     }  
  33.   
  34.     public void Post() {  
  35.         System.Web.HttpContext.Current.Response.Clear();  
  36.   
  37.         System.Web.HttpContext.Current.Response.Write("<html><head>");  
  38.   
  39.         System.Web.HttpContext.Current.Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));  
  40.         System.Web.HttpContext.Current.Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, Url));  
  41.         for (int i = 0; i < Inputs.Keys.Count; i++) {  
  42.             System.Web.HttpContext.Current.Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\">", Inputs.Keys[i], Inputs[Inputs.Keys[i]]));  
  43.         }  
  44.         System.Web.HttpContext.Current.Response.Write("</form>");  
  45.         System.Web.HttpContext.Current.Response.Write("</body></html>");  
  46.   
  47.         System.Web.HttpContext.Current.Response.End();  
  48.     } 
Now we come to Return Controller.
 
Add view for Return() Action method.
  1. @{  
  2.     ViewBag.Title = "Return";  
  3. }  
  4.   
  5. <h2>PayUMoney Response</h2>  
  6.   
  7. <h1> ViewData["Message"] </h1>  
 Add method in Return Controller.
  1. public void Return(FormCollection form)  
  2.         {  
  3.             try  
  4.             {  
  5.   
  6.                 string[] merc_hash_vars_seq;  
  7.                 string merc_hash_string = string.Empty;  
  8.                 string merc_hash = string.Empty;  
  9.                 string order_id = string.Empty;  
  10.                 string hash_seq = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";  
  11.   
  12.                 if (form["status"].ToString() == "success")  
  13.                 {  
  14.   
  15.                     merc_hash_vars_seq = hash_seq.Split('|');  
  16.                     Array.Reverse(merc_hash_vars_seq);  
  17.                     merc_hash_string = ConfigurationManager.AppSettings["SALT"] + "|" + form["status"].ToString();  
  18.   
  19.   
  20.                     foreach (string merc_hash_var in merc_hash_vars_seq)  
  21.                     {  
  22.                         merc_hash_string += "|";  
  23.                         merc_hash_string = merc_hash_string + (form[merc_hash_var] != null ? form[merc_hash_var] : "");  
  24.   
  25.                     }  
  26.                     Response.Write(merc_hash_string);  
  27.                     merc_hash = Generatehash512(merc_hash_string).ToLower();  
  28.   
  29.   
  30.   
  31.                     if (merc_hash != form["hash"])  
  32.                     {  
  33.                         Response.Write("Hash value did not matched");  
  34.   
  35.                     }  
  36.                     else  
  37.                     {  
  38.                         order_id = Request.Form["txnid"];  
  39.   
  40.                         ViewData["Message"] = "Status is successful. Hash value is matched";  
  41. ;  
  42.                         Response.Write("<br/>Payment successful");  
  43.   
  44.                         //Hash value did not matched  
  45.                     }  
  46.   
  47.                 }  
  48.   
  49.                 else  
  50.                 {  
  51.   
  52.                     Response.Write("Hash value did not matched");  
  53.                     // osc_redirect(osc_href_link(FILENAME_CHECKOUT, 'payment' , 'SSL', null, null,true));  
  54.   
  55.                 }  
  56.             }  
  57.   
  58.             catch (Exception ex)  
  59.             {  
  60.                 Response.Write("<span style='color:red'>" + ex.Message + "</span>");  
  61.   
  62.             }  
  63.   
  64.   
  65.         }  
Return() method will give the output accordingly after the transection completes or fails. 
 
Also add this method in Returncontroller.
  1. public string Generatehash512(string text)  
  2. {  
  3.   
  4.     byte[] message = Encoding.UTF8.GetBytes(text);  
  5.   
  6.     UnicodeEncoding UE = new UnicodeEncoding();  
  7.     byte[] hashValue;  
  8.     SHA512Managed hashString = new SHA512Managed();  
  9.     string hex = "";  
  10.     hashValue = hashString.ComputeHash(message);  
  11.     foreach (byte x in hashValue)  
  12.     {  
  13.         hex += String.Format("{0:x2}", x);  
  14.     }  
  15.     return hex;  
  16.   
  17. }  
 Add a few lines in your web.config file.
  1. <appSettings>  
  2.    <add key="webpages:Version" value="3.0.0.0"/>  
  3.    <add key="webpages:Enabled" value="false"/>  
  4.    <add key="PreserveLoginUrl" value="true" />  
  5.    <add key="ClientValidationEnabled" value="true"/>  
  6.    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>  
  7.    <add key="MERCHANT_KEY" value="Add your marchantkey"/> //Add your marchantkey 
  8.    <add key="SALT" value="Add your salt key"/>  //Add your Salt key
  9.    <add key="PAYU_BASE_URL" value="https://sandboxsecure.payu.in"/>  
  10.    <add key="action" value=""/>  
  11.    <add key="hashSequence" value="key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10"/>  
  12.  </appSettings>  
 
 Now we are done with our project but before we build and run it give the proper route in route.config file.
 
Outputs
 
 
 
After submitting: 
 
Enter OTP
 
 
Transaction completed successfully,
 
Thank you and happy learning.


Similar Articles