Drop Javascript SDK

The Drop javascript SDK uses pre-built UI components to help you accept payments on your website or app.

Cashfree Drop SDK

Drop is our pre-built UI solution for accepting payments. Drop works by displaying payment components we call as drops at any place you want in your page. It can either display all the payment components at one place or different places depending on your need. Currently Drop supports the following payment components

  • Card
  • UPI (collect, intent, qrcode)
  • Wallets
  • Netbanking

Features

The Drop SDK supports the following features-

  • No Redirection
  • Highly Customizable
  • Pure Javascript
  • Automatic theme detection
  • No PCI certification required

How it works

From an implementation perspective, a Drop integration contains the following components.

  • Server side:
    • API call which creates the order_token
    • API call to check the status of a payment
    • Receive webhook events
  • Client side
    • JS code that uses order_token to render and initiate a payment

The payment flow is listed below.

  1. Shopper goes to checkout page
  2. Your server makes an API call to create an order with Cashfree to get the order_token
  3. Your server shares the order_token to your website
  4. Your website initializes Drop SDK
  5. Drop shows the available payment methods, makes the payment request, handles additional actions.
  6. On payment completion Drop sends callback, use the callback data to verify payment status from your backend
  7. Additionally you can use webhook to verify the payment status
  8. Show thank you page to shopper

Demo

Here is a codepen demo. You can play around with the different options. The demo uses an order_token, which can be easily generated using Create Order API.

Before you begin

Before you begin please make sure

  • You have Cashfree's Test Account created
  • Your client-id and client-secret obtained from the dashboard
  • You have a backend server

Step 1 (Create order)

As a first step you need to create an order with Cashfree from your backend server. Once you have created an order, you will receive an order_token in the API response. This order_token shall be used in the Drop JS sdk. View details to Create Order.

Step 2 (Drop SDK)

Include our Drop sdk in your client code

Current stable version is 1.0.26

<script src="https://sdk.cashfree.com/js/ui/1.0.26/dropinClient.sandbox.js"></script>

Drop Configuration Object

The configuration object will help you build a custom flow. For instance if you only need to display a card element, you can specify that in the components array. The details about each of these parameters is listed below.

const dropConfig = {
    "components": [
        "order-details",
        "card",
        "netbanking",
        "app",
        "upi"
    ],
    "orderToken": "your-order-token",
    "onSuccess": function(data) {
        //on payment flow complete
    },
    "onFailure": function(data) {
        //on failure during payment initiation
    },
    "style": {
        //to be replaced by the desired values
        "backgroundColor": "#ffffff",
        "color": "#11385b",
        "fontFamily": "Lato",
        "fontSize": "14px",
        "errorColor": "#ff0000",
        "theme": "light", //(or dark)
    }
}

The following objects can be part of the drop configuration. This configuration will get passed to the Drop SDK.

Parameter NameRequiredDescription
componentsAn array that takes in the components to be rendered. Available: order-details card netbanking app upi-collect upi-intent upi-qrcode
orderTokenOrder token returned by Cashfree
onSuccessCallback function triggered when payment flow is completed
onFailure Callback function triggered whenever an error happens
style Custom styling for components. Available: backgroundColor color fontFamily fontSize errorColor theme

Components

Components represents specific blocks each used to display a specific part of the payment UI. You can think of components as pre-built react components which can be easily imported in your payment page. These components handle different workflows and their lifecycle is managed by the Drop library.

NameDescription
order-detailsUse this component to show order and customer details
cardUse this component to show card as a payment method
netbankingUse this component to Net Banking as a payment method
appUse this component to show wallets as a payment method
upi-collectUse this component to have your customers enter their UPI ID
upi-qrcodeUse this component to accept payments by QR code
upi-intentUse this component to show Top 4 PSP apps. GooglePay, Phonepe, Paytm, Bhim UPI. Only works on mobile devices

Style

You can style the components by providing some specific parameters as part of the style object.

NameDescription
backgroundColorCan be used to modify the background color of the drop. Default is #fafafa
colorCan be used to set theme color of the drop. Default is #6933D3
fontFamilyCan be used to set the font-family to match your website, Default is Lato
fontSizeCan be used to set the base font size. Default is 14px
errorColorCan be used to modify the color of error text. Default is #ff0000
themeCan be used to set dark or light theme. Default is light

Initiate Drop

You would be using initialiseDropin function to render the Drop. The function takes in two parameters

  1. First parameter is the HTML element where there drop will be rendered
  2. Second parameter is your drop config
const cashfree = new Cashfree();
const paymentElement = document.getElementById("payment-form");
cashfree.initialiseDropin(paymentElement, dropConfig);

Step 3 (Handle response)

Once you have presented the payment form to the customer they will be able to attempt a payment. After completion you might need to redirect the user to a thank-you page or an error page (in case of failures). To handle this workflow, Drop emits events which need to be handled by you.
You can provide two different event handlers onSuccess and onFailure to handle these two scenarios.

Handle onSuccess and onFailure

 onSuccess: (data) => {
      if (data.order && data.order.status == "PAID") {
            //order is paid
            //verify order status by making an API call to your server
            // using data.order.orderId
      } else {
          //order is still active and payment has failed
      }
    
},
onFailure: (data) => {                                                
      console.log(data.order.errorText)
}

Step 4 (Verify Payment)

As a final step you need to verify your order status with Cashfree from your backend server. You must first verify this order in your system and ensure that it is the correct order_id. Then you must make an API call to Cashfree's server to fetch the order status. Based on Cashfree's response, you can update your system and share the same information with your client code.
Use the following api to get the order status - https://docs.cashfree.com/reference/getorder

Complete Demo code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Cashfree Drops</title>
  </head>
  <body>
    <div id="payment-form"></div>
    <button id="pay-btn">Pay</button>
      
    <script src="https://sdk.cashfree.com/js/ui/1.0.20/dropinClient.sandbox.js"></script>
    <script src="main.js"></script>
  </body>
</html>
let orderToken = "your-token";
const cashfree = new Cashfree();
const paymentDom = document.getElementById("payment-form");
const success = function(data) {
    if (data.order && data.order.status == "PAID") {
        $.ajax({
            url: "checkstatus.php?order_id=" + data.order.orderId,
            success: function(result) {
                if (result.order_status == "PAID") {
                    alert("Order PAID");
                }
            },
        });
    } else {
        //order is still active
        alert("Order is ACTIVE")
    }
}
let failure = function(data) {
    alert(data.order.errorText)
}
document.getElementById("pay-btn").addEventListener("click", () => {
    const dropConfig = {
        "components": [
            "order-details",
            "card",
            "netbanking",
            "app",
            "upi"
        ],
        "orderToken": orderToken,
        "onSuccess": success,
        "onFailure": failure,
        "style": {
            "backgroundColor": "#ffffff",
            "color": "#11385b",
            "fontFamily": "Lato",
            "fontSize": "14px",
            "errorColor": "#ff0000",
            "theme": "light", //(or dark)
        }
    }
    if (order_token == "") {
        $.ajax({
            url: "fetchtoken.php",
            success: function(result) {
                order_token = result["order_token"];
                cashfree.initialiseDropin(paymentDom, dropConfig);
            },
        });
    } else {
        cashfree.initialiseDropin(paymentDom, dropConfig);
    }

})
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://sandbox.cashfree.com/pg/orders",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"customer_details\":{\"customer_id\":\"12345\",\"customer_email\":\"[email protected]\",\"customer_phone\":\"1299087801\"},\"order_amount\":1,\"order_currency\":\"INR\",\"order_note\":\"test order\"}",
  CURLOPT_HTTPHEADER => [
    "Accept: application/json",
    "Content-Type: application/json",
    "x-api-version: 2022-01-01",
    "x-client-id: Test_Client_ID",
     "x-client-secret: TEST_CLIENT_SECRET"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode(array("error" => 1));
  echo "cURL Error #:" . $err;
  die();

} else {
  $result = json_decode($response, true);
  header('Content-Type: application/json; charset=utf-8');
  $output = array("order_token" => $result["order_token"]);
  echo json_encode($output);
  die();
}
?>
<?php

$curl = curl_init();

curl_setopt_array($curl, [
  CURLOPT_URL => "https://sandbox.cashfree.com/pg/orders/" . $_GET["order_id"],
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => [
    "Accept: application/json",
    "Content-Type: application/json",
    "x-api-version: 2021-05-21",
    "x-client-id: Test_Client_ID",
     "x-client-secret: TEST_CLIENT_SECRET"
  ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode(array("error" => 1));
  echo "cURL Error #:" . $err;
  die();

} else {
  $result = json_decode($response, true);
  header('Content-Type: application/json; charset=utf-8');
  $output = array("order_status" => $result["order_status"]);
  echo json_encode($output);
  die();
}
?>

NPM

npm i cashfree-dropjs

For further steps please visit the official npm package


Did this page help you?