ASP.NET MVC

How To Integrate Razorpay Standard Checkout In Asp.Net MVC

In this blog, we are integrating with Razorpay Standard Checkout in Asp.Net MVC.

integrating Razorpay Standard Checkout on our website will allow us to accept online payments from customers. Razorpay supports different payment methods such as net banking, credit and debit cards, wallets, and UPI.

Razorpay’s checkout.js library provides us all the essential features for integrating Razorpay Checkout with the client-side of our application.

Different methods of Standard Checkout are available with Razorpay.

  1. Automatic Checkout
  2. Manual Checkout

here we are using the Automatic Checkout method.

But first, if you don’t know How To Integrate Razorpay In Asp.Net MVC then click here.

In our .Net Application, I am using its NuGet Package named Razorpay.

for checkout First, we need to Create Order with proper details at server side(in the controller)

Now, create the Checkout Method and add the following code into the Checkout Method.

[HttpGet]
       public ActionResult Checkout()
       {
           try
           {
               var Amount = 3000;
               Dictionary<string, object> options = new Dictionary<string, object>();
               options.Add("amount", Amount); // amount in the smallest currency unit
               options.Add("receipt", "Order_rcptid_1234");
               options.Add("currency", "INR");
               options.Add("payment_capture", "0");
               Order order = client.Order.Create(options);

               ViewBag.orderid = Convert.ToString(order["id"]);
               ViewBag.Amount = Amount;
           }
           catch (Razorpay.Api.Errors.BadRequestError ex)
           {

           }
           catch (SignatureVerificationError ex)
           {
           }
           catch (Exception ex)
           {
           }

           return View();
       }

above code will create order in Razorpay. the amount and currency attributes are mandatory. in the receipt you can pass Your receipt id for this order of Maximum length 40 characters. in payment_capture if you pass 1 then it will automatically capture the payment. if you pass 0 then it will capture payments manually using the API or Dashboard. for more details about its attribute please click here.

after successfully creating order, we need to pass an order Id to view. I used ViewBag for passing OrderId and Amount.

Now, create the Checkout.cshtml View and add the following code into it.

@{
    ViewBag.Title = "Checkout";
}

<div class="jumbotron">
    <p class="lead">Check Out</p>

    <form action="@Url.Action("CheckoutPost","Home")" method="POST">

        <script src="https://checkout.razorpay.com/v1/checkout.js"
                data-key="rzp_test_ugqAEIZQWdxOgE"
                data-amount="@ViewBag.Amount"
                data-currency="INR"
                data-order_id="@ViewBag.orderid"
                data-buttontext="Pay with Razorpay"
                data-name="Tabish Company"
                data-description="Test transaction"
                data-image="http://localhost:58542/Content/12.jpg"
                data-prefill.name="tabish"
                data-prefill.email="Your Email Address"
                data-prefill.contact="Your Contact Number"
                data-theme.color="#F37254"></script>
        <input type="hidden" custom="Hidden Element" name="hidden">
    </form>

</div>

in the above code, we are using Checkout script. as you can see we are using ViewBag for giving OrderId and amount for giving data into the script attribute. we can use data attributes in our HTML code according to our needs.

a Detailed list of Checkout form options is available here.

after successful payment on the Checkout, the form will be redirected to the link which we gave in form action attributes.

For every successful payment, razorpay_payment_id, razorpay_order_id, and razorpay_signature are submitted along with the form to the action URL.

Now, create the CheckoutPost Method and add the following code into the CheckoutPost Method. this is a post method which we gave in form action URL. so, after successful payment, this method will be called.

[HttpPost]
      public ActionResult CheckoutPost(string razorpay_order_id, string razorpay_payment_id, string razorpay_signature)
      {
          bool IsValidRequest = true;
          bool IsPaymentSuccess = false;
          bool IsPaymentCapturedSuccess = false;

          try
          {
              if (!string.IsNullOrEmpty(razorpay_order_id) && !string.IsNullOrEmpty(razorpay_payment_id) && !string.IsNullOrEmpty(razorpay_signature))
              {

                  var payload = razorpay_order_id + '|' + razorpay_payment_id;

                  Utils.verifyWebhookSignature(payload, razorpay_signature, "YOUR-API-SECRET-KEY");

                  //You can write your business logic here
                  IsPaymentSuccess = true;

                  var Amount = 3000;
                  Payment payment = client.Payment.Fetch(razorpay_payment_id);
                  Dictionary<string, object> options = new Dictionary<string, object>();
                  options.Add("amount", Amount);
                  options.Add("currency", "INR");
                  Payment paymentCaptured = payment.Capture(options);

                  var PaymentId = Convert.ToString(paymentCaptured["id"]);
                  if (!String.IsNullOrEmpty(PaymentId))
                  {
                      IsPaymentCapturedSuccess = true;
                  }
              }
              else
              {
                  IsValidRequest = false;
              }



          }
          catch (Razorpay.Api.Errors.BadRequestError ex)
          {

          }
          catch (SignatureVerificationError ex)
          {
              IsValidRequest = false;
          }
          catch (Exception ex)
          {
          }

          ViewBag.IsValidRequest = IsValidRequest;
          ViewBag.IsPaymentSuccess = IsPaymentSuccess;
          ViewBag.IsPaymentCapturedSuccess = IsPaymentCapturedSuccess;
          return View();

      }

After successful completion of the payment customer will be redirected to the CheckoutPost method above, with parameters.

as you can see, we are verifying that the request is valid or not. for that, we are checking/Verifying Signature.

we verify the razorpay_signature parameter to validate that it is authentic and sent from Razorpay servers so if any someone tries to modify the request or do invalid requests then we can verify it.

Razorpay server is returning razorpay_signature in a parameter. we need to check it against our response.

For verifying the signature, we need to create/Generate a signature using razorpay_invoice_id, razorpay_invoice_receipt, razorpay_invoice_status, and razorpay_payment_id​ as payload and your key_secret​ (your API secret) as secret.

here we are connecting it all in the payload variable.

And we are using Utils.verifyWebhookSignature() method for verify it. in Utils.verifyWebhookSignature() method we need to pass payloadexpectedSignature (razorpay_signature which we get from Razorpay server), secret (your API secret).

if the signature is Invalid then it will throw Exception and go in SignatureVerificationError Exception block. if the signature is valid then it will execute the next line.

so this way you can verify the valid request, and you can write your business logic after Utils.verifyWebhookSignature() method.

so after verifying the request, we are capturing payment done by customers on checkout.

Once the payment is authorized by the customer’s bank, we must verify if the authorized amount deducted from the customer’s account is the same as the amount paid by the customer on our website.

for changing the status of the payment from authorized to captured. we need to send a capture request. you can learn more detail about it by clicking here.

for capturing payment we need razorpay_payment_id, Amount, and Currency. razorpay_payment_id is the payment id which user pay on checkout. The Amount should be the same as the authorized amount(checkout amount). Currency is an ISO code of the currency in which the payment was made.

Now, create the CheckoutPost.cshtml View and add the following code into it.

@{
    ViewBag.Title = "CheckoutPost";
}

<div class="jumbotron">

    @if (ViewBag.IsValidRequest == false)
    {
        <p class="lead"><label class="label-danger">Invalid Request.!</label></p>
    }
    else
    {
        if (ViewBag.IsPaymentSuccess == true && ViewBag.IsPaymentCapturedSuccess == true)
        {
            <p class="lead"><label class="label-success">Payment Captured successfully.!</label></p>
        }
        else if (ViewBag.IsPaymentSuccess == true)
        {
            <p class="lead"><label class="label-warning">Payment done successfully.!</label></p>
        }
    }

</div>

 

The following are outputs of the above codes.

Checkout.cshtml

Checkout.cshtml (on click Pay with Razorpay)

Checkout.cshtml (on Razorpay checkout payment)

CheckoutPost.cshtml

Razorpay Dashboard for Order

Razorpay Dashboard for Payment

 

Tabish Rangrej

Tabish Rangrej is an Experienced .NET Team Leader, software engineer, and Author with a demonstrated history of working in the IT industry. He has quite well experience in developing, communicating, managing, and writing in his field. He has strong skills and knowledge of ASP.NET C#, ASP.NET MVC, ASP.NET CORE, Angular, AngularJS, Web API, SQL, Entity Framework, JavaScript, Jquery, Different Integrations like Quickbooks, Stripe, Google APIs, Zoho, Orion, Xero, etc., Different versioning tools like TFS, SVN, GIT, etc. and Windows services. Strong engineering professional with a Master of Computer Applications - MCA focused on Computer Science from Veer Narmad South Gujarat University, Surat. Tabish is always ready to accept new challenges and learn new things, he would like to serve better for the community.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago