Integrate Cashfree Payment Gateway: A Step-by-Step Guide (2025)


💳 Integrate Cashfree Payment Gateway: A Step-by-Step Guide (2025)

In the digital era, online payments have become the backbone of modern business. Whether you’re selling physical products, digital content, subscriptions, or services, having a secure, fast, and reliable payment gateway is essential. One of India’s fastest-growing payment solutions is Cashfree Payments—a powerful platform that enables developers and businesses to accept payments from customers in India and globally.

In this comprehensive guide, we’ll take you through everything you need to know about integrating Cashfree Payment Gateway into your PHP-based web application. By the end, you’ll be ready to go live with a fully functional and secure payment system.


🧐 Why Choose Cashfree Payments?

Before diving into the technical setup, let’s understand why Cashfree is a top choice among Indian developers and businesses:

✅ Key Benefits:

  • Fast Settlements: Instant and next-day payment settlements.
  • Multiple Payment Modes: UPI, NetBanking, Cards, Wallets, Pay Later, EMI, etc.
  • Developer-Friendly APIs: Easy REST APIs with detailed documentation.
  • Recurring Billing Support: For subscription-based services.
  • Webhooks: Real-time order tracking and status updates.
  • Low Transaction Fees: Among the most competitive in the Indian market.

🔧 Prerequisites

To begin with the integration, here’s what you’ll need:

  • A Cashfree Account (Register at https://www.cashfree.com)
  • Access to Sandbox credentials (for testing)
  • A PHP-based website or application
  • cURL enabled on your server
  • Optional: MySQL Database for order tracking
  • Web Hosting (e.g., Hostinger, GoDaddy, AWS, etc.)

📝 Step 1: Create a Cashfree Sandbox Account

Before going live, you must test your integration in a sandbox environment provided by Cashfree.

🔹 How to Register:

  1. Visit: https://sandbox.cashfree.com
  2. Sign up using your business email.
  3. Complete the onboarding form.
  4. Navigate to the “Developers” > “API Keys” section.

🔹 Note down the following:

  • APP ID
  • SECRET KEY

⚠️ These credentials are used for testing only. You’ll need to switch to live credentials once you’re ready for production.


🗂️ Step 2: Set Up the File Structure

Create a simple folder structure to keep your code organized:/cashfree-integration/ │ ├── payment.php # Create and redirect to payment ├── return.php # Redirected page after payment ├── notify.php # Webhook handler └── db.php # Database connection file


💰 Step 3: Create a Payment Order (payment.php)

Here’s where we initiate a payment using Cashfree’s API and redirect the user to the payment link.<?php // payment.php require_once 'db.php'; define('CF_APP_ID', 'YOUR_SANDBOX_APP_ID'); define('CF_SECRET', 'YOUR_SANDBOX_SECRET_KEY'); define('CF_RETURN_URL', 'https://yourdomain.com/return.php'); define('CF_NOTIFY_URL', 'https://yourdomain.com/notify.php'); function createCashfreeOrder($amount, $email, $phone) { $orderId = "ORDER" . time(); $payload = [ "order_id" => $orderId, "order_amount" => $amount, "order_currency" => "INR", "customer_details" => [ "customer_id" => uniqid(), "customer_email" => $email, "customer_phone" => $phone ], "order_meta" => [ "return_url" => CF_RETURN_URL, "notify_url" => CF_NOTIFY_URL ] ]; $curl = curl_init(); curl_setopt_array($curl, [ CURLOPT_URL => "https://sandbox.cashfree.com/pg/orders", CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "Content-Type: application/json", "x-client-id: " . CF_APP_ID, "x-client-secret: " . CF_SECRET ], CURLOPT_POSTFIELDS => json_encode($payload) ]); $response = curl_exec($curl); curl_close($curl); $json = json_decode($response, true); if (!empty($json['payment_link'])) { header("Location: " . $json['payment_link']); exit; } else { echo "❌ API Error: "; print_r($json); } } createCashfreeOrder(99, "[email protected]", "9876543210");


🌐 Step 4: Handle Payment Return URL (return.php)

Cashfree redirects the customer to this page after they complete the payment.<?php // return.php echo "<h2>Thank You!</h2>"; echo "<p>Your payment was processed successfully. You’ll receive a confirmation shortly.</p>";


📩 Step 5: Handle Webhook Notifications (notify.php)

This is where Cashfree notifies you (in the background) about successful payments. You can also update the user’s status here.<?php // notify.php $input = file_get_contents("php://input"); $data = json_decode($input, true); file_put_contents("webhook_log.txt", print_r($data, true), FILE_APPEND); if ($data['event'] === "PAYMENT_SUCCESS") { $orderId = $data['data']['order']['order_id']; $paymentId = $data['data']['payment']['payment_id']; require_once 'db.php'; $sql = "UPDATE orders SET status='paid', payment_id='$paymentId' WHERE order_id='$orderId'"; mysqli_query($conn, $sql); }

🛑 Note: Always validate the webhook signature (for security) using the headers x-webhook-signature.


🗃️ Step 6: Optional – Setup a MySQL Database

Although optional, it’s a good idea to track orders in a database.

🔹 Create a table:

CREATE TABLE `orders` ( `id` INT NOT NULL AUTO_INCREMENT, `order_id` VARCHAR(255) NOT NULL, `amount` DECIMAL(10,2) NOT NULL, `email` VARCHAR(100), `phone` VARCHAR(15), `status` VARCHAR(50) DEFAULT 'pending', `payment_id` VARCHAR(255), `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) );

🔹 db.php (connection file):

<?php $conn = mysqli_connect("localhost", "username", "password", "dbname"); if (!$conn) { die("Database connection failed: " . mysqli_connect_error()); }


🔄 Step 7: Switch to Production Mode

Once you’ve fully tested the integration in sandbox mode, it’s time to go live!

🔁 Replace the following:

From (Sandbox) To (Production) https://sandbox.cashfree.com/pg/ordershttps://api.cashfree.com/pg/ordersYOUR_SANDBOX_APP_IDYOUR_LIVE_APP_IDYOUR_SANDBOX_SECRET_KEYYOUR_LIVE_SECRET_KEY

🔐 Go Live Checklist:

  • [ ] Use HTTPS everywhere.
  • [ ] Validate webhook signature.
  • [ ] Store order data securely.
  • [ ] Test with real payments in low amounts first.

⚠️ Troubleshooting Common Issues

Error Cause Fix 401 Unauthorized Invalid APP ID/Secret Check credentials Empty payment link Bad payload or missing fields Check field names and formats No webhook received Wrong notify_url or blocked server Use HTTPS and public domain Payment not updated Missing DB update logic Review notify.php logic


🛡️ Security Tips

📦 Want the Source Code?

  • Always verify webhook payloads using the HMAC signature.
  • Never expose your secret key on the frontend.
  • Sanitize and validate user input (email, phone, etc.).
  • Implement HTTPS and CORS policies on all APIs.

📈 Advanced Features You Can Add

Once basic payments are working, you can integrate:

  • Subscription Billing (for SaaS platforms)
  • Payment Link APIs
  • Split Payments (useful for marketplaces)
  • Refund APIs
  • Auto-retry for failed transactions

Refer to: Cashfree API Docs


🧩 Real-World Use Case Example

Let’s say you’re building a blogging tool where users pay ₹99/month to access AI-generated content.

  • When the user clicks “Buy Now”, you generate an order using payment.php.
  • Upon success, return.php shows the thank-you page.
  • Meanwhile, notify.php gets called in the background, and you update their account as “premium”.
  • Store order status, payment ID, and email in a database for tracking.

It’s simple, fast, and scales well with your business.


✅ Conclusion

Integrating Cashfree Payment Gateway into your PHP application is easier than you might think. With just a few API calls, you can enable secure and fast online payments for your users—whether it’s for a product, service, or subscription.

By following the steps outlined in this guide, you’re equipped with everything needed to get started—from sandbox testing to production deployment.


Like, share and comment



tags
categories
Blogging

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *