Right Click Is Disabled...

Payment Gateway Integration With RazorPay In.Net Core

In this article we are discussing What is Razorpay, how to setup razorpay account and implement in Asp.net Core

What we will learn

  • What is Razorpay Payment Gateway?
  • Creating Razorpay Payment Gateway Account Setup
  • Integrate Razorpay Payment Gateway in ASP.NET Core

What is Razorpay Payment Gateway?

A payment gateway is an online service that authorizes and processes payments for online businesses. It is the connection between the customer and the merchant. Razorpay’s platform is designed to facilitate smooth and secure transactions, with features like easy integration, robust security measures, detailed analytics, and customizable checkout options. Some popular payments Gateway are below

  • PayPal
  • Stripe
  • Authorize.net
  • Amazon Payments
  • 2Checkout

Here, Razorpay Payment Gateway enables to accept payments via debit card, credit card, net banking, UPI, and popular supported wallets.

Creating Razorpay Payment Gateway Account Setup

  • Let’s sign up using this razor pay site https://razorpay.com/. you’ll need to some basic information about you business. we can sign up using a mobile number
  • After sign up it asks for the “business type” along with your name filling details and submit
  • Log into the Razorpay Dashboard After that move to the Settings then API key tab and generate a key for the selected mode

The razor pay payment gateway provides two modes Live and test mode. If we are beginner then start with test mode and test transactions without processing real payment. We can here use test cards, bank accounts and other payment methods which is provide by razorpay. Live mode If you are satisfied with your integration and testing in sandbox environment, you can switch test mode to live mode

Click on the Regenerate test key to open below pop up with razor pay key id and key secret and we can use this key id and key secret in our application. Remember this key id and the key secret is only for testing purposes and not will be used in the live application.

Integrate Razorpay Payment Gateway in ASP.NET Core

1.1  First Create ASP.NET Core MVC Project After that we need to Install the Razorpay package in NuGet using following command

Install-Package Razorpay -Version {version_number}

1.2  After installation we can use the Razorpay attribute in the asp.net core. So first I have created a payment button so that clicking on this button shows payment windows. Here we have used the below source code in payment.aspx.cs file to open payment windows.

# HTML Code

<div>
    <link rel ="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <button type ="button" runat="server" class="btn btn-primary" onServerClick="btnProceedToPay_Click" >
        Proceed To Pay
    </button>
</div>

1.3 Clicking on the button that calls btnProceedToPay_Click method. In this method first, create an order, and after that call the openPaymentwindow function in jquery. So in jquery, we can handle payment status.

C# – Button Click Event Call

protected void btnProceedToPay_Click(object sender, EventArgs e)
{
    decimal amountinSubunits = Convert.ToDecimal(TotalAmount) * 100;
    string name = "Google";
    string currency = "INR";
    string description = "Razorpay Payment Gateway";
    string imageLogo = "https://www.google.co.in/google.png";
    string profileMobile = "9187874598";
    string profileEmail = "test@gmail.com";
    Dictionary<string, string> notes = new Dictionary<string, string>()
    {
        { "note 1", "this is a payment note" },
        { "note 2", "here another note, you can add max 15 notes" }
    };
    string orderId = CreateOrder(amountinSubunits, currency, notes);
    string jsFunction = "OpenPaymentWindow('" + _key + "', '" + amountinSubunits + "', '" + currency + "', '" + 
                        name + "', '" + description + "', '" + imageLogo + "', '" + orderId + "', '" + 
                        profileName + "', '" + profileEmail + "', '" + profileMobile + "', '" + 
                        JsonConvert.SerializeObject(notes) + "'"); ";
    ClientScript.RegisterStartupScript(this.GetType(), "OpenPaymentWindow", jsFunction, true);
}

We can customize the below Details in the Payment windows.

  1. Title: Name of company, it will be shown on UI modal
  2. Description: Just a simple description of the purchase, it will also be shown in the modal. 
  3. Currency: Currency string of three characters
  4. ImageLogo: Link of Logo, must be min dimension 256×256 & max size 1MB, of Company to be shown on modal, in our example case we are using a google logo.
  5. ProfileMobile: prefilled mobile number
  6. ProfileEmail: prefilled email

In the below code, we have used razorpay_key and razorpay_secret. Which is getting in the web config file. Whenever went with payment first order is created and after that payment is completed using orderID.

C# – Create Order Function Call

private string CreateOrder(decimal amountInSubunits, Dictionary<string, string> notes,)
{
    try
    {
        int paymentCapture = 1;
        string _key = ConfigurationManager.AppSettings["razorpay_key"];
        string _secret = ConfigurationManager.AppSettings["razorpay_secret"];
        RazorpayClient client = new RazorpayClient(_key, _secret);
        Dictionary<string, object> options = new Dictionary<string, object>();
        options.Add("amount", amountInSubunits);
        options.Add("payment_capture", paymentCapture);
        options.Add("notes", notes);
        ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00);
        ServicePointManager.Expect100Continue = false;
        Order orderResponse = client.Order.Create(options);
        var orderId = orderResponse.Attributes["id"].ToString();
        string SQL = //INSERTION QUERY;
        cmd = new SqlCommand(SQL, con);
        con.Open();
        cmd.ExecuteNonQuery();
        return orderId;
    }
    catch (Exception ex)
    {
        throw;
    }
}

1.4 So now here we have calling jquery function to handle payment status. If any issues arrived during the payment transaction then we can handle using payment.failed method.

# jQuery – Send Pay Request


<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script type="text/javascript">
function OpenPaymentWindow(key, amountInSubunits, currency, name, descritpion, imageLogo, orderId, profileName, profileEmail, profileMobile, notes) 
{
    notes = $.parseJSON(notes);
    var options = {
        "key": key, // Enter the Key ID generated from the Dashboard
        "amount": amountInSubunits, // Amount is in currency subunits. Default     
        "currency": currency, //currency is INR. Hence, 50000 refers to 50000 paise
        "name": name,
        "description": descritpion,
        "image": imageLogo,
        "order_id": orderId, //This is a sample Order ID. Pass the `id` obtained
                                      // in the response of Step 1
        "handler": function (response) {
        $.ajax({
            type: "POST",
            url: "frmExpiredVehicle.aspx/CreateOnlinePayment",

            // stored in  database using this method
            data: "{ TotalAmount:" + TotalAmount + ",'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var pID = response.d;   //successfully transaction
            },
            error: function (err) {
                alert(err);
            }
        });
    },
    "prefill": {
        "name": profileName,
        "email": profileEmail,
        "contact": profileMobile
    },
    "notes": notes,
    "theme": {
        "color": "#F37254"
    }
};
var rzp1 = new Razorpay(options);
    rzp1.open();
    rzp1.on('payment.failed', function (response) {
        alert("Oops, something went wrong and payment failed. Please try again later");
    });
}
</script>

Explanation of the above output:

  1. The user clicks on the button associated with the payment.
  2. A Modal open, which is provided by Razorpay opens in the middle of the window, Here the company name, the description, and the logo we have set before sending the request have been rendered here, also the contact number and email are prefilled.
  3. Even if we have prefilled some details Like mobileno and email also then we have access to change them during the proceeding to payment.
  4. After then, we can proceed to payment, let’s say we have chosen the card method, Here we have entered a test card detail “Card Number 4111 1111 1111 1111” expiry date can be any future month/year, CVV can be any three-digit number, also the name of the cardholder is prefilled here, but you can edit it before proceeding After that asking pin number you can enter any four digits and proceed.
  5. Then Immediately, Razorpay will process the payment.
  6. After completion once again Razorpay asks for your permission whether to do payment or not, click on success for proceeding with payment or click on failure to deny.

If payment is successfully done then we have received the below alert messages.

If payment failed then we received this message. It is always not possible to payment is successfully done. Sometimes we have facing issues like network issues, System down, incorrect OTP, and more.

Share On

Leave a Comment

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