What is a Payment Gateway?
A Payment gateway is a platform that allows any online business to accept payments. It may offer payment options like cards (debit and credit cards), digital wallets, UPIs, etc.
These online companies or businesses are called merchants. These can be industries ranging from e-commerce to all SaaS businesses. Traditionally, payment gateways in India were provided by banks in the early 1990s.But since the late 1990s, external private companies have stepped in.
Today, most businesses integrate these third-party payment processors to collect payments from their customers. Like Paytm, Razorpay, Instamojo, Cashfree and Paypal etc. They can also help you with payments to suppliers and employees.
See also
- Paypal Payment Gateway Integration in PHP Step by Step
- Instamojo payment gateway integration in PHP
- Razorpay Payment Gateway Integration in PHP
- Paytm Payment Gateway Integration in PHP Step by Step
- Integrate PayUMoney Payment Gateway in PHP
How to Integrate Cashfree Payment Gateway in PHP
Integrating Cashfree Payment gateway in PHP is a very easy task. Here are some of the steps that are needed to be followed in order to integrate the Cashfree Payment gateway in PHP:
Cashfree Login or Sign-up
First of all go the cash free website https://www.cashfree.com/ and sign up for an account. After signing up, log in to your dashboard and navigate to the “API Keys” section to obtain your API credentials, including the App ID and Secret Key.
Click on the Developers button top of the page. In Payment gateway => API Keys => Generate API Keys => App ID and Secret Key.
Install the Cashfree PHP SDK
Cashfree provides an official PHP SDK to simplify the integration process. You can download it from GitHub or install it using Composer. For the latest instructions, check out Cashfree GitHub repository https://github.com/cashfree.
Use Composer Command
composer require cashfree/cashfree-pg-sdk-php
File Structure

File Name | Purpose |
---|---|
index.php | Contains the Products listing |
config.php | Contains the database connection |
cashfree-config.php | Contains Cashfree config like API KEY, SECRET KEY |
checkout.php | Contains customer and products details |
request.php | Send to the request to cashfree method |
response.php | Update payment status, Trxns Id & date show Trxns Details. |
Create Database and Table by SQL query
We need to create database and table, so here I created webscodex database payment_transaction & products table. payment_transaction table holds the records which will be payment success or failed. You can simply create table as following SQL query.
-- Database: `webscodex` -- -- -------------------------------------------------------- -- -- Table structure for table `products` -- CREATE TABLE `products` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `product_name` varchar(100) NOT NULL, `image` varchar(100) NOT NULL, `description` text NOT NULL, `price` int(50) NOT NULL, `status` tinyint(4) NOT NULL, `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci; -- -- Table structure for table `payment_transaction` -- CREATE TABLE `payment_transaction` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `order_id` varchar(100) NOT NULL, `product_summary` varchar(100) NOT NULL, `full_name` varchar(100) NOT NULL, `mobile_number` varchar(100) NOT NULL, `email` varchar(50) DEFAULT NULL, `amount` float(10,2) NOT NULL, `currency` varchar(100) NOT NULL, `status` varchar(100) NOT NULL, `txns_id` varchar(100) NOT NULL, `txns_date` datetime NOT NULL, `address` varchar(50) NOT NULL, `pincode` varchar(50) NOT NULL, `city` varchar(50) NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
Create Database Configuration
In this step, we require to create database configuration file, here we will set database name, server, username and password. So let’s create config.php file on your root directory and put bellow code:
config.php
<?php // Database configuration define('DBSERVER', 'localhost'); define('DBUSERNAME', 'root'); define('DBPASSWORD', ''); define('DBNAME', 'webscodex'); // Create database connection $con = new mysqli(DBSERVER, DBUSERNAME, DBPASSWORD, DBNAME); // Check connection if ($con->connect_error) { die("Connection failed: " . $con->connect_error); } ?>
Create Add to cart or Buy Product Page
Create Product list or add to card list in our project for e-commerce feature then buy a product using cashfree payment gateway. We have created an index.php file for product payment form.
index.php
<!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Cashfree Payment Gateway Integration in PHP Step by Step</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container" style="background:#e6e6e6;padding: 50px;"> <div class="py-5 text-center"> <h2> Products List (Cashfree Payment Gateway Integration) </h2> </div> <div class="row"> <?php // Database configuration require "inc/config.php"; $sql = "SELECT * FROM products WHERE status = '1' order by id DESC"; $query = $con->query($sql); if ($query->num_rows > 0) { while ($row = $query->fetch_assoc()) { ?> <div class="col-md-4"> <div class="card" style="height: 543px;"> <img src="images/<?php echo $row['image']?>" style="width:348px; height: 250px;"> <div class="card-body"> <h5 class="card-title"><?php echo $row['product_name']?></h5> <p class="card-text"><?php echo $row['description']?></p> <a href="checkout.php?product_id=<?php echo $row['id']?>" class="btn btn-sm btn-primary">Buy Now</a> <b><span style="float: right;">₹<?php echo $row['price']?></span></b> </div> </div> </div> <?php } } ?> </div> </div> </body> </html>
Cashfree App Id and Secret Key Config
This file is contains the Cashfree App Id, Secret Key and Response URL Initialization constant variable for global used.
cashfree-config.php
<?php // Cashfree configuration define('APPID', 'APP_ID'); // Replace "TEST" AppId to PROD AppId define('SECRECTKEY', 'SECRECT_KEY'); // Replace "TEST" Secret key to PROD Secret key define('RETURNURL', 'http://localhost/Cashfree-Payment-gateway-in-php/response.php'); define('NOTIFYURL', ''); define("CURRENCY", 'INR'); ?>
Create HTML Checkout Form
Create a HTML checkout form on your website with the required fields so that it can be passed to the Cashfree Payment to retrieve the order id and other information needed for the payment step. An example HTML form field is shown below. Name of the item, quantity, amount, item description, item address, email, and so on.
checkout.php
<?php // Database configuration require_once "inc/config.php"; // Include Cashfree Configuration require_once "inc/cashfree-config.php"; if (!empty($_GET['product_id']) && isset($_GET['product_id'])) { $pid = $_GET['product_id']; } $sql = "SELECT * FROM products WHERE id = $pid"; $query = $con->query($sql); if ($count = $query->num_rows > 0) { $row = $query->fetch_assoc(); } ?> <!DOCTYPE html> <html lang=""> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Cashfree Payment Gateway Integration in PHP Step by Step</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container" style="background: #f2f2f2; padding-bottom:20px; border: 1px solid #d9d9d9; border-radius: 5px;"> <div class="py-5 text-center"> <h2> Cashfree Payment Gateway Integration Checkout</h2> <p class="lead">This Checkout page using Cashfree Payment Gateway for Testing purpose </p> </div> <form action="request.php" method="POST"> <div class="row"> <div class="col-md-8"> <h4>Billing address</h4> <input type="hidden" class="form-control" name="appId" value="<?php echo APPID ?>"/> <input type="hidden" class="form-control" name="orderCurrency" value="<?php echo CURRENCY ?>" /> <input type="hidden" class="form-control" name="returnUrl" value="<?php echo RETURNURL ?>"/> <input type="hidden" class="form-control" name="notifyUrl" value="<?php echo NOTIFYURL ?>"/> <div class="card p-3"> <div class="mb-3"> <label for="firstName">Full Name </label> <input type="text" class="form-control" name="customerName" placeholder="Full Name" required=""> </div> <div class="mb-3"> <label for="mobile">Mobile Number</label> <input type="text" class="form-control" name="customerPhone" placeholder="Mobile Number" required=""> </div> <div class="mb-3"> <label for="email">Email</label> <input type="email" class="form-control" name="customerEmail" placeholder="Email"> </div> <div class="mb-3"> <label for="address">Flat, House no. Area, Street, Sector, Village</label> <input type="text" class="form-control" name="address" placeholder="Full Address" required=""> </div> <div class="row"> <div class="col-md-6 mb-3"> <label for="city">Town/City</label> <input type="text" class="form-control" name="city" placeholder="Town/City"> </div> <div class="col-md-6 mb-3"> <label for="pincode">Pincode</label> <input type="text" class="form-control" name="pincode" placeholder="6 digits [0-9] Pin code" required=""> </div> </div> </div> </div> <div class="col-md-4"> <h4 class="d-flex justify-content-between align-items-center"> <span>Order Summary</span> <span class="badge badge-secondary badge-pill"><?php echo $count; ?></span> </h4> <ul class="list-group mb-3 sticky-top"> <li class="list-group-item d-flex justify-content-between lh-condensed"> <div class="product-list"> <img src="images/<?php echo $row['image']?>" style="width:100px; height: 100px;"> <h6><?php echo $row['product_name']?></h6> <small class="text-muted"><?php echo $row['description']?></small> </div> <span class="text-muted">₹<?php echo $row['price']?></span> </li> <li class="list-group-item d-flex justify-content-between"> <strong> Order Total: </strong> <strong>₹<?php echo $row['price']?></strong> <input type="hidden" name="orderAmount" value="<?php echo $row['price']?>" /> <input type="hidden" name="product_summary" value="<?php echo $row['product_name']?>" /> </li> </ul> <div class="form-group"> <input type="submit" name="check_out" class="btn btn-success btn-block" value="Continue to Checkout"> </div> </div> </div> </form> </div> </body> </html>

Cashfree Payment Request Page
request.php
<!DOCTYPE html> <html> <head> <title>Cashfree - Signature Generator</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body onload="document.formSubmit.submit()"> <?php // Database configuration require_once "inc/config.php"; // Include Cashfree Configuration require_once "inc/cashfree-config.php"; $mode = "TEST"; //<------------ Change to TEST for test server, PROD for production extract($_POST); $secretKey = SECRECTKEY; // Secret key from cashfree-config.php // create order Id by using mt_rand function $orderId = "WC".mt_rand(11111, 99999); $postData = array( "appId" => $appId, "orderId" => $orderId, "orderAmount" => $orderAmount, "orderCurrency" => $orderCurrency, "customerName" => $customerName, "customerPhone" => $customerPhone, "customerEmail" => $customerEmail, "returnUrl" => $returnUrl, "notifyUrl" => $notifyUrl, ); ksort($postData); $signatureData = ""; foreach ($postData as $key => $value){ $signatureData .= $key.$value; } $signature = hash_hmac('sha256', $signatureData, $secretKey, true); $signature = base64_encode($signature); if ($mode == "PROD") { $url = "https://www.cashfree.com/checkout/post/submit"; } else { $url = "https://test.cashfree.com/billpay/checkout/post/submit"; } // Get Post Data from checkout page for insert into payment_transaction $customerName = $_POST['customerName']; $customerEmail = $_POST['customerEmail']; $customerPhone = $_POST['customerPhone']; $description = $_POST['product_summary']; $address = $_POST['address']; $city = $_POST['city']; $pincode = $_POST['pincode']; $amount = $_POST['orderAmount']; $currency = $_POST['orderCurrency']; $payment_status = 'Pending'; // Insert transaction data into the database $query = "INSERT INTO payment_transaction (order_id, product_summary, full_name, mobile_number, email, amount, currency, status, address, pincode, city) VALUES ('$orderId', '$description', '$customerName', '$customerPhone', '$customerEmail', '$amount', '$currency', '$payment_status', '$address', '$pincode', '$city')"; $con->query($query); ?> <form action="<?php echo $url; ?>" name="formSubmit" method="post"> <p>Please wait.......</p> <input type="hidden" name="signature" value='<?php echo $signature; ?>'/> <input type="hidden" name="orderCurrency" value='<?php echo $orderCurrency; ?>'/> <input type="hidden" name="customerName" value='<?php echo $customerName; ?>'/> <input type="hidden" name="customerEmail" value='<?php echo $customerEmail; ?>'/> <input type="hidden" name="customerPhone" value='<?php echo $customerPhone; ?>'/> <input type="hidden" name="orderAmount" value='<?php echo $orderAmount; ?>'/> <input type="hidden" name="notifyUrl" value='<?php echo $notifyUrl; ?>'/> <input type="hidden" name="returnUrl" value='<?php echo $returnUrl; ?>'/> <input type="hidden" name="appId" value='<?php echo $appId; ?>'/> <input type="hidden" name="orderId" value='<?php echo $orderId; ?>'/> </form> </body> </html>

Cashfree Payment Status or Response
response.php
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Cashfree Payment Gateway Integration in PHP Step by Step</title> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> </head> <body> <?php // Database configuration require_once "inc/config.php"; // Include Cashfree Configuration require_once "inc/cashfree-config.php"; $secretkey = SECRECTKEY; // Secret key from cashfree-config.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); /* update payment status, date and txnsId by order Id */ $query = "UPDATE payment_transaction SET txns_id ='$referenceId', txns_date ='$txTime', status='$txStatus' WHERE order_id = '$orderId'"; $con->query($query); if ($signature == $computedSignature) { ?> <div class="container"> <div class="card m-5"> <div class="card-heading text-success mt-3"> <h3 align="center">Your Payment has been Successful</h3> </div> <div class="card-body mt-2"> <div class="container"> <table class="table table-hover table-striped"> <tbody> <tr> <td>Order ID</td> <td><?php echo $orderId; ?></td> </tr> <tr> <td>Order Amount</td> <td><?php echo $orderAmount; ?></td> </tr> <tr> <td>Reference ID</td> <td><?php echo $referenceId; ?></td> </tr> <tr> <td>Transaction Status</td> <td><?php echo $txStatus; ?></td> </tr> <tr> <td>Payment Mode </td> <td><?php echo $paymentMode; ?></td> </tr> <tr> <td>Message</td> <td><?php echo $txMsg; ?></td> </tr> <tr> <td>Transaction Time</td> <td><?php echo $txTime; ?></td> </tr> </tbody> </table> </div> <a href="index.php" class="btn-link">Back to Products</a> </div> </div> </div> <?php } else { ?> <div class="container"> <div class="card mt-5"> <div class="card-heading text-danger mt-3"> <h3 align="center">Your PayPal Transaction has been Cancelled</h3> </div> <div class="card-body mt-2"> <div class="container"> <table class="table table-hover table-striped"> <tbody> <tr> <td>Order ID</td> <td><?php echo $orderId; ?></td> </tr> <tr> <td>Order Amount</td> <td><?php echo $orderAmount; ?></td> </tr> <tr> <td>Reference ID</td> <td><?php echo $referenceId; ?></td> </tr> <tr> <td>Transaction Status</td> <td><?php echo $txStatus; ?></td> </tr> <tr> <td>Payment Mode </td> <td><?php echo $paymentMode; ?></td> </tr> <tr> <td>Message</td> <td><?php echo $txMsg; ?></td> </tr> <tr> <td>Transaction Time</td> <td><?php echo $txTime; ?></td> </tr> </tbody> </table> </div> <a href="index.php" class="btn-link">Back to Products</a> </div> </div> <?php } ?> </body> </html>

Conclusion
In this tutorial, I have explain the process of How you can integrate Cashfree in PHP application. I have explain the very simple way to Cashfree payment integrate. You can extend this to more complex uses like online shops etc.
If you have any suggestions or problems about this tutorial, please comment on the form below.😊