Last updated Nov 5, 2024

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

Seamlessly integrate Razorpay with Angular & Node.js.

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:

<script src="https://checkout.razorpay.com/v1/checkout.js" async defer></script>
Buy Button in Angular

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

<a href="javascript:void();" (click)="buywithRazorpay(product)">
  Buy with Razorpay
</a>

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

Tags

Available for projectsLet’s build together

Need this built properly,
not just explained?

I take on Angular and NestJS work directly — auth systems, multi-tenant SaaS, API rewrites and the deploy pipeline underneath them. You talk to the person writing the code.

Projects delivered
20+ Projects delivered
Angular • NestJS
7+ years Angular • NestJS
Average reply time
1 day Average reply time

What I can help with

  • Auth and permissions systems
  • Multi-tenant SaaS foundations
  • API design and rewrites
  • Deploy pipelines and VPS setup
  • Bug fixing and performance optimization
Send me a message

Tell me about your project and I’ll get back with a realistic scope and price.

Turn
Your Ideas
Into Reality

Stay in the loop

Get the finished tutorials, projects and resources in your inbox.

Join 5,000+ developers and get new tutorials, source code, product updates and exclusive content — straight to your inbox.

  • No spam
  • Useful content only
  • Unsubscribe anytime

Subscribe to TutsCoder

Be the first to get new tutorials, projects and tips.

Join 5,000+ developers already learning with us.

Learn
Build
Grow

Discussion

0 comments

Share your thoughts, ask questions or suggest improvements. Let’s learn and grow together!

No comments yet — be the first to start the discussion.

Join the discussion

Sign in to join the discussion. Your account also keeps your saved tutorials and path progress.