Tuesday, 22 October 2024

Razorpay payment gateway intergration C# ASP.Net MVC5

 

Streamline your payments with Razorpay integration in ASP.NET MVC5 using C#. This comprehensive guide provides step-by-step instructions and includes well-commented source code.

Key benefits:
  • Versatile application: The code can be seamlessly integrated into any e-commerce or web application requiring a secure payment gateway.
  • Real-world example: The accompanying sample code demonstrates a printing house scenario, similar to VistaPrint, where users upload PDFs for printing and utilize Razorpay for secure transactions.

Need help? Don't hesitate to reach out for assistance via email at rajkumar9795@gmail.com.

Screen Shots



Checkout

Checkout


Razorpay Payment Page


Steps 1 (Signup Razorpay)

Sign up for Razorpay to obtain your public and secret keys for both test and live environments. Use the test keys to simulate real-world payment scenarios. Once testing is complete, simply replace the test keys with the live keys. For detailed assistance with signing up, you can search for "Razorpay signup" on YouTube, where you’ll find numerous tutorial videos. Steps for signing up are not included here to keep this post concise.

Step 2 (Add Keys)

After obtaining the test key from step 1, open the web.config file and add your key in the <appSettings> section. In the given  example below, a test key is used. Replace this keys with your actual test key, and once testing is complete, replace it with your live key.

<appSettings>

       <add key="RazorPaykey" value="rzp_test_8tA6a3yZ37fImL" />

       <add key="RazorPaySecret" value="zi3Ue184585oNam4eYLKwVbw" />

</appSettings>

Step 3 (Razorpay Extension Installation)

Install Razorpay extension from Nuget .  The menu as given below

Tools > Nuget Package Manager >  Manage Nuget Packages for solution.

Search Razorpay in the Browse search textbox.


Step 4  (Create Order )


HTML & Javascript

 <input type="hidden" value="@ViewBag.orderId" id="oid" />

<button id="rzp-button1"  class="btn btn-primary">

Proceed to Pay 

</button>

<script src="https://checkout.razorpay.com/v1/checkout.js"></script>

<!-- Hidden form to create order by sending request to Razorpay-->
<form action="/order/payment" method="post" name="razorpayForm">
  <input id="razorpay_payment_id" type="hidden" name="razorpay_payment_id" />
  <input id="razorpay_order_id" type="hidden" name="razorpay_order_id" />
  <input id="razorpay_signature" type="hidden" name="razorpay_signature" />
</form>


<script>
  /*  alert(document.getElementById('oid').value);*/
  var orderId = document.getElementById('oid').value;
  var options = {
     "name": "Prints Online",
     "description": "Payment using Razorpay",
     "order_id": orderId,
     "image": "https://example.com/AppImage/page/logo.png", "prefill":
     {
        "name": "Prints Online",
        "email": "info@exanple.com",
        "contact":"+919999999999",
      },
      "notes":
       {
           "address": "Test Payment"
       },
      "theme":
       {
         "color": "#3399cc"
       }
}

// Boolean whether to show image inside a white frame. (default: true)               options.theme.image_padding= false;
 options.handler = function (response) {
   document.getElementById('razorpay_payment_id').value = response.razorpay_payment_id;           document.getElementById('razorpay_order_id').value = orderId;                       document.getElementById('razorpay_signature').value = response.razorpay_signature;
   document.razorpayForm.submit();
        };
        options.modal = {
            ondismiss: function() {
              console.log("This code runs when the popup is closed");
              },
      // Boolean indicating whether pressing escape key
      // should close the checkout form. (default: true)
       escape: true,
      // Boolean indicating whether clicking translucent blank
     // space outside checkout form should close the form. (default: false)                           backdropclose: false
     };
     var rzp = new Razorpay(options);
     document.getElementById('rzp-button1').onclick = function (e) {
        rzp.open();
        e.preventDefault();

        }

        </script>

Controller

public ActionResult StartPaymentProcess(string amount)
{

  var key = ConfigurationManager.AppSettings["RazorPaykey"].ToString();
  var secret = ConfigurationManager.AppSettings["RazorPaySecret"].ToString();
  RazorpayClient client = new RazorpayClient(key, secret);
  Dictionary <string, object> options = new Dictionary<string, object>();
  options.Add("amount", Convert.ToDecimal(amount) * 100); // multiply by 100 to accommodate      decimal values
  options.Add("currency", "INR"); // change curreny INR to $ g for get  payment in dollar
  Order order = client.Order.Create(options);
  ViewBag.orderId = order["id"].ToString();
  return View("Payment");  // view to show user final proceed to pay

}


public ActionResult Payment(string razorpay_payment_id, string razorpay_order_id, string razorpay_signature)
{
    Dictionary<string, string> attributes = new Dictionary<string, string>();                 
    attributes.Add(
"razorpay_payment_id", razorpay_payment_id);|
    attributes.Add("razorpay_order_id", razorpay_order_id);
    attributes.Add("razorpay_signature", razorpay_signature);
    try
    {
        Utils.verifyPaymentSignature(attributes);
        return View("PaymentSuccess");
    }
    catch (Exception ex)
    {
        return View("PaymentFailure");
    }
    return View();

}

Step 5 (Success,Failure page)


You can create success or failure page to show appropriate message to user . you can also save/show the ordered. which is coming from Payment view . Check the payment view signature and save the razorpay_order_id in database for future reference.



No comments:

Post a Comment