DEV Community

Cover image for Two-Day Razorpay Integration for Seamless Payments 🚀
Athreya aka Maneshwar
Athreya aka Maneshwar

Posted on • Edited on

Two-Day Razorpay Integration for Seamless Payments 🚀

Hello, I'm Maneshwar. I'm building git-lrc, an AI code reviewer that runs on every commit. It is free, unlimited, and source-available on Github. Star Us to help devs discover the project. Do give it a try and share your feedback for improving the product.

Integrating Razorpay into your application might sound intimidating, but guess what?

You can get it done in just two days! Razorpay's smooth workflow and intuitive APIs make payment integration a breeze.

In this blog, we’ll dive into how the integration works and the flow behind it. Let’s make your application payment-ready in no time. 💸

Why Razorpay? 🤔

Razorpay offers a robust, developer-friendly payment gateway that supports multiple payment methods, from UPI to net banking.

It’s perfect for modern applications that want to scale fast and offer a seamless user experience.

Installation 🛠️

Start by installing the Razorpay package in your backend:

npm install razorpay
Enter fullscreen mode Exit fullscreen mode

This package provides the tools needed to interact with Razorpay APIs.

The Flow 🌊

Here’s how it all works:

Step 1: Frontend Hits Backend for an Order API

Your frontend starts by making a call to your backend to create a new order.

Razorpay requires an order to be created before processing a payment.

Step 2: Backend Hits Razorpay’s Order API

The backend calls Razorpay’s Order API with the order details (amount, currency, etc.) and gets an order_id in response.

Here's a simple example of how you can set this up:

import Razorpay from 'razorpay';

export const razorPayInstance = new Razorpay({
  key_id: process.env.RAZOR_PAY_KEY_ID!,
  key_secret: process.env.RAZOR_PAY_KEY_SECRET!,
});

// Function to create an order
export const createOrder = async (orderData) => {
  try {
    const order = await razorPayInstance.orders.create(orderData);
    return order; // This contains the order ID
  } catch (error) {
    console.error('Error creating Razorpay order:', error);
    throw new Error('Failed to create order');
  }
};

// Function to verify a payment
export const verifyPayment = async (paymentId) => {
  try {
    const payment = await razorPayInstance.payments.fetch(paymentId);
    return payment;
  } catch (error) {
    console.error('Error verifying payment:', error);
    throw new Error('Failed to verify payment');
  }
};
Enter fullscreen mode Exit fullscreen mode

The backend returns the order_id to the frontend.

Step 3: Frontend Does the Checkout

Here’s where the magic happens! Razorpay provides a neat JavaScript library that handles the entire checkout flow.

Here’s a sample HTML code snippet for the frontend:

<button id="rzp-button1" class="btn btn-outline-dark btn-lg">
  <i class="fas fa-money-bill"></i> Own Checkout
</button>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
  var options = {
    key: 'rzp_test_asdfW2Nb', // Replace with your Key ID from Razorpay Dashboard
    order_id: 'order_Pmt1nNrwwjYttK', // Order ID from your backend
    currency: 'INR',
    description: 'Acme Corp',
    image: 'example.com/image/rzp.jpg',
    prefill: {
      email: 'gaurav.kumar@example.com',
      contact: 9620107401,
    },
    method: {
      upi: true,
      card: false,
      netbanking: false,
      wallet: false,
      emi: false,
    },
    handler: function (response) {
      alert('Payment ID: ' + response.razorpay_payment_id);
    },
    modal: {
      ondismiss: function () {
        if (confirm('Are you sure you want to close the form?')) {
          console.log('Checkout form closed by the user');
        } else {
          console.log('Complete the payment to proceed.');
        }
      },
    },
  };
  var rzp1 = new Razorpay(options);
  document.getElementById('rzp-button1').onclick = function (e) {
    rzp1.open();
    e.preventDefault();
  };
</script>
Enter fullscreen mode Exit fullscreen mode

When the user completes the payment, Razorpay’s checkout returns a payment_id to the frontend.

Step 5: Backend Verifies the Payment

The frontend sends the payment_id to the backend. The backend uses Razorpay’s Payment API to verify the payment details and ensure it was successful.

await razorPayInstance.payments.fetch(paymentId);
Enter fullscreen mode Exit fullscreen mode

What If the Payment ID Is Missing? 🤷‍♂️

Great question! Payments can fail, or the frontend might not send the payment_id.

Don’t worry; Razorpay’s got your back with webhooks.

Webhook Setup:

Razorpay can notify your backend directly about payment events (like successful payments).

Just configure a webhook in the Razorpay Dashboard, and your backend will always stay updated, ensuring reliability in any scenario.

Wrapping Up 🎁

Razorpay’s integration flow is simple yet powerful:

  1. Frontend requests an order.
  2. Backend creates the order with Razorpay.
  3. Frontend completes the payment using Razorpay’s checkout.
  4. Backend verifies the payment.

Bonus: Webhooks ensure you don’t miss any payment notifications!

With just two days of effort, you can integrate Razorpay and start accepting payments like a pro. Happy coding! 😊

What’s Next?

Start experimenting with Razorpay APIs today, and let me know if you have questions or hit any roadblocks.

LiveAPI helps you get all your backend APIs documented in a few minutes

With LiveAPI, you can quickly generate interactive API documentation that allows users to execute APIs directly from the browser.

Return only the cleaned text without any additional commentary:

git-lrc
*AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.*

Any feedback or contributors are welcome! It's online, source-available, and ready for anyone to use.

⭐ Star it on GitHub:

GitHub logo HexmosTech / git-lrc

Free, Unlimited AI Code Reviews That Run on Commit

git-lrc logo

git-lrc

Free, Unlimited AI Code Reviews That Run on Commit


git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.

See It In Action

See git-lrc catch serious security issues such as leaked credentials, expensive cloud operations, and sensitive material in log statements

git-lrc-intro-60s.mp4

Why

  • 🤖 AI agents silently break things. Code removed. Logic changed. Edge cases gone. You won't notice until production.
  • 🔍 Catch it before it ships. AI-powered inline comments show you exactly what changed and what looks wrong.
  • 🔁 Build a habit, ship better code. Regular review → fewer bugs → more robust code → better results in your team.
  • 🔗 Why git? Git is universal. Every editor, every IDE, every AI…




Top comments (0)