NAV Navbar
Logo
PHP Java Python C# node.js Ruby

Intro

Welcome to the CashFree API! You can use this to access CashFree API endpoints, which allows you to create orders, get order status, send notification,etc...

We have language bindings in Shell and Php! You can view code examples in the dark area to the right, and you can switch the programming language of the examples with the tabs in the top right.

API reference

Test EndPoint: https://test.gocashfree.com/

Prod EndPoint: https://api.gocashfree.com/

CashFree uses API keys to allow access to the API. Once you have signed up at our merchant site, you will be able to retreive your AppId and SecretKey (API keys).

CashFree expects API key to be included in all API requests to the server.
Use the endpoint /api/v1/credentials/verify to verify your credentials first (check API reference section).

Create Order

To create orders.

HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/order/create

<?php
   $apiEndpoint = "https://test.gocashfree.com/";
   $opUrl = $apiEndpoint."api/v1/order/create";

   $cf_request = array();
   $cf_request["appId"] = "<your_app_id>";
   $cf_request["secretKey"] = "<your_secret_key>";
   $cf_request["orderId"] = "ORDER-104"; 
   $cf_request["orderAmount"] = 100;
   $cf_request["orderNote"] = "Subscription";
   $cf_request["customerPhone"] = "9000012345";
   $cf_request["customerName"] = "Test Name";
   $cf_request["customerEmail"] = "test@gocashfree.com";
   $cf_request["returnUrl"] = "https://example.com/return";
   $cf_request["notifyUrl"] = "https://example.com/notify";

   $timeout = 10;

   $request_string = "";
   foreach($cf_request as $key=>$value) {
     $request_string .= $key.'='.rawurlencode($value).'&';
   }

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL,"$opUrl?");
   curl_setopt($ch,CURLOPT_POST, count($cf_request));
   curl_setopt($ch,CURLOPT_POSTFIELDS, $request_string);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
   $curl_result=curl_exec ($ch);
   curl_close ($ch);

   $jsonResponse = json_decode($curl_result);
   if ($jsonResponse->{'status'} == "OK") {
     $paymentLink = $jsonResponse->{"paymentLink"};
     //Send this payment link to customer over email/SMS OR redirect to this link on browser
   } else {
    //Log request, $jsonResponse["reason"]
   }   
?>

using System;
using System.IO;
using System.Net;
using System.Text;

public enum HttpVerb
{
    GET,
    POST,
    PUT,
    DELETE
}

namespace HttpUtils
{
  public class RestClient
  {
    public string EndPoint { get; set; }
    public HttpVerb Method { get; set; }
    public string ContentType { get; set; }
    public string PostData { get; set; }



    public RestClient(string endpoint, HttpVerb method, string postData)
    {
      EndPoint = endpoint;
      Method = method;
      ContentType = "application/x-www-form-urlencoded";
      PostData = postData;
    }


    public string MakeRequest()
    {
      return MakeRequest("");
    }

    public string MakeRequest(string parameters)
    {
      var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);

      request.Method = Method.ToString();
      request.ContentLength = 0;
      request.ContentType = ContentType;

      if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
      {
        var encoding = new UTF8Encoding();
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
        request.ContentLength = bytes.Length;

        using (var writeStream = request.GetRequestStream())
        {
          writeStream.Write(bytes, 0, bytes.Length);
        }
      }

      using (var response = (HttpWebResponse)request.GetResponse())
      {
        var responseValue = string.Empty;

        if (response.StatusCode != HttpStatusCode.OK)
        {
          var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
         //Parse JSON response here
          throw new ApplicationException(message);
        }

        // grab the response
        using (var responseStream = response.GetResponseStream())
        {
          if (responseStream != null)
            using (var reader = new StreamReader(responseStream))
            {
              responseValue = reader.ReadToEnd();
            }
        }

        return responseValue;
      }
    }

    public static void Main() {
       String endPoint = "https://test.gocashfree.com/api/v1/order/create";

       String appId = "<Your_App_id>";
       String secretKey = "<Your_Secret_key>";
       String orderId = "ASP-102";
       String orderAmount = "100";
       String customerPhone = "9000012345";
       String customerName = "Test Name";
       String customerEmail = "user@gocashfree.com";
       String orderNote = "Bill for services";

       String postData = "appId=" + appId;
       postData += "&secretKey=" + secretKey;
       postData += "&orderId=" + orderId;
       postData += "&orderAmount=" + orderAmount;
       postData += "&customerPhone=" + customerPhone;
       postData += "&customerName=" + customerName;
       postData += "&customerEmail=" + customerEmail;
       postData += "&orderNote=" + orderNote;

       RestClient rc = new RestClient(endPoint, HttpVerb.POST, postData);
       String response = rc.MakeRequest();
       //parse response to get a json object. Name the object as responseObj
      // Redirect the user to responseObj.paymentLink

  } 
}

POST Parameters

Parameter Description
appId* Your app id
secretKey* Secret Key
orderId* Order/Reference Id (alphanumeric, max-len 100)
orderAmount* Bill amount of the order (numeric, max-len 10)
orderNote A help text to make customers know more about the order (alphanum, max-len 200)
customerName* Name of the customer (alphabets/spaces, max-len 150)
customerPhone* Phone number of customer (numeric, len 8-12)
customerEmail* Email id of the customer (valid email, max-len 200)
sellerPhone Notification phone number, which will get notified when payment for the order succeeds. Use it to accept COD payments
returnUrl Return URL to which user will be redirected after the payment (max-len 500)
notifyUrl Notification URL for server-server communication. Useful when user’s connection drops while re-directing (max-len 500) notifyUrl should be an https U
paymentModes Allowed payment modes for this order. Available values: cc, dc, nb, paypal, wallet
pc Partner Code

Response Parameters

Parameter Description
status* Status of API call. Values are - OK and ERROR
paymentLink link of payment page. Returned when status is OK
reason reason of failure when status is ERROR

Returns payment link for an existing order. Further, you can send it the customer via email or sms.

HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/order/info/link

POST Parameters

Parameter Description
appId Your app id
secretKey Secret Key
orderId Existing order id

Response Parameters

Parameter Description
status* Status of API call. Values are - OK and ERROR
paymentLink link of payment page for that order. Returned when status is OK
reason reason of failure when status is ERROR

Get Status

Returns payment status of an existing order. This can also be used to query order status at any point of time.

HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/order/info/status

POST Parameters

Parameter Description
appId Your app id
secretKey Secret Key
orderId Existing order id

Response Parameters

Parameter Description
status* Status of API call. Values are - OK and ERROR
orderStatus Payment status of order. Values are - ACTIVE, PAID, PROCESSED
reason reason of failure when status is ERROR
txStatus transaction status, if a payment has been attempted
txTime transaction time, if payment has been attempted
txMsg transaction message, if payment has been attempted
referenceId transaction reference id, if payment has been attempted
paymentMode payment mode of transaction, if payment has been attempted

Trigger Payment Email

Sends Email with payment link to the customer’s mailbox.

HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/order/email

POST Parameters

Parameter Description
appId Your app id
secretKey Secret Key
orderId Existing order id

Initiate Refund

<?php

   $apiEndpoint = "https://test.gocashfree.com/";
   $opUrl = $apiEndpoint."api/v1/order/refund";

   $cf_request = array();
   $cf_request["appId"] = "<your_app_id>";
   $cf_request["secretKey"] = "<your_secret_key>";
   $cf_request["referenceId"] = "<payment_reference_id>";
   $cf_request["refundAmount"] = 50;
   $cf_request["refundNote"] = "Sample Note";

   $timeout = 10;

   $request_string = "";
   foreach($cf_request as $key=>$value) {
     $request_string .= $key.'='.rawurlencode($value).'&';
   }

   $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL,"$opUrl?");
     curl_setopt($ch,CURLOPT_POST, count($cf_request));
     curl_setopt($ch,CURLOPT_POSTFIELDS, $request_string);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
     $curl_result=curl_exec ($ch);
   curl_close ($ch);

   $jsonResponse = json_decode($curl_result);
   if ($jsonResponse->{'status'} == "OK") {
     echo "Refund has been initiated";
   } else {
    //Log request, $jsonResponse->{"message"}
   }
?>


Can do partial/full refund of the payment made for the order

HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/order/refund

POST Parameters

Parameter Description
appId* Your app id
secretKey* Secret Key
referenceId* CashFree reference Id
refundAmount* Amount to be refunded. Should be lesser than equal to transaction amount
refundNote A refund note for your reference

Response Parameters

Parameter Description
status* Status of API call. Values are - OK and ERROR
message* Response message

Fetch Transactions

<?php

   $apiEndpoint = "https://test.gocashfree.com/";
   $opUrl = $apiEndpoint."api/v1/transactions";

   $cf_request = array();
   $cf_request["appId"] = "<your_app_id>";
   $cf_request["secretKey"] = "<your_secret_key>";
   $cf_request["startDate"] = "2016-09-12";
   $cf_request["endDate"] = "2016-09-14";
   $cf_request["count"] = 20;

   $timeout = 10;

   $request_string = "";
   foreach($cf_request as $key=>$value) {
     $request_string .= $key.'='.rawurlencode($value).'&';
   }

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL,"$opUrl?");
   curl_setopt($ch,CURLOPT_POST, count($cf_request));
   curl_setopt($ch,CURLOPT_POSTFIELDS, $request_string);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
   $curl_result=curl_exec ($ch);
   curl_close ($ch);

   $response = json_decode($curl_result, true);
   if ($response["status"] == "OK") {
     $transactions = $response["transactions"];
     foreach ($transactions as $transaction) {
        //Fetch transaction fields
     }
   } else {
    //Request failed;
   }
?>


Fetch transactions processed on your CashFree Account

HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/transactions

POST Parameters

Parameter Description
appId* Your app id
secretKey* Secret Key
startDate* Date(in the format of YYYY-MM-DD), from which you want the data
endDate* Date till you want the data (this date is included)
txStatus Filter the transactions as per the status. Valid status values are SUCCESS, FAILED, PENDING, FLAGGED and CANCELLED
lastId Use it for paginated response. Transactions having id greater than this value will be returned
count Number of transactions you want to receive. Default is 20 and max is 50.

Response Parameters

Parameter Description
status API call status (OK means successful, ERROR means otherwise)
settlements List of transaction
message response message (will have the reason when status is sent as ERROR)
lastId ID of the last transaction returned. Use it in your next request if current one didn't return all the transactions

Fields part of a transaction array

Parameter Description
id id of the entry
orderId merchant order id that is passed during payment request
orderAmount Order Amount
orderNote Order Note
customerName Customer Name
customerPhone Customer Phone
customerEmail Customer Email
referenceId Transaction Reference Id
txAmount Transaction Amount
txStatus Transaction Status
txTime Transaction Time
settlementStatus Settlement Status
refundStatus Refund Status

Fetch Refunds

<?php

   $apiEndpoint = "https://test.gocashfree.com/";
   $opUrl = $apiEndpoint."api/v1/refunds";

   $cf_request = array();
   $cf_request["appId"] = "<your_app_id>";
   $cf_request["secretKey"] = "<your_secret_key>";
   $cf_request["startDate"] = "2016-09-12";
   $cf_request["endDate"] = "2016-09-14";
   $cf_request["count"] = 20;

   $timeout = 10;

   $request_string = "";
   foreach($cf_request as $key=>$value) {
     $request_string .= $key.'='.rawurlencode($value).'&';
   }

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL,"$opUrl?");
   curl_setopt($ch,CURLOPT_POST, count($cf_request));
   curl_setopt($ch,CURLOPT_POSTFIELDS, $request_string);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
   $curl_result=curl_exec ($ch);
   curl_close ($ch);

   $response = json_decode($curl_result, true);
   if ($response["status"] == "OK") {
     $refunds = $response["refunds"];
     foreach ($refunds as $refund) {
        //Fetch refund fields
     }
   } else {
    //Request failed;
   }
?>


Fetch refunds processed on your CashFree Account

HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/refunds

POST Parameters

Parameter Description
appId* Your app id
secretKey* Secret Key
startDate* Date(in the format of YYYY-MM-DD), from which you want the data
endDate* Date till you want the data (this date is included)
lastId Use it for paginated response. Refunds having id greater than this value will be returned
count Number of refunds you want to receive. Default is 20 and max is 50.

Response Parameters

Parameter Description
status API call status (OK means successful, ERROR means otherwise)
refunds List of refunds
message response message (will have the reason when status is sent as ERROR)
lastId ID of the last refund returned. Use it in your next request if current one didn't return all the refunds

Fields part of a refund array

Parameter Description
refundId Id of the refund
orderId merchant order id that is passed during payment request
referenceId Cashfree reference id of the transaction
txAmount Transaction Amount
refundAmount Amount supposed to be refunded
refundNote Note provided during refund initiation
processed Refund processing status (Values will be YES or NO)
initiatedOn DateTime of refund initiation
processedOn DateTime of refund processing (Will be blank for unprocessed ones)

Fetch Settlements

<?php

   $apiEndpoint = "https://test.gocashfree.com/";
   $opUrl = $apiEndpoint."api/v1/settlements";

   $cf_request = array();
   $cf_request["appId"] = "<your_app_id>";
   $cf_request["secretKey"] = "<your_secret_key>";
   $cf_request["startDate"] = "2016-09-12";
   $cf_request["endDate"] = "2016-09-14";
   $cf_request["count"] = 20;

   $timeout = 10;

   $request_string = "";
   foreach($cf_request as $key=>$value) {
     $request_string .= $key.'='.rawurlencode($value).'&';
   }

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL,"$opUrl?");
   curl_setopt($ch,CURLOPT_POST, count($cf_request));
   curl_setopt($ch,CURLOPT_POSTFIELDS, $request_string);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
   $curl_result=curl_exec ($ch);
   curl_close ($ch);

   $response = json_decode($curl_result, true);
   if ($response["status"] == "OK") {
     $settlements = $response["settlements"];
     foreach ($settlements as $settlement) {
        //Fetch settlement fields
     }
   } else {
    //Request failed;
   }
?>


Fetch settlements processed on your CashFree Account

HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/settlements

POST Parameters

Parameter Description
appId* Your app id
secretKey* Secret Key
startDate* Date(in the format of YYYY-MM-DD), from which you want the data
endDate* Date till you want the data (this date is included)
lastId Use it for paginated response. Settlements having id greater than this value will be returned
count Number of settlements you want to receive. Default is 20 and max is 50.

Response Parameters

Parameter Description
status API call status (OK means successful, ERROR means otherwise)
settlements List of settlements
message response message (will have the reason when status is sent as ERROR)
lastId ID of the last settlement returned. Use it in your next request if current one didn't return all the settlements

Fields part of a settlement array

Parameter Description
id Settlement Id (use it to fetch transactions that are part of this settlement)
totalTxAmount Total transactions amount
settlementAmount Amount after deducting the TDR
adjustment Any adjustments (because of refunds OR disputes).
amountSettled Amount settled after including the adjustments
transactionFrom transaction included from this day
transactionTill transactions included till this day
utr Bank Reference number
settledOn Time of settlement (this could be different than credit date shown on the account statement)

Fetch transactions that are part of a settlement

<?php

   $apiEndpoint = "https://test.gocashfree.com/";
   $opUrl = $apiEndpoint."api/v1/settlement";

   $cf_request = array();
   $cf_request["appId"] = "<your_app_id>";
   $cf_request["secretKey"] = "<your_secret_key>";
   $cf_request["settlementId"] = "<settlement_id>";
   $cf_request["count"] = 20;

   $timeout = 10;

   $request_string = "";
   foreach($cf_request as $key=>$value) {
     $request_string .= $key.'='.rawurlencode($value).'&';
   }

   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL,"$opUrl?");
   curl_setopt($ch,CURLOPT_POST, count($cf_request));
   curl_setopt($ch,CURLOPT_POSTFIELDS, $request_string);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
   $curl_result=curl_exec ($ch);
   curl_close ($ch);

   $response = json_decode($curl_result, true);
   if ($response["status"] == "OK") {
     $transactions = $response["transactions"];
     foreach ($transactions as $transaction) {
        //Fetch transaction fields
     }
   } else {
    //Request failed;
   }
?>


HTTP Request

Method: POST
Content-Type: application/x-www-form-urlencoded
Endpoint: /api/v1/settlement

POST Parameters

Parameter Description
appId* Your app id
secretKey* Secret Key
settlementId ID of the settlement
lastId Use it for paginated response. Transactions having id greater than this value will be returned
count Number of transactions you want to receive. Default is 20 and max is 50.

Response Parameters

Parameter Description
status API call status (OK means successful, ERROR means otherwise)
transactions List of transactions
message response message (will have the reason when status is sent as ERROR)
lastId ID of the last transaction returned. Use it in your next request if current one didn't return all the transactions

Fields part of a transaction array

Parameter Description
id id of the entry
orderId merchant order id that is passed during payment request
referenceId Cashfree reference id of the transaction
txAmount Transaction Amount
paymentMode Payment Mode
bankName Issuer Bank (currently supported for NetBanking payment mode)
serviceCharge service charge computed
serviceTax service tax computed on service charge
settlementAmount Amount after reducing servie charge and service tax from transaction amount
txTime Transaction Time

Payment Gateway Integration

Checkout Form

Sample checkout form

  <form id="redirectForm" method="post" action="ACTION_URL">
    <input type="hidden" name="appId" value="YOUR_APP_ID"/>
    <input type="hidden" name="orderId" value="ORDERID"/>
    <input type="hidden" name="orderAmount" value="ORDERAMOUNT"/>
    <input type="hidden" name="orderNote" value="ORDERNOTE"/>
    <input type="hidden" name="customerName" value="CUSTOMER_NAME"/>
    <input type="hidden" name="customerEmail" value="CUSTOMER_EMAIL"/>
    <input type="hidden" name="customerPhone" value="CUSTOMER_PHONE"/>
    <input type="hidden" name="returnUrl" value="RETURN_URL"/>
    <input type="hidden" name="notifyUrl" value="NOTIFY_URL"/>
    <input type="hidden" name="signature" value="GENERATED_SIGNATURE"/>
  </form>

You can also use below javascript snippet to submit the form automatically on page load without waiting for user's click.

  <script type="text/javascript">
    document.getElementById("redirectForm").submit();
  </script>

Code sample to generate signature

<?php

  $postData = array( "appId" => $appId,
                     "orderId" = > $ORDERID,
                     "orderAmount" => $ORDERAMOUNT,
                     "orderNote" => $ORDERNOTE,
                     "customerName" => $customerName,
                     "customerPhone" => $customerPhone,
                     "customerEmail" => $customerEmail,
                     "returnUrl" => $returnUrl,
                     "notifyUrl" => $notifyUrl,
);
 // get secret key from your config
 ksort($postData);
 $signatureData = "";
 foreach ($postData as $key => $value){
      $signatureData .= $key.$value;
 }
 $signature = hash_hmac('sha256', $signatureData, $secretKey,true);
 $signature = base64_encode($signature);
?>
import hashlib
import hmac
import base64

postData = {"appId" : appId, "orderId" : orderId, "orderAmount" : orderAmount, "orderNote" : orderNote, "customerName" : customerName, "customerPhone" : customerPhone, "customerEmail" : customerEmail, "returnUrl" : returnUrl, "notifyUrl" : notifyUrl};

sortedKeys = sorted(postData);
signatureData = "";
for key in sortedKeys:
  signatureData += key+postData[key];

message = bytes(signatureData).encode('utf-8')
#get secret key from your config
secret = bytes(secretKey).encode('utf-8')
signature = base64.b64encode(hmac.new(secret, message,digestmod=hashlib.sha256).digest())

Map<String, String> postData = new HashMap<String, String>();
postData.put("appId", appId);
postData.put("orderId", ORDERID);
postData.put("orderAmount", ORDERAMOUNT);
postData.put("orderNote", ORDERNOTE);
postData.put("customerName", CUSTOMER_NAME);
postData.put("customerEmail", CUSTOMER_EMAIL);
postData.put("customerPhone", CUSTOMER_PHONE);
postData.put("returnUrl",RETURN_URL);
postData.put("notifyUrl", NOTIFY_URL);

String data = "";
SortedSet<String> keys = new TreeSet<String>(postData.keySet());
for (String key : keys) {
    data = data + key + postData.get(key);
}
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key_spec = new
SecretKeySpec(secretKey.getBytes(),"HmacSHA256");
sha256_HMAC.init(secret_key_spec);
String signature = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(data.getBytes()));

using System;
using System.Security.Cryptography;
using System.Collections.Generic;

namespace Rextester {
  public class Program {
    private string CreateToken(string message, string secret){
      secret = secret ?? "";
      var encoding = new System.Text.ASCIIEncoding();
      byte[] keyByte = encoding.GetBytes(secret);
      byte[] messageBytes = encoding.GetBytes(message);
      using (var hmacsha256 = new HMACSHA256(keyByte))
      {
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
        return Convert.ToBase64String(hashmessage);
      }
    }

    public static void Main(string[] args) {

      string secret = "<your_secret_key>";
      string data = "";  

      SortedDictionary<string, string> formParams = new SortedDictionary<string, string>();
      formParams.Add("appId", "<your_app_id>");
      formParams.Add("orderId", "FEX101");
      formParams.Add("orderAmount", "10.00");
      formParams.Add("orderNote", "Test payment");
      formParams.Add("customerName", "Customer Name");
      formParams.Add("customerPhone", "9900000085");
      formParams.Add("customerEmail", "test@gocashfree.com");
      formParams.Add("returnUrl", "http://example.com");
      formParams.Add("notifyUrl", "http://example.com");

     foreach (var kvp in formParams) {
        data = data + kvp.Key + kvp.Value;
     }

      Program n = new Program();
      string signature = n.CreateToken(data, secret);
      Console.WriteLine(signature);
    }
  }
}


In this method, you will prepare the checkout form with order and customer details and redirect the user to cashfree payment page to let customer provide card/bank details. Below are the list of parameters supported for this form. A sample form is displayed on the right side.

POST Parameters

Parameter Description
appId* Your Cashfree App Id
orderId* Order Id
orderAmount* Bill amount of the order
orderNote A help text to make customers know more about the order
customerName* Name of the customer
customerPhone* Phone number of customer
customerEmail* Email id of the customer
returnUrl* Return URL to which user will be redirected after the payment
notifyUrl Notification URL for server-server communication. Useful when user’s connection drops while re-directing. notifyUrl should be an https URL
paymentModes Allowed payment modes for this order. Available values: cc, dc, nb, paypal, wallet
pc Partner Code
signature* request signature

Signature is generated by computing HMAC hash of concatenated key-value pairs. Please find language specific signature generation code in the example section.
TEST action_url: https://test.gocashfree.com/billpay/checkout/post/submit
PROD action_url: https://www.gocashfree.com/checkout/post/submit

Merchant Hosted

This integration mode allows customers to provide their card/bank details on merchant's website itself. Unlike checkout form/API based integration, users need not navigate away from your website. However, for mobile views, standard redirect flow will be adopted.

Customer card details are accepted inside a cashfree-managed iframe. You do not have to work on securing the details yourself. You can use this mode without worrying about PCI compliances. We take care of it on your behalf.

Steps

Inline mode

<div id="payment-div"></div>
# Paste below code base before the closing tag(</body>) of body element
<script src="https://www.gocashfree.com/assets/cashfree.sdk.v1.js" type="text/javascript"></script>
<script type="text/javascript">
(function() {

  var data = {};
  data.orderId = "1234";
  data.orderAmount = 450;
  data.customerName = "Seth";
  data.customerPhone = "900XXXXX21";
  data.customerEmail = "example@example.com";
  data.returnUrl = "https://mysite.com/payment/response";
  data.notifyUrl = "https://mysite.com/payment/notify";
  data.appId = "<your_app_id>";
  data.paymentToken = "<payment_token>";

  var callback = function (event) { 
      var eventName = event.name; 
      switch(eventName) {
        case "PAYMENT_REQUEST":
           console.log(event.message);
           break;
        default:
           console.log(event.message);
       };
  }

  var config = {};
  config.layout = {view: "inline", container: "payment-div", width: "600"};
  config.mode = "TEST"; //use PROD when you go live
  var response = CashFree.init(config);
  if (response.status == "OK") {
    CashFree.makePayment(data, callback);
  } else {
    //handle error
     console.log(response.message);
  }

  })();
</script>

Inline

This is first of two sub-modes supported under hosted checkout mode. Cashfree payment form can be embedded anywhere at your page. Form width and color theme can be controlled by you. Code examples are mentioned in the right bar.

Popup mode

# Paste below code base before the closing tag(</body>) of body element
<script src="https://www.gocashfree.com/assets/cashfree.sdk.v1.js" type="text/javascript"></script>
<script type="text/javascript">
(function() {

  var cfInitialized = false;
  var data = {};
  data.orderId = "1234";
  data.orderAmount = 450;
  data.customerName = "Seth";
  data.customerPhone = "900XXXXXX21";
  data.customerEmail = "example@example.com";
  data.returnUrl = "https://mysite.com/payment/response";
  data.notifyUrl = "https://mysite.com/payment/notify";
  data.appId = "<your_app_id>";
  data.paymentToken = "<payment_token>";

  var callback = function (event) { 
      var eventName = event.name; 
      switch(eventName) {
        case "PAYMENT_REQUEST":
           console.log(event.message);
           break;
        default:
           console.log(event.message);
       };
  }

  var config = {};
  config.layout = {view: "popup", width: "650"};
  config.mode = "TEST"; //use PROD when you go live
  var response = CashFree.init(config);
  if (response.status == "OK") {
    cfInitialized = true;
  } else {
    //handle error
     console.log(response.message);
  }

# Make sure you put id of your payment button, that triggeres the payment flow, at below statement. 
  $("#paymentButton").click(function () {
    if (cfInitialized) { 
      CashFree.makePayment(data, callback);
    }
  }); 

})();
</script>

This is the second sub-mode. It allows you to host the payment form without making any changes to your page layout. You can control form width and color theme for this sub-mode too. Code examples are mentioned in the right bar.

Sample code to generate payment token

 <?php
   $appId = "<your_app_id>"; //replace it with your appId
   $secretKey = "<your_secret_key">"; //replace it with your secret key 
   $orderId = "1234"; 
   $orderAmount = 450; 
   $returnUrl = "https://mysite.com/payment/response"; 
   $paymentModes = ""; //keep it blank to display all supported modes 
   $tokenData = "appId=".$appId."&orderId=".$orderId."&orderAmount=".$orderAmount."&returnUrl=".$returnUrl."&paymentModes=".$paymentModes;
   $token = hash_hmac('sha256', $tokenData, $secretKey, true);
   $paymentToken = base64_encode($token);
 ?>
import hashlib
import hmac
import base64

data = "appId=" + appId + "&orderId=" + orderId + "&orderAmount=" + orderAmount + "&returnUrl=" + returnUrl + "&paymentModes=" + paymentModes;
message = bytes(data).encode('utf-8')
secret = bytes(secretKey).encode('utf-8')
paymentToken = base64.b64encode(hmac.new(secret, message,digestmod=hashlib.sha256).digest())
  String data = "appId=" + appId + "&orderId=" + orderId + "&orderAmount=" + orderAmount + "&returnUrl=" + returnUrl + "&paymentModes=" + paymentModes;
  Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  SecretKeySpec skspec = new SecretKeySpec(secretKey.getBytes(),"HmacSHA256");
  sha256_HMAC.init(skspec);
  paymentToken = Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes()));
using System;
using System.Security.Cryptography;


namespace HttpUtils
{
  public class CashFreeToken
  {
     private string CreateToken(string message, string secret){
       secret = secret ?? "";
       var encoding = new System.Text.ASCIIEncoding();
       byte[] keyByte = encoding.GetBytes(secret);
       byte[] messageBytes = encoding.GetBytes(message);
       using (var hmacsha256 = new HMACSHA256(keyByte))
       {
         byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
         return Convert.ToBase64String(hashmessage);
       }
     }

     public static void Main() { 
       String appId = "<Your_APP_ID>";
       String orderId = "<Your_Order_ID>";
       String orderAmount = "<Order_amount>";
       String returnUrl = "<return_url>";
       String paymentModes = "";
       String secret = "<secret_key>";

       String data = "appId=" + appId + "&orderId=" + orderId + "&orderAmount=" + orderAmount + "&returnUrl=" + returnUrl + "&paymentModes=" + paymentModes;

       CashFreeToken n = new CashFreeToken();
       String signature = n.CreateToken(data, secret);
       Console.WriteLine(signature);
     }
  } 
}

JSON data parameters

Parameter Description
appId* Your app id
orderId* Order/Reference Id
orderAmount* Bill amount of the order
orderNote A help text to make customers know more about the order
customerName Name of the customer
customerPhone* Phone number of customer
customerEmail* Email id of the customer
returnUrl* Return URL to which user will be redirected after the payment
notifyUrl Notification URL for server-server communication. Useful when user’s connection drops while re-directing. notifyUrl should be an https URL
paymentModes Allowed payment modes for this order. Available values: cc, dc, nb, paypal, wallet. Leave it blank if you want to display all modes
paymentToken* Unique token to be generated for each new order. Refer example section in right for code samples

Configuration parameters

Parameter Description
mode Inetgration stage. Values could be TEST or PROD
layout javascript object to define layout
layout.view (i) "inline" for inline view (ii) "popup" for popup (iii) "page" for standard redirect flow
layout.width Width of payment form. Value should be a number. Could be in range of 500 to 700.
layout.container Applicable(and mandatory) for inline view. Id of a html div/section into which payment form will be rendered.

API Integration

We also support REST API integration to enable you collect payment at your website. Please refer create order via API section to learn how to create new order via an API call.

Seamless - JS Integration

If you want to create your own payment page then you can use our JS SDK for initiating Seamless payments. This allows you to provide your own Payment Details form and then invoke our payment subroutine. The payment will be finished in a popup and you will get a callback.

The detailed steps for each of the payment types are highlighted below:

Steps

CashFree.paySeamless(data, paymentCallback)

Parameter Description
data A simple JS Object containing all the data related to transaction. All possible parameters listed below in JS Parmeters section
paymentCallback A callback method of the form paymentCallback(event). Event object is described in the JS Response section

Sample code to generate payment token

 <?php
   $appId = "<your_app_id>"; //replace it with your appId
   $secretKey = "<your_secret_key">"; //replace it with your secret key 
   $orderId = "1234"; 
   $orderAmount = 450;
   $customerEmail = test@gmail.com
   $customerPhone = 9900012345;
   $tokenData = "appId=".$appId."&orderId=".$orderId."&orderAmount=".$orderAmount."&customerEmail=".$customerEmail."&customerPhone=".$customerPhone;   $token = hash_hmac('sha256', $tokenData, $secretKey, true);
   $paymentToken = base64_encode($token);
 ?>
import hashlib
import hmac
import base64

data = "appId=" + appId + "&orderId=" + orderId + "&orderAmount=" + orderAmount + "&customerEmail=" + customerEmail + "&customerPhone=" + customerPhone;
message = bytes(data).encode('utf-8')
secret = bytes(secretKey).encode('utf-8')
paymentToken = base64.b64encode(hmac.new(secret, message,digestmod=hashlib.sha256).digest())
  String data = "appId=" + appId + "&orderId=" + orderId + "&orderAmount=" + orderAmount + "&customerEmail=" + customerEmail + "&customerPhone=" + customerPhone;
  Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
  SecretKeySpec skspec = new SecretKeySpec(secretKey.getBytes(),"HmacSHA256");
  sha256_HMAC.init(skspec);
  paymentToken = Base64.encodeBase64String(sha256_HMAC.doFinal(data.getBytes()));
using System;
using System.Security.Cryptography;


namespace HttpUtils
{
  public class CashFreeToken
  {
     private string CreateToken(string message, string secret){
       secret = secret ?? "";
       var encoding = new System.Text.ASCIIEncoding();
       byte[] keyByte = encoding.GetBytes(secret);
       byte[] messageBytes = encoding.GetBytes(message);
       using (var hmacsha256 = new HMACSHA256(keyByte))
       {
         byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
         return Convert.ToBase64String(hashmessage);
       }
     }

     public static void Main() { 
       String appId = "<Your_APP_ID>";
       String orderId = "<Your_Order_ID>";
       String orderAmount = "<Order_amount>";
       String customerEmail = "<return_url>";
       String customerPhone = "";
       String secret = "<secret_key>";

       String data = "appId=" + appId + "&orderId=" + orderId + "&orderAmount=" + orderAmount + "&customerEmail=" + customerEmail + "&customerPhone=" + customerPhone;

       CashFreeToken n = new CashFreeToken();
       String signature = n.CreateToken(data, secret);
       Console.WriteLine(signature);
     }
  } 
}

JS Parameters

These parameters are available for all payment types.

General Parameters Description
data.appId* Your app id
data.orderId* Order/Reference Id
data.orderAmount* Bill amount of the order
data.orderNote A help text to make customers know more about the order
data.customerName Name of the customer
data.customerPhone* Phone number of customer
data.customerEmail* Email id of the customer
data.notifyUrl Notification URL for server-server communication. Useful when user’s connection drops while re-directing. notifyUrl should be an https URL
data.paymentToken* Unique token to be generated for each new order. Refer example section in right for code samples.
data.pc Partner Code

CREDIT CARD

These parameters are available only for Credit Card Payments

Parameter Description
data.card.num* Credit Card Number. Sixteen digits only. No spaces or Hyphens
data.card.expiryMonth* Expiration Month for the Credit Card. In MM format.
data.card.expiryYear* Expiration Year for the Credit Card. In YYYY format.
data.card.cvv* CVV number of the Credit Card
data.card.holder* Name of the Card Holder

NET BANKING

These parameters are available only for Credit Card Payments

Parameter Description
data.nb.code* Code for the Bank See the list below
Bank Code Bank Name
3333 TEST Bank. This is a mock bank for testing only
3003 Axis Bank
3028 IndusInd Bank
3057 Vijaya Bank

WALLET

These parameters are available only for Wallets

Parameter Description
data.wallet.code* Code for the Bank See the list below
Wallet Code Bank Name
4001 Free Charge
4002 Mobikwik
4003 Ola Money

UPI

These parameters are available only for UPI

Parameter Description
data.upi.vpa* UPI VPA for triggering UPI payment

JS Response

paymentCallback as mentioned above is a JS function of the form paymentCallback(event). These function paymentCallback will be called once to report the status of the Payment. The event parameter will have details of the transaction. Here are the various possible values of the event parameter

Case event.name event.status
Successful Payment PAYMENT_RESPONSE SUCCESS
Payment Failed PAYMENT_RESPONSE FAILED
Payment not completed PAYMENT_RESPONSE CANCELLED
Invalid inputs VALIDATION_ERROR -

Mobile App

Android Integration

Use our library to integrate the Cashfree Payment Gateway directly into your app using CashfreeSDK for Android. CashfreeSDK has been designed to offload the complexity of handling and integrating payments in your app.

The CashfreeSDK is available at a publicly hosted github repo as an AAR (link below). Instructions on importing the lib is also provided.

CashFree Android SDK V0

Details

The CashfreeSDK requires that you add the permissions shown on the right panel in your Android Manifest

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Prototype of the doPayment method of CFPaymentService


    /***
     * This method handles the payment gateway invocation.
     *
     * @param context Android context of the calling method
     * @param params Map containing all the parameters required for creating a payment order
     * @param checksumUrl Provide the checksumUrl to verify the integrity of the transaction
     * @param callback Reference of the class which will be notified on completion of the request
     *                 via a callback
     * @param stage Indetifies if test or production service needs to be invoked. Possible values:
     *              PROD, TEST.
     */

    public void doPayment(Context context, Map<String, String> params,
                          String checksumUrl, CFClientInterface callback, String stage) {

Invoke the payment gateway with a couple of lines of code from your activity


CFPaymentService cfpay = CFPaymentService.getCFPaymentServiceInstance();
cfpay.doPayment(this, params, checksum, this);

Please follow the below mentioned steps after pulling in CashfreeSDK into your setup.

Steps for using the CashfreeSDK

  1. Implement the CFClientInterface in the calling activity.

  2. Get the instance of the CFPaymentService

  3. Use doPayment method on the CFPaymentService to invoke the CashfreeSDK. Look at the adjoining code example for more information.

  4. Typically the context will be provided by the calling activity, the callback should also be handled by implementing the methods of CFClientInterface.

  5. A merchant hosted Checksum generation url should be provided. This allows us to verify the integrity of transaction. Please refer to the checksum generation section for a sample of checksum generation code.

  6. Parameters include order and customer details. Refer to the table below for the full list:

Checksum Generation

The checksum is a SHA256 hash of the values involved in the transaction. Please see the example scripts for more information. Please ensure that checksum scripts responds with the JSON encoded information in the following format

{ "orderId" : order_id_value, "checksum" : checksum_value, "status" : "OK" }

<?php
 $appId = ... //CODE for fetching your appId from your config files
 $secretKey ... //CODE to fetching your secretKey from your config files

 //The postData initializes its values from the Post parameters
 foreach($_POST as $key => $value) {
    $postData[$key] = $_POST[$key];
 }

 // Also add appId  
  $postData["appId"] = $appId;

 // combine all of the data into a single string as shown below
 ksort($postData);
 $checksumData = "";
 foreach ($postData as $key => $value){
      $checksumData .= $key.$value;
 }

 $checksum = hash_hmac('sha256', $checksumData, $secretKey,true);
 $checksum = base64_encode($checksum);

 // This is how the response is expected
 $response = array("orderId" => $orderId, "checksum" => $checksum, "status" => "OK");
 echo json_encode($response);
?>

    String appId = ..; //CODE to retreive the APP ID from your config
    String secretKey = ..; //CODE to retreive the SECRET KEY from your config

    Map<String, String> postData = ..; //CODE For retreiving all Post Parameters as Hashmap

    postData.put("appId", appId); //ensure that appId is initialized from your config
    
    //Generate Checksum
    String data = "";
    SortedSet<String> keys = new TreeSet<String>(postData.keySet());
    for (String key : keys) {
    data = data + key + postData.get(key);
    }
    Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key_spec = new
    SecretKeySpec(secretKey.getBytes(),"HmacSHA256");
    sha256_HMAC.init(secret_key_spec);

    String checksum = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(data.getBytes()));


    //Prepare the response JSON
    JSONObject obj = new JSONObject();
    obj.put("orderId", postData.get("orderId"));
    obj.put("checksum", checksum);

    obj.put("status", "OK");

    //Return the JSON Response
    String jsonResponse = obj.toString();

Parameters for the CFPaymentService

Parameter Description
appId* Your app id
orderId* Order/Reference Id
orderAmount* Bill amount of the order
orderNote A help text to make customers know more about the order
customerName* Name of the customer
customerPhone* Phone number of customer
customerEmail* Email id of the customer
checksumUrl* Link hosted on your server, that computes and returns a signature for the parameters sent to it
notifyUrl Notification URL for server-server communication. Useful when user’s connection drops while re-directing. notifyUrl should be an https URL
paymentModes Allowed payment modes for this order. Available values: cc, dc, nb, paypal, wallet. Leave it blank if you want to display all modes

Response parameters, shared with callback functions

Please refer to left panel for information on params argument

public interface CFClientInterface {
    // The Payment succeeded
    void onSuccess(Map<String, String> params);

    // Payment did not succeed 
    void onFailure(Map<String, String> params);

    // The user navigated back from payment activity
    void onNavigateBack();
}

These parameters are returned to the callback functions you implement (for e.g. params argument of the CFClientInterface onSuccess() method). They contain the details of the transaction.

Parameter Description
orderId Order id for which transaction has been processed. Ex: GZ-212
orderAmount Amount of the order. Ex: 256.00
referenceId Cashfree generated unique transaction Id. Ex: 140388038803
txStatus Payment status for that order. Values can be : SUCCESS, FLAGGED, FAILED, CANCELED.
paymentMode Payment mode used by customer to make the payment. Ex: DEBIT_CARD, MobiKwik, etc..
txMsg Message related to the transaction. Will have the reason, if payment failed
txTime Time of the transaction

Payment Response

We send response paramaters to both returnUrl and notifyUrl(which were passed during the payment request) via HTTP POST method. Please note few times due to drop in network connection at user's end, users fail to load the returnUrl in the browser and thus response couldn't get processed.

To have a fallback for such instances, we recommend you to use notifyUrl to receive same set of parameters through a server-server communication. You can update the order status on receiving response at the notifyUrl if redirect to returnUrl fails.

Response Parameters

Parameter Description
orderId Order id for which transaction has been processed. Ex: GZ-212
orderAmount Amount of the order. Ex: 256.00
referenceId Cashfree generated unique transaction Id. Ex: 140388038803
txStatus Payment status for that order. Values can be : SUCCESS, FLAGGED, FAILED, CANCELED.
paymentMode Payment mode used by customer to make the payment. Ex: DEBIT_CARD, MobiKwik, etc..
txMsg Message related to the transaction. Will have the reason, if payment failed
txTime Time of the transaction
signature HMAC value of the data being passed. Generated using SHA256 hash function in combination with merchant’s API secret key (Your API secret key can be retrieved from "Settings -> API Access" tab). Purpose of this argument is to authenticate the server call. We will generate a signature at our end and expect you to do the same with the POSTED data and match it with the passed argument.

Hash Generation

<?php
  $orderId = $_POST["orderId"];
  $orderAmount = $_POST["orderAmount"];
  $referenceId = $_POST["referenceId"];
  $txStatus = $_POST["txStatus"];
  $paymentMode = $_POST["paymentMode"];
  $txMsg = $_POST["txMsg"];
  $txTime = $_POST["txTime"];
  $signature = $_POST["signature"];

  $data = $orderId.$orderAmount.$referenceId.$txStatus.$paymentMode.$txMsg.$txTime;
  $hash_hmac = hash_hmac('sha256', $data, $secretkey, true) ;
  $computedSignature = base64_encode($hash_hmac);

  if ($signature == $computedSignature) {
    // Proceed
  } else {
    // Reject this call
  }
?>
import hashlib
import hmac
import base64

data = orderId + orderAmount + referenceId + txStatus + paymentMode + txMsg + txTim
message = bytes(data).encode('utf-8')
secret = bytes(secretKey).encode('utf-8')
signature = base64.b64encode(hmac.new(secret, message,digestmod=hashlib.sha256).digest())
if (signature != computedSignature):
    //Reject
else:
    //Proceed
require 'openssl'
require "base64"
hash = OpenSSL::HMAC.digest('sha256', secretKey, data)
computedSignature = Base64.encode64(hash)
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class ComputedSignature {
  public static String generateHMAC(String secretKey, String data) {
    String hash = null;
    try {
      String secret = secretKey;
      String message = data;
      Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
      SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(),"HmacSHA256");
      sha256_HMAC.init(secret_key);
      hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
    }
    catch (Exception e){
      //Log it
    }
    return hash;
  }
}
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System;
using System.Security.Cryptography;
namespace Rextester {
  public class Program {
    private string CreateToken(string message, string secret){
      secret = secret ?? "";
      var encoding = new System.Text.ASCIIEncoding();
      byte[] keyByte = encoding.GetBytes(secret);
      byte[] messageBytes = encoding.GetBytes(message);
      using (var hmacsha256 = new HMACSHA256(keyByte))
      {
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
        return Convert.ToBase64String(hashmessage);
      }
    }
    public static void Main(string[] args) {
      string secret = "<Your_secret_key>";
      string message = orderId + orderAmount + referenceId +
      txStatus + paymentMode + txMsg + txTime;Program n = new Program();
      string signature = n.CreateToken(message, secret);
      Console.WriteLine(signature);
    }
  }
}

var crypto = require('crypto');
var hmac = function(msg, secret){
  var hmac = require('crypto').createHmac('sha256', secret);
  hmac.update(msg);
  return hmac.digest('base64');
};

var orderId = "FLSQ103";
var orderAmount = "51";
var referenceId = "1470045350650";
var status = "SUCCESS";
var paymentMode = "NET_BANKING";
var message = "Transaction Completed";
var txTime = "2016-08-01 15:26:23";
var accesskey = "63ca0b83c8ca85d73fff9c3fd29a7c87e292fd63";
var str = "";
var dataToHash = str.concat(orderId, orderAmount, referenceId, status,
paymentMode, message, txTime);
console.log(hmac(dataToHash, accesskey));

Browse through language tabs on the right to see how you can generate hash for respective language.

Test Data

Test Card

Parameter Value
Number 4444 3333 2222 1111
Expiry 07/18
CVV 123
Name Test
Parameter Value
Number 4111 1111 1111 1111
Expiry 07/18
CVV 123
Name Test

Test Net Banking

Use "TEST Bank" while testing Net Banking payment mode