Razorpay Payment Gateway Integration with Angular and Node.js: A Complete Tutorial

Razorpay Payment Gateway Integration with Angular and Node.js: A Complete Tutorial

Integrating a payment gateway into your web application is essential for providing a seamless payment experience to your users. In this tutorial, we will walk through the process of integrating the Razorpay Payment Gateway with Angular and Node.js, allowing you to accept payments securely and efficiently.

What is Razorpay?

Razorpay is one of the most popular payment gateways in India, offering businesses and developers a simple and secure way to accept payments online. Its easy integration with platforms like Angular and Node.js makes it a preferred choice for modern web applications.

πŸ’‘ Want to speed up your integration process? Check out my ready-to-use Razorpay Payment Gateway Integration script for Node.js! This script comes with all the essential features, saving you hours of setup time. Perfect for developers who want to get up and running quickly!

Why Use Razorpay with Angular and Node.js?

Integrating Razorpay with Node.js and Angular allows you to manage payments on the backend with Node.js while offering users a smooth experience on the Angular frontend. Using Razorpay ensures secure transactions, quick setup, and support for various payment methods like credit/debit cards, UPI, and net banking.

Step 1: Setting Up Razorpay in Node.js

First, install the Razorpay package in your Node.js application:

npm install razorpay

Then, require Razorpay and create an instance with your API credentials:

const Razorpay = require('razorpay');

const instance = new Razorpay({
  key_id: process.env.RAZORPAY_KEY_ID,
  key_secret: process.env.RAZORPAY_KEY_SECRET,
});

Step 2: Creating a Razorpay Order in Node.js

You need to create a new order on the backend before initiating a payment. Below is the code to create a Razorpay order:

exports.createRazorpayOrder = async (req, res) => {
  try {
    const { amount, currency, receipt } = req.body;
    const options = {
      amount: amount * 100, // amount in smallest currency unit
      currency: currency || "INR",
      receipt: receipt || `order_rcptid_${Date.now()}`
    };
    const order = await instance.orders.create(options);
    res.status(200).json({ success: true, order });
  } catch (err) {
    res.status(500).json({ success: false, error: "Order creation failed" });
  }
}
Node.js API Routes for Razorpay:
router.post("/razorypay/create-order", createRazorpayOrder);

Step 3: Verifying Razorpay Payments in Node.js

After the payment is processed on the frontend, Razorpay sends a response that must be verified to ensure that the payment is valid.

exports.verifyPayment = async (req, res) => {
  const { razorpay_order_id, razorpay_payment_id, razorpay_signature } = req.body;
  const secret = process.env.RAZORPAY_KEY_SECRET;

  const hmac = crypto.createHmac('sha256', secret);
  hmac.update(razorpay_order_id + "|" + razorpay_payment_id);
  const generated_signature = hmac.digest('hex');

  if (generated_signature === razorpay_signature) {
    res.status(200).json({ success: true, message: "Payment verified successfully" });
  } else {
    res.status(400).json({ success: false, error: "Invalid payment signature" });
  }
};
Node.js API Route for Verifying Payments:
router.post("/razorypay/verify-payment", verifyPayment);

Step 4: Razorpay Integration in Angular Frontend

In the Angular frontend, you'll trigger the Razorpay payment popup when the user clicks a "Buy" button.

Razorpay Checkout Script

Add the Razorpay checkout script to your Angular component:

Buy Button in Angular

Use a button in your template that calls the payment method when clicked:


  Buy with Razorpay

Angular Payment Method

In your Angular component, handle the payment by calling the backend to create an order and then invoking Razorpay's checkout popup:

buywithRazorpay(product: any) {
  const price = product.price * 100;
  const receiptId = `order_rcptid_${Date.now()}`;

  this.paymentGetwaysService.createOrder(price, 'INR', receiptId).subscribe((response: any) => {
    if (response.success) {
      const orderId = response.order.id;
      this.payWithRazor(orderId, price);
    }
  });
}

payWithRazor(orderId: string, amount: number) {
  const options: any = {
    key: 'your_razorpay_key_id',
    amount: amount.toString(),
    currency: 'INR',
    name: 'Your Business',
    description: 'Payment for your order',
    order_id: orderId,
    callback_url: 'http://localhost:4200/payment-success',
    prefill: { name: 'Your Name', email: 'your.email@example.com', contact: '9999999999' },
    theme: { color: '#F37254' },
    handler: (response: any) => { this.verifyPayment(response); },
    modal: { ondismiss: () => { console.log('Transaction cancelled.'); } }
  };
  const rzp = new this.winRef.nativeWindow.Razorpay(options);
  rzp.open();
}

Step 5: Payment Verification on Angular

After the payment is processed, you'll verify the payment by calling the backend API:

verifyPayment(paymentDetails: any) {
  this.paymentGetwaysService.verifyPayment(paymentDetails).subscribe((response: any) => {
    if (response.success) {
      console.log('Payment verified successfully');
    } else {
      console.error('Payment verification failed');
    }
  });
}
Conclusion

By following this tutorial, you now have a complete integration of Razorpay Payment Gateway with Angular and Node.js. This setup allows users to make secure payments while ensuring that the payments are verified and the transaction data is stored properly.

Integrating payment gateways like Razorpay with Angular and Node.js provides an efficient and scalable solution for online businesses.

πŸ“– Enjoyed this article? Let’s work together! I’m open to freelance projects on Upwork and Fiverr. Drop by and say hi!πŸ‘‹  

Subscribe to our Newsletter

Stay up to date! Get all the latest posts delivered straight to your inbox.

If You Appreciate What We Do Here On TutsCoder, You Should Consider:

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Support Us

We are thankful for your never ending support.

Leave a Comment