Cashfree Web Integration Guide

✅ Simplified Checkout: Cashfree Checkout is a pre-built Checkout Page by Cashfree Payments to provide the most optimal payment experience. Accept payments from 120+ payment methods easily, and securely. Your customers are redirected to Cashfree Checkout to complete the Payment.

✅ Secure and PCI Compliant: Cashfree Checkout collects the data and submits to Cashfree servers securely, so, no PCI compliance requirements are required at your end.

✅ Personalised: Customise payment methods, branding, and much more to match the theme of your company.

Requirements

  • Create a Cashfree Merchant Account.
  • Log in to the Merchant Dashboard and generate test keys from Cashfree Dashboard.
  • Generate API Keys - Client ID & Secret Key.
  • Ensure you have whitelisted your website domain for integration. Read more about Domain Whitelisting.

Integration process consists of three essential steps: creating an order, opening the checkout page, and confirming the order. Below is a step-by-step guide for each part of the integration process.

Step 1: Creating an Order

To integrate the Cashfree Payment Gateway, the first step is to create an Order. This must be done before any payment processing can occur. Set up an endpoint on your server to handle order creation as you cannot call this api from client side.

API Request for Creating an Order

Here’s a sample request for creating an order using your desired backend language. Cashfree offers backend SDKs to simplify the integration process.

You can find the SDKs here.

import { Cashfree } from "cashfree-pg"; 

Cashfree.XClientId = {Client ID};
Cashfree.XClientSecret = {Client Secret Key};
Cashfree.XEnvironment = Cashfree.Environment.PRODUCTION;

function createOrder() {
  var request = {
    "order_amount": "1",
    "order_currency": "INR",
    "customer_details": {
      "customer_id": "node_sdk_test",
      "customer_name": "",
      "customer_email": "example@gmail.com",
      "customer_phone": "9999999999"
    },
    "order_meta": {
      "return_url": "https://test.cashfree.com/pgappsdemos/return.php?order_id=order_123"
    },
    "order_note": ""
  }

  Cashfree.PGCreateOrder("2023-08-01", request).then((response) => {
    var a = response.data;
    console.log(a)
  })
    .catch((error) => {
      console.error('Error setting up order request:', error.response.data);
    });
}

After successfully creating an order, you will receive a unique order_id and payment_session_id that you need for subsequent steps.

You can view all the complete api request and response for /orders here.

Step 2: Opening the Checkout Page

This step requires you to whitelist your domain with Cashfree. Read more here

1. Include JS SDK in your client code

To integrate the Cashfree Checkout, you must include our JavaScript SDK within your JS file.

<script src="https://sdk.cashfree.com/js/v3/cashfree.js"></script>

2. Initialize the SDK

You need to initialise the variable using the Cashfree() function.

There are two modes applicable for this - sandbox or production.

Sandbox is used for test environment, whereas production is used for production mode.

const cashfree = Cashfree({
    mode:"sandbox" //or production
});

3. Open Cashfree Checkout

To open the checkout, you can use cashfree.checkout() method. This method can take in following parameters -

  • paymentSessionId(required) - Received from Create Order Response
  • redirectTarget(optional) - This parameter decides how the payment page will open up. You can provide the following values:
  • Property ValueDescription
    _self(default)Opens the payment link in the same frame as it was clicked.
    _blankOpens the payment link in a new window or tab.
    _topOpens the linked document in the full body of the window.
    _modalOpens the payment link in a pop-up window on the current page.
    DOM elementOpens the payment link directly within a specified DOM element.

    Checkout Variants

  • Redirect Checkout - For redirectTarget _self, _blank, _top
  • Popup Checkout - For redirectTarget _modal
  • Inline Checkout - For redirectTarget DOM element
  • Note: For Popup & Inline Checkout the usage differs slightly as you should handle the promise returned by cashfree.checkout() to execute additional code after the payment attempt

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Cashfree Checkout Integration</title>
            <script src="https://sdk.cashfree.com/js/v3/cashfree.js"></script>
        </head>
        <body>
            <div class="row">
                <p>Click below to open the checkout page in current tab</p>
                <button id="renderBtn">Pay Now</button>
            </div>
            <script>
                const cashfree = Cashfree({
                    mode: "production",
                });
                document.getElementById("renderBtn").addEventListener("click", () => {
                    let checkoutOptions = {
                        paymentSessionId: "your-payment-session-id",
                        redirectTarget: "_self",
                    };
                    cashfree.checkout(checkoutOptions);
                });
            </script>
        </body>
    </html>
    

    Step 3: Confirming the Payment

    Once the payment is completed, you need to confirm whether the payment was successful by checking the order status.

  • Redirect Checkout
  • Once the payment process finishes, the user will be redirected to the return URL you provided during order creation (Step 1). If no return URL is provided, customers will be redirected to a Cashfree’s default page.

    We recommend you to provide a return URL while creating an order. This will improve the overall user experience by ensuring your customers don’t land on broken or duplicated pages. Also, remember to add context of the order in your return url so that you can identify the order once customer has returned on this url.

  • Popup & Inline Checkout
  • Once the payment process finishes, cashfree.checkout() function returns a promise which should be handled by the merchant

    Order Status - Verification

    To verify an order you can call our /pg/orders endpoint from your backend. You can also use our SDK to achieve the same.

    version := "2023-08-01"
    response, httpResponse, err := cashfree.PGFetchOrder(&version, "<order_id>", nil, nil, nil)
    if err != nil {
    	fmt.Println(err.Error())
    } else {
    	fmt.Println(httpResponse.StatusCode)
    	fmt.Println(response)
    }
    

    Note: Prior to delivering your services to customers, it is crucial to verify the status of your order. Order should be verified using the Get Order API. When the order_status is PAID you can consider that payment was successful.

    Testing

    You should now have a working checkout button that opens Cashfree hosted payment page. If your integration isn’t working:

    1. Open the Network tab in your browser’s developer tools.
    2. Click the button and check the console logs.
    3. Ensure correct environment and payment session id is being passed.
    4. Use console.log() inside your button click listener to confirm whether the data is being passed correctly or not.