Last updated Oct 3, 2024

Cashfree Payment Gateway Integration with Node.js & Angular (Complete Guide)

Integrate Cashfree in Node.js and Angular apps. Follow this guide to set up secure payments, APIs, and handle transactions efficiently.

Cashfree Payment Gateway Integration with Node.js & Angular (Complete Guide)

Integrating a payment gateway is essential for any eCommerce application, and Cashfree offers a reliable, fast, and secure payment solution.

In this comprehensive guide, we’ll walk you through the steps to integrate Cashfree Payment Gateway into a Node.js and Angular application.

Why Choose Cashfree for Payment Integration?

Cashfree offers a wide variety of payment options, making it easy for businesses to receive payments through UPI, cards, and net banking. Their easy API integration, high success rate, and competitive pricing make it a preferred choice for developers.https://www.tutscoder.com/blog/angular/angular-installation

Prerequisites

Before starting, make sure you have the following:

  1. A Node.js application set up. If not, you can follow Node.js Official Guide to get started.
  2. An Angular application for the frontend. If you need to set up an Angular project, check out the Angular Quickstart Guide.
  3. Cashfree Sandbox Credentials: Register at Cashfree to get your API credentials.

Step 1: Setting Up Cashfree in Node.js

First, install the Cashfree Node.js SDK by running:

npm install cashfree-pg

Import and Configure Cashfree in Your Backend

In your Node.js application, import the Cashfree package and configure your API credentials.

const { Cashfree } = require('cashfree-pg');

Cashfree.XClientId = process.env.CASHFREE_CLIENT_ID;
Cashfree.XClientSecret = process.env.CASHFREE_CLIENT_SECRET;
Cashfree.XEnvironment = Cashfree.Environment.SANDBOX;

This setup configures Cashfree in sandbox mode for testing. Remember to switch to production when deploying live.

Step 2: Creating an Order in Node.js

Next, create a function that handles creating a Cashfree order:

var request = {
    "order_amount": 1.00,
    "order_currency": "INR",
    "order_id": "devstudio_34987817",
    "customer_details": {
        "customer_id": "devstudio_user",
        "customer_phone": "8474090589",
        "customer_name": "Harshith",
        "customer_email": "test@cashfree.com"
    },
    "order_meta": {
        "return_url": "https://www.cashfree.com/devstudio/preview/pg/web/checkout?order_id={order_id}"
    },
    "order_note": "Sample Order Note"
};

Cashfree.PGCreateOrder("2023-08-01", request)
    .then(response => {
        console.log('Order created successfully:', response.data);
    })
    .catch(error => {
        console.error('Error:', error.response.data.message);
    });

This code sends a request to Cashfree’s API to create an order, passing the necessary details like the customer info and order amount.

Step 3: Verifying Payment in Node.js

Once a payment is completed, you’ll want to verify its status. Here’s how you can verify the payment in Node.js:

exports.verifyCashfreePayment = async (req, res) => {
  try {
    const { cashFreeOrderid } = req.body;

    const response = await Cashfree.PGOrderFetchPayments("2023-08-01", cashFreeOrderid);
    const paymentStatus = response.data;

    if (paymentStatus.filter(transaction => transaction.payment_status === "SUCCESS").length > 0) {
      orderStatus = "Success";
    } else if (paymentStatus.filter(transaction => transaction.payment_status === "PENDING").length > 0) {
      orderStatus = "Pending";
    } else {
      orderStatus = "Failure";
    }

    if (orderStatus === 'Success') {
      res.json({ success: true, message: 'Payment successful', data: paymentStatus });
    } else {
      res.json({ success: false, message: 'Payment failed or still processing', data: paymentStatus });
    }
  } catch (error) {
    console.error('Error verifying payment:', error);
    res.status(500).json({ success: false, message: 'Server error', error: error.message });
  }
};

This function checks if the payment was successful, pending, or failed and returns the appropriate status.

Step 4: Setting Up Payment Routes

Now, set up your API routes to create orders and verify payments:

router.post("/cashfree/create-order", createCashfreeOrder);
router.post("/cashfree/verify-payment", verifyCashfreePayment);

These routes allow your frontend to communicate with the backend for creating orders and verifying payments.

Step 5: Integrating Cashfree Payment in Angular

Install Cashfree JS Library

In your Angular app, install the Cashfree JavaScript library:

npm i @cashfreepayments/cashfree-js

Setting Up Cashfree Payment on Frontend

Here’s how you can trigger the Cashfree payment popup in your Angular component:

//@ts-ignore
import { load } from '@cashfreepayments/cashfree-js';

buywithCashfree(product: any) {
    const price = 1;
    const reqData = {
        "order_amount": price,
        "customer_details": {
            "customer_id": this.userDetails.name,
            "customer_name": this.userDetails.name,
            "customer_email": this.userDetails.email,
            "customer_phone": "9999999999"
        },
        "order_meta": {
            "return_url": "http://localhost:4200/payment-status?order_id={order_id}"
        },
        "order_note": "This is a test order"        
    };

    this.paymentGetwaysService.createCashFreeOrder(reqData).subscribe((response: any) => {
        this.paywithCashFree(response.paymentSessionId);
    });
}

This function triggers the order creation, then processes the payment through the Cashfree payment gateway.

Initialize the Cashfree SDK

cashfree: any;

async initializeSDK() {
    this.cashfree = await load({
        mode: "sandbox"
    });
}

async paywithCashFree(paymentSessionId: any) {
    await this.initializeSDK();
    let checkoutOptions = {
        paymentSessionId: paymentSessionId,
        redirectTarget: "_self",
    };
    this.cashfree.checkout(checkoutOptions);
}

Here, the Cashfree SDK is initialized, and the payment session is passed for checkout.

Step 6: Testing Payment Flow

Once everything is set up, you can test the payment flow using Cashfree’s sandbox mode. Ensure you switch to production when going live.

Conclusion

By following this guide, you can successfully integrate Cashfree’s payment gateway into your Node.js and Angular application, providing a seamless checkout experience for your users. For more detailed information, you can refer to Cashfree API Docs to explore additional functionalities.

Useful Resources

Cashfree Developers Documentation

Data to Test Integration

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.