ASP.NET Core MVC Razorpay Payment Gateway Integration in C#

Step 1: Create a new ASP.NET Core MVC project with Visual Studio 2019.

“Start a new project” -> Choose the ASP.NET Core Web-application MVC template. Give your project a name -> Choose the.NET Core version (I’m using 5) and click “Create.”

Step 2: In Visual Studio, install the Razorpay Nuget package and, navigate to “Tools” -> “Nuget Package Manager” -> Select “Manage package for a solution…”-> Select “Browse” and look for “Razorpay”, Install the “RazorPay.Core” package in your solution.

Step 3: Now, we’ll need a secret key/id, which you can collect from RazorPay Dashboard, so we’ll need to create a new account on razorpay.com. You’ll need an email and a mobile number to register on razorpay.com, if you’ve not, otherwise you can log in to your Razorpay account.

Select Settings -> API Keys -> To generate the key for the specified mode, use Generate Key.

The Key Id and Key Secret appear in a pop-out window; keep these since we will use them in our code.

Step 4: Let’s make two classes, one for creating orders and another for payment requests, so right-click on your Models Folder and then pick

“Add” -> “Class” -> “Save” Make “Order.cs”

using System.ComponentModel.DataAnnotations;

namespace RazorPayIntegration.Models
{
    public class RazorPayOrder
    {
        public string OrderId { get; set; }
        public string RazorPayAPIKey { get; set; }
        public int Amount { get; set; }
        public string Currency { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }

    public class PaymentRequest
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string Email { get; set; }
        [Required]
        public int Amount { get; set; }
    }
}

We will acquire user information using the Class specified above.

Step 5: Navigate to HomeController.cs and paste the following code into it.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Razorpay.Api;
using RazorPayIntegration.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace RazorPayIntegration.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CreateOrder(PaymentRequest _requestData)
        {
            Random randomObj = new Random();
            string transactionId = randomObj.Next(10000000, 100000000).ToString();
            RazorpayClient client = new Razorpay.Api.RazorpayClient("rzp_test_izHk2Mfuy6rsMk", "Abh0Isk4SaE1nI3zlPwp9laz");
            Dictionary<string, object> options = new Dictionary<string, object>();
            options.Add("amount", _requestData.Amount * 100);  // Amount will in paise
            options.Add("receipt", transactionId);
            options.Add("currency", "INR");
            options.Add("payment_capture", "0"); // 1 - automatic  , 0 - manual
            Order orderResponse = client.Order.Create(options);
            string orderId = orderResponse["id"].ToString();
            RazorPayOrder orderModel = new RazorPayOrder
            {
                OrderId = orderResponse.Attributes["id"],
                RazorPayAPIKey = "rzp_test_izHk2Mfuy6rsMk",
                Amount = _requestData.Amount * 100,
                Currency = "INR",
                Name = _requestData.Name,
                Email = _requestData.Email,
            };
            return View("PaymentPage", orderModel);
        }

        [HttpPost]
        public ActionResult Complete()
        {
            string paymentId = HttpContext.Request.Form["rzp_paymentid"].ToString();
            string orderId = HttpContext.Request.Form["rzp_orderid"].ToString();
            RazorpayClient client = new Razorpay.Api.RazorpayClient("rzp_test_izHk2Mfuy6rsMk", "Abh0Isk4SaE1nI3zlPwp9laz");
            Payment payment = client.Payment.Fetch(paymentId);
            Dictionary<string, object> options = new Dictionary<string, object>();
            options.Add("amount", payment.Attributes["amount"]);
            Payment paymentCaptured = payment.Capture(options);
            string amt = paymentCaptured.Attributes["amount"];
            if (paymentCaptured.Attributes["status"] == "captured")
            {
                ViewBag.Message = "Paid successfully";
                ViewBag.OrderId = paymentCaptured.Attributes["id"];
                return View("Result");
            }
            else
            {
                ViewBag.Message = "Payment failed, something went wrong";
                return View("Result");
            }
        }
    }
}

Inside the CreateOrder ActionMethod, we take the payee’s (user’s) email, name, and amount to be paid; after we have that, the code will be redirected to the PaymentPage, which has the JS and Razor code seen below.

@model UPIIntegration.Models.RazorPayOrder

<button id="rzp-button1" hidden>Pay</button>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
var options = {
    "key": "@Html.DisplayFor(model => model.RazorPayAPIKey)", 
    "amount": "@Html.DisplayFor(model => model.Amount)",
    "currency": "@Html.DisplayFor(model => model.Currency)",
    "name": "@Html.DisplayFor(model => model.Name)",
    "description": "Sample description here",
    "order_id": "@Html.DisplayFor(model => model.OrderId)",
    "handler": function (response){
        document.getElementById('rzp_paymentid').value = response.razorpay_payment_id;
        document.getElementById('rzp_orderid').value = response.razorpay_order_id;
        document.getElementById('rzp-paymentresponse').click();
    },
    "prefill": {
        "name": "@Html.DisplayFor(model => model.Name)",
        "email": "@Html.DisplayFor(model => model.Email)",
        "contact": "9090974785" //pre-filled sample number
    },
    "notes": {
        "address": "You can add notes here"
    },
    "theme": {
        "color": "#F37254"
    }
};
var rzp1 = new Razorpay(options);

window.onload = function(){
    document.getElementById('rzp-button1').click();
};
document.getElementById('rzp-button1').onclick = function(e){
    rzp1.open();
    e.preventDefault();
}
</script>

@using (Html.BeginForm("Complete", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.Hidden("rzp_paymentid")
    @Html.Hidden("rzp_orderid")
    <button type="submit" id="rzp-paymentresponse" class="btn btn-primary" hidden>Submit</button>
}

In the above code, we are using JS to call the RazorPay client, which will open the RazorPay pop-up, where the user must provide Phone and UPI or Credit Card credentials for payment.

When payment is successfully completed, the JS handler is invoked.

"handler": function (response){
        // After payment successfully made response will come here and Set the data in hidden form
        document.getElementById('rzp_paymentid').value = response.razorpay_payment_id;
        document.getElementById('rzp_orderid').value = response.razorpay_order_id;
        document.getElementById('rzp-paymentresponse').click();
    },

This will open a hidden HTML Form and submit the data to the C# Controller ActionMethod “Complete,” where we will verify whether or not payment was successful.

We must now create additional Views, each

Index.cshtml

@model UPIIntegration.Models.PaymentRequest
@{
    ViewData["Title"] = "Home Page";
}

@using (Html.BeginForm("CreateOrder", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <div class="row">
        <label for="name">Customer Name</label>
        @Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
    </div>
    <div class="row">
        <label for="email">Email ID</label>
        @Html.TextBoxFor(x => x.Email, new { @class = "form-control" })
    </div>
    <div class="row">
        <label for="amount">Amount (INR)</label>
        @Html.TextBoxFor(x => x.Amount, new { @class = "form-control" })
    </div>
    <div class="row">
        <br/>
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
}

and another Result. cshtml in which we display the status and Order Id

@ViewBag.Message<br/>
Order Id: @ViewBag.OrderId

Run the project and make transaction using UPI; in this case, used the test UPI id success@razorpay.

That’s it; as you can check on your Razorpay Dashboard, the payment was made successfully.

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories