2024-08-06

How to Integrate Cashfree Payment Gateway in PHP with UPI Intent

Integrating the Cashfree Payment Gateway in PHP for UPI Intent is a straightforward process. This guide will walk you through the steps to set up the integration, including creating orders, handling callbacks, and checking order statuses.

Imdad

Imdadullah Babu

Full Stack Developer

[object Object]

Prerequisites

Before you begin, make sure you have:

  1. PHP installed on your server.
  2. A Cashfree account with client ID and client secret.
  3. Basic knowledge of PHP and JavaScript.

Order of Execution: The files should be executed in the following order:

  • order.php
  • intent.php
  • return.php
  • callback.php
  • check.php (optional)

Tailwind Play CDN: This integration uses Tailwind Play CDN for styling. Ensure you include the Tailwind CSS script in your project for proper styling.

Setting Up Your PHP Files

Create a file: order.php

This file is responsible for creating orders with Cashfree. It sets up the order details and sends a request to Cashfree to create a payment session.

1<?php
2
3date_default_timezone_set("Asia/Kolkata");
4
5$cashfreeBaseUrl = "https://api.cashfree.com/pg/";
6$notifyURL = "NOTIFY_URL";
7$returnURL = "RETURN_URL";
8
9if (isset($_GET['order_id'])) {
10    $clientId = "YOUR_CLIENT_ID";
11    $clientSecret = "YOUR_CLIENT_SECRET";
12    $order_id = $_GET['order_id']; // Get your order ID
13    
14    $customer_id = $_GET['customer_id']; // Get customer ID
15    $user_name = $_GET['user_name']; // Get customer name
16    $user_email = $_GET['user_email']; // Get customer email
17    $user_number = $_GET['user_number']; // Get customer phone number
18    $amount = $_GET['amount']; // Get order amount
19    
20    $data = createOrder($clientId, $clientSecret, $order_id, $customer_id, $user_name, $user_email, $user_number, $amount);
21    $session = $data['session'];
22    echo json_encode($data);
23}
24
25function createExpiryTime()
26{
27    return date_format(date_timestamp_set(new DateTime(), strtotime("+16 Minutes", strtotime(date('Y-m-d H:i:s')))), 'c');
28}
29
30function requestWithHeader($url, $headers, $data)
31{
32    $curl = curl_init($url);
33    curl_setopt($curl, CURLOPT_URL, $url);
34    curl_setopt($curl, CURLOPT_POST, true);
35    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
36    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
37    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, true));
38
39    $resp = curl_exec($curl);
40    curl_close($curl);
41    return $resp;
42}
43
44function createOrder($clientId, $clientSecret, $orderId, $customerId, $name, $email, $number, $amount)
45{
46    global $cashfreeBaseUrl, $notifyURL, $returnURL;
47    $headers = array(
48        "Accept: application/json",
49        "Content-Type: application/json",
50        "x-api-version: 2022-09-01",
51        "x-client-id: $clientId",
52        "x-client-secret: $clientSecret",
53    );
54
55    $postData = array();
56    $postData['customer_details']['customer_id'] = $customerId;
57    $postData['customer_details']['customer_name'] = $name;
58    $postData['customer_details']['customer_email'] = $email;
59    $postData['customer_details']['customer_phone'] = $number;
60    $postData['order_meta']['return_url'] = $returnURL.'?orderId={order_id}';
61    $postData['order_meta']['notify_url'] = $notifyURL;
62    $postData['order_meta']['payment_methods'] = "upi";
63    $postData['order_amount'] = $amount;
64    $postData['order_id'] = $orderId;
65    $postData['order_currency'] = "INR";
66    $postData['order_expiry_time'] = createExpiryTime();
67    $response = requestWithHeader($cashfreeBaseUrl . 'orders', $headers, $postData);
68    $response = json_decode($response, true);
69
70    $arr = array();
71    $arr['status'] = isset($response['payment_session_id']);
72    $arr['session'] = isset($response['payment_session_id']) ? $response['payment_session_id'] : "Session";
73    return $arr;
74}
75?>

Create a file: intent.php

This file handles the UPI payment intent using Cashfree's JavaScript SDK. It mounts the UPI app for payment.

1<?php
2if (!isset($_GET['session'])) {
3  echo "Unauthorized access";
4  exit;
5}
6?>
7
8<!DOCTYPE html>
9<html lang="en">
10<head>
11  <meta charset="UTF-8">
12  <meta name="viewport" content="width=device-width, initial-scale=1.0, userScalable=no" />
13  <title>Pay Now</title>
14  <script src="./tailwind.js"></script>
15</head>
16<body>
17  <div class="h-screen w-screen md:hidden ">
18    <div class="rounded-none py-3">
19      <div class="flex flex-col items-center">
20        <div class="logo m-auto mb-5 bg-white w-[100px] h-[100px] p-3 border rounded-full overflow-hidden">
21          <!-- Add an image or logo -->
22          <img src="/assets/upi.png" alt="">
23        </div>
24        <h2 class="font-bold text-md text-center mb-2">
25          Complete your payment
26        </h2>
27        <p class="text-[13px] text-center px-3">
28          Please select your preferred payment app from the options provided
29          in the pop-up, proceed with your payment, and return here once
30          your transaction is complete.
31        </p>
32      </div>
33    </div>
34    <div id="intent" class="invisible absolute"></div>
35    <div class="p-3">
36      <button id="pay" class="w-full dark:bg-zinc-900 border border-white text-white py-3 rounded-md hidden">Pay Now</button>
37    </div>
38    <div id="Cerror" class="mx-3 text-white p-2 bg-red-500 rounded-md hidden"></div>
39  </div>
40
41  <script src="https://sdk.cashfree.com/js/v3/cashfree.js"></script>
42  <script>
43    let cashfree = Cashfree({
44      mode: "production",
45    });
46
47    let upiApp = cashfree.create("upiApp", {
48      values: {
49        upiApp: "web",
50        buttonIcon: false,
51      },
52    });
53
54    upiApp.on("loaderror", function(data) {
55      Cerror.style.display = "block";
56      pay.style.display = "none";
57      Cerror.innerHTML = data.error.message;
58    });
59
60    upiApp.mount("#intent");
61
62    upiApp.on("ready", function(d) {
63      pay.style.display = "block";
64      pay.click();
65    });
66
67    document.getElementById("pay").addEventListener("click", function() {
68      let paymentPromise = cashfree.pay({
69        paymentMethod: upiApp,
70        paymentSessionId: "<?= $_GET['session']; ?>",
71      });
72      paymentPromise.then(function(result) {
73        window.parent.postMessage("Payment triggered", "*");
74      });
75    });
76  </script>
77</body>
78</html>

Create a file: return.php

This file is a placeholder that informs the user to wait while the payment is being processed. It redirects to a specified endpoint once the payment process is complete.

1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <meta name="viewport" content="width=device-width, initial-scale=1.0">
6    <title>Please Wait...</title>
7    <script src="./tailwind.js"></script>
8    <style>
9        @keyframes spin {
10            0% { transform: rotate(0deg); }
11            100% { transform: rotate(360deg); }
12        }
13        .spin {
14            animation: spin 1s linear infinite;
15        }
16    </style>
17</head>
18<body class="flex items-center justify-center mt-12 bg-gray-100">
19    <div class="flex flex-col items-center">
20        <div class="loader border-t-4 border-blue-500 rounded-full w-16 h-16 spin"></div>
21        <p class="mt-4 text-lg text-gray-700">Do not close the app</p>
22    </div>
23    <script>
24        location.replace('YOUR_ENDPOINT')
25    </script>
26</body>
27</html>

Create a file: callback.php

This file handles the callback from Cashfree after the payment is completed. It checks the payment status and returns a success or failure message.

1<?php
2
3if ($_SERVER['REQUEST_METHOD'] === 'POST') {
4    $postData = file_get_contents('php://input');
5    $data = json_decode($postData, true);
6
7    if($data['payment']['payment_status'] == "SUCCESS"){
8        $payment_id = $data['payment']['cf_payment_id'];
9        $bank_reference = $data['payment']['bank_reference'];
10        echo "Payment Successful";
11    } else{
12        echo "Payment Pending or Failed";
13    }
14} else {
15    echo 'This script only accepts POST requests.';
16}
17?>

Create a file: check.php

This optional file checks the order status using the order ID. It can be used to verify the payment status.

1<?php
2if (isset($_GET['order_id'])) {
3    $orderId = $_GET['order_id'];
4    $apiUrl = "https://api.cashfree.com/pg/orders/{$orderId}";
5
6    $headers = array(
7        'x-api-version: 2023-08-01',
8        'x-client-id: ' . 'YOUR_CLIENT_ID',
9        'x-client-secret: ' . 'YOUR_CLIENT_SECRET',
10        'Content-Type: application/json'
11    );
12
13    $ch = curl_init();
14    curl_setopt($ch, CURLOPT_URL, $apiUrl);
15    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
16    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
17    $response = curl_exec($ch);
18    echo $response;
19}
20?>

By following these steps, you can successfully integrate the Cashfree Payment Gateway with UPI Intent in your PHP application. This setup will allow you to handle payments efficiently and provide a smooth user experience for your customers.

Share with your friends

IMDOS.IN

© 2024 IMDOS | All right reserved