Ultimate Tutorial for Cashfree Payment Gateway Integration with Node.js and Angular

Ultimate Tutorial for Cashfree Payment Gateway Integration with Node.js and Angular

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.

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

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