DEV Community

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

Posted on

Two-Day Razorpay Integration for Seamless Payments 🚀

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! 😊

Image description

What’s Next?

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

I’ve been working on a super-convenient tool called LiveAPI.

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.

Image description

If you’re tired of manually creating docs for your APIs, this tool might just make your life easier.

Top comments (0)