Create Order

Create an order from with Cashfree from your backend

The first step to initiate a payment is to create an order in Cashfree's system. You need to do this from your backend server. You will pass the mandatory details like order amount, currency and customer details to create an order in Cashfree's system.

Once an order is created, you will receive an order token. This order token will be used by the JS sdk. Details about Create Order. Below we list down the two steps to get the token in your frontend.

Backend code

Here is a sample backend code that needs to be hosted by you to create an order. This endpoint will be consumed by your javascript code to fetch a token. Please note that the curl fields are hardcoded in the below PHP code.

<?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\":\"9908734801\"},\"order_amount\":4,\"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: <app Id>",
     "x-client-secret: <secret key>"
  ],
]);

$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();
}
?>
{"order_token":"uHOuAZtmNjo72tPI78GF"}

Javascript code

Once you have tested the backend code which creates a token for a specific order, we must call this endpoint from the frontend. Below we simply show how to do this in jquery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  var orderToken = "";
  const getTokenAndPay = function(){
  $.ajax({
    url: "http://localhost/cashfree/jssdk/fetchtoken.php",
    success: function(result) {
      console.log(result);
      orderToken = result["order_token"]
      // comment this out for now, we will use this later!
      //cfCheckout.pay(orderToken, payType);
    }
  });
  return false
}
</script>

What’s Next
Did this page help you?