A complete step-by-step guide to PhonePe payment gateway integration in PHP using the v2 Backend SDK, including order creation, status verification, UPI intent, and webhooks.
Imdadullah BabuDesigner & Developer
Integrating digital payments into web applications requires speed, security, and absolute reliability. For platforms targeting Indian users, PhonePe is one of the most widely used payment providers. While PhonePe provides official SDKs, many production environments—including legacy codebases, microservices, and light shared servers—prefer dependency-free phonepe payment gateway integration using native PHP and cURL without standard package managers like Composer.
Using raw REST API endpoints gives you total control over the execution stack, eliminates heavy vendor directories, and guarantees full compatibility across PHP 8.0+.
In this guide, we will implement direct REST API integrations for PhonePe using native PHP. We will build a complete workflow comprising a MySQL database schema and five zero-dependency scripts: config.php, order.php, status.php, intent.php, and callback.php.
Key takeaways
- Zero External Dependencies: Standard cURL and PHP's native OpenSSL/Hash functions handle all HTTP requests and SHA256 checksum signatures.
- Paisa Precision: Amounts must always be converted to an integer in paisa (₹1 = 100 paisa, minimum 100 paisa).
- X-VERIFY Signature Verification: Every API call and incoming webhook payload must be signed and validated using
SHA256(payload + endpoint + salt_key) + "###" + salt_index. - Server Verification: Never trust front-end redirects alone; always query PhonePe server-to-server using the status endpoint.
- Idempotency: Webhook listeners must verify order states in your database before executing state updates to prevent double fulfillment.
Architecture and Database Setup
Database Schema (schema.sql)
Before running payment scripts, create a dedicated table to persist transaction states. This table acts as the source of truth for idempotency checks.
CREATE TABLE IF NOT EXISTS `orders` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`merchant_transaction_id` VARCHAR(64) NOT NULL UNIQUE,
`phonepe_transaction_id` VARCHAR(64) DEFAULT NULL,
`amount` INT NOT NULL COMMENT 'Amount in paisa',
`status` VARCHAR(20) NOT NULL DEFAULT 'PENDING',
`customer_phone` VARCHAR(15) DEFAULT NULL,
`payment_mode` VARCHAR(50) DEFAULT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`updated_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Central Credentials and HTTP Helper (config.php)
PhonePe REST APIs use an X-VERIFY header for request authentication. The signature format for API payloads is:
$$\text{SHA256}(\text{Base64 Payload} + \text{Endpoint} + \text{Salt Key}) + \text{"###"} + \text{Salt Index}$$
Create config.php to manage credentials, database connections via PDO, and HTTP cURL requests.
<?php
// config.php
// PhonePe Sandbox / Testing Credentials
define('PHONEPE_MERCHANT_ID', 'PGTESTPAYUAT');
define('PHONEPE_SALT_KEY', '099eb0cd-02cf-4e2a-8aca-3e6c6aff0399');
define('PHONEPE_SALT_INDEX', '1');
// Environment Endpoints
// Sandbox: https://api-preprod.phonepe.com/apis/pg-sandbox
// Production: https://api.phonepe.com/apis/hermes
define('PHONEPE_BASE_URL', 'https://api-preprod.phonepe.com/apis/pg-sandbox');
// Callback & Redirect URLs
define('PHONEPE_CALLBACK_URL', 'https://yourdomain.com/callback.php');
define('PHONEPE_REDIRECT_URL', 'https://yourdomain.com/status.php');
// Database Credentials
define('DB_HOST', '127.0.0.1');
define('DB_USER', 'root');
define('DB_PASS', 'secret');
define('DB_NAME', 'store_db');
/**
* Shared PDO instance generator
*/
function getDbConnection(): PDO {
static $pdo = null;
if ($pdo === null) {
$dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4";
$pdo = new PDO($dsn, DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
return $pdo;
}
/**
* Generic cURL wrapper for PhonePe REST API execution
*/
function sendPhonePeApiRequest(string $endpoint, string $payloadBase64 = '', string $method = 'POST'): array {
$checksum = hash('sha256', $payloadBase64 . $endpoint . PHONEPE_SALT_KEY) . '###' . PHONEPE_SALT_INDEX;
$headers = [
'Content-Type: application/json',
'X-VERIFY: ' . $checksum,
'accept: application/json'
];
$ch = curl_init(PHONEPE_BASE_URL . $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if ($method === 'POST' && !empty($payloadBase64)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(['request' => $payloadBase64]));
}
$response = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
throw new Exception("cURL Transport Error: " . $curlError);
}
return json_decode($response, true) ?? [];
}
Step-by-Step REST API Implementation
1. Initiating Standard Checkout (order.php)
This script constructs the order payload, encodes it to Base64, calculates the X-VERIFY header, saves a PENDING order record in MySQL, and redirects the browser to PhonePe's hosted payment engine.
<?php
// order.php
require_once __DIR__ . '/config.php';
try {
$rawAmount = 499.00; // Amount in INR
$amountInPaisa = (int) round($rawAmount * 100);
$customerPhone = "9876543210";
// Generate unique alphanumeric transaction ID (max 63 chars)
$merchantTransactionId = "MT_" . time() . "_" . rand(1000, 9999);
$merchantUserId = "MUID_" . rand(100, 999);
if ($amountInPaisa < 100) {
throw new Exception("Minimum amount must be ₹1.00 (100 paisa).");
}
// 1. Insert initial pending record into Database
$db = getDbConnection();
$stmt = $db->prepare("INSERT INTO orders (merchant_transaction_id, amount, status, customer_phone) VALUES (?, ?, 'PENDING', ?)");
$stmt->execute([$merchantTransactionId, $amountInPaisa, $customerPhone]);
// 2. Build API Request Body
$payloadArray = [
"merchantId" => PHONEPE_MERCHANT_ID,
"merchantTransactionId" => $merchantTransactionId,
"merchantUserId" => $merchantUserId,
"amount" => $amountInPaisa,
"redirectUrl" => PHONEPE_REDIRECT_URL . "?id=" . urlencode($merchantTransactionId),
"redirectMode" => "REDIRECT",
"callbackUrl" => PHONEPE_CALLBACK_URL,
"mobileNumber" => $customerPhone,
"paymentInstrument" => [
"type" => "PAY_PAGE"
]
];
$payloadBase64 = base64_encode(json_encode($payloadArray, JSON_UNESCAPED_SLASHES));
$endpoint = '/pg/v1/pay';
// 3. Send request to PhonePe API
$response = sendPhonePeApiRequest($endpoint, $payloadBase64, 'POST');
// 4. Redirect customer to PhonePe payment URL
if (isset($response['success']) && $response['success'] === true) {
$redirectUrl = $response['data']['instrumentResponse']['redirectInfo']['url'] ?? null;
if ($redirectUrl) {
header("Location: " . $redirectUrl);
exit;
}
}
$errorMessage = $response['message'] ?? 'Unknown gateway error during initialization.';
throw new Exception("PhonePe API Error: " . $errorMessage);
} catch (Exception $e) {
http_response_code(500);
echo "Payment Execution Error: " . htmlspecialchars($e->getMessage());
}
2. Checking Order Status Server-Side (status.php)
When the transaction finishes, PhonePe redirects the user back to your site. This script queries PhonePe's server directly via GET request to verify transaction state before displaying the result to the user.
Checksum note for GET status endpoint: The signature formula for GET status is
SHA256("/pg/v1/status/{merchantId}/{merchantTransactionId}" + saltKey) + "###" + saltIndex.
<?php
// status.php
require_once __DIR__ . '/config.php';
$merchantTransactionId = $_GET['id'] ?? null;
if (!$merchantTransactionId) {
http_response_code(400);
die("Error: Missing transaction parameter.");
}
// Sanitize parameter
$merchantTransactionId = preg_replace('/[^a-zA-Z0-9_\-]/', '', $merchantTransactionId);
try {
$endpoint = '/pg/v1/status/' . PHONEPE_MERCHANT_ID . '/' . $merchantTransactionId;
// Status Checksum: SHA256(endpoint + saltKey) + ### + saltIndex
$checksum = hash('sha256', $endpoint . PHONEPE_SALT_KEY) . '###' . PHONEPE_SALT_INDEX;
$headers = [
'Content-Type: application/json',
'X-VERIFY: ' . $checksum,
'X-MERCHANT-ID: ' . PHONEPE_MERCHANT_ID,
'accept: application/json'
];
$ch = curl_init(PHONEPE_BASE_URL . $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$rawResponse = curl_exec($ch);
curl_close($ch);
$response = json_decode($rawResponse, true);
$code = $response['code'] ?? 'UNKNOWN';
$phonepeTxnId = $response['data']['transactionId'] ?? null;
// Database state synchronization
$db = getDbConnection();
if ($code === 'PAYMENT_SUCCESS') {
$stmt = $db->prepare("UPDATE orders SET status = 'COMPLETED', phonepe_transaction_id = ? WHERE merchant_transaction_id = ?");
$stmt->execute([$phonepeTxnId, $merchantTransactionId]);
$statusText = "Payment Successful";
$cssClass = "success";
} elseif ($code === 'PAYMENT_PENDING') {
$statusText = "Payment Pending";
$cssClass = "pending";
} else {
$stmt = $db->prepare("UPDATE orders SET status = 'FAILED', phonepe_transaction_id = ? WHERE merchant_transaction_id = ?");
$stmt->execute([$phonepeTxnId, $merchantTransactionId]);
$statusText = "Payment Failed";
$cssClass = "failed";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Order Verification</title>
<style>
body { font-family: system-ui, sans-serif; background: #f9fafb; padding: 2rem; }
.box { background: #fff; max-width: 480px; margin: 0 auto; padding: 2rem; border-radius: 8px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.success { color: #166534; } .pending { color: #854d0e; } .failed { color: #991b1b; }
</style>
</head>
<body>
<div class="box">
<h2 class="<?php echo $cssClass; ?>"><?php echo $statusText; ?></h2>
<p><strong>Merchant Order ID:</strong> <?php echo htmlspecialchars($merchantTransactionId); ?></p>
<?php if ($phonepeTxnId): ?>
<p><strong>PhonePe Ref ID:</strong> <?php echo htmlspecialchars($phonepeTxnId); ?></p>
<?php endif; ?>
</div>
</body>
</html>
<?php
} catch (Exception $e) {
http_response_code(500);
echo "Status Error: " . htmlspecialchars($e->getMessage());
}
3. Native Mobile UPI Intent (intent.php)
UPI Intent bypasses hosted web checkouts on mobile browsers by returning a direct UPI URI link (upi://pay?...). This link opens installed mobile UPI apps (such as PhonePe, Paytm, or Google Pay) directly.
<?php
// intent.php
require_once __DIR__ . '/config.php';
header('Content-Type: application/json');
try {
$rawAmount = $_POST['amount'] ?? 100.00;
$targetApp = $_POST['target_app'] ?? 'PHONEPE'; // e.g., PHONEPE, GPAY, PAYTM
$amountInPaisa = (int) round(((float)$rawAmount) * 100);
$merchantTransactionId = "INT_" . time() . "_" . rand(1000, 9999);
$merchantUserId = "MUID_" . rand(100, 999);
// Save PENDING status in DB
$db = getDbConnection();
$stmt = $db->prepare("INSERT INTO orders (merchant_transaction_id, amount, status) VALUES (?, ?, 'PENDING')");
$stmt->execute([$merchantTransactionId, $amountInPaisa]);
// Construct Payload for UPI Intent
$payloadArray = [
"merchantId" => PHONEPE_MERCHANT_ID,
"merchantTransactionId" => $merchantTransactionId,
"merchantUserId" => $merchantUserId,
"amount" => $amountInPaisa,
"callbackUrl" => PHONEPE_CALLBACK_URL,
"paymentInstrument" => [
"type" => "UPI_INTENT",
"targetApp" => $targetApp
]
];
$payloadBase64 = base64_encode(json_encode($payloadArray, JSON_UNESCAPED_SLASHES));
$response = sendPhonePeApiRequest('/pg/v1/pay', $payloadBase64, 'POST');
if (isset($response['success']) && $response['success'] === true) {
$intentUrl = $response['data']['instrumentResponse']['intentUrl'] ?? null;
echo json_encode([
"status" => "SUCCESS",
"merchantTransactionId" => $merchantTransactionId,
"intentUrl" => $intentUrl
]);
exit;
}
echo json_encode([
"status" => "FAILED",
"message" => $response['message'] ?? "Failed to generate Intent URI"
]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode([
"status" => "ERROR",
"message" => $e->getMessage()
]);
}
4. Handling Webhooks Securely (callback.php)
PhonePe sends an asynchronous HTTP POST notification to your PHONEPE_CALLBACK_URL when an order settles. Your endpoint must verify the request signature before modifying database states.
The callback payload contains a JSON wrapper: {"response": "BASE64_STRING"}. PhonePe sends the checksum header X-VERIFY, which matches SHA256(BASE64_STRING + salt_key) + "###" + salt_index.
<?php
// callback.php
require_once __DIR__ . '/config.php';
// 1. Capture Raw Post Body and Headers
$rawInput = file_get_contents('php://input');
$headers = getallheaders();
// Account for potential case variations in HTTP headers
$receivedXVerify = $headers['X-VERIFY'] ?? $headers['x-verify'] ?? '';
if (empty($rawInput)) {
http_response_code(400);
echo json_encode(["status" => "FAILED", "reason" => "Empty body"]);
exit;
}
$decodedWrapper = json_decode($rawInput, true);
$base64Response = $decodedWrapper['response'] ?? '';
if (empty($base64Response)) {
http_response_code(400);
echo json_encode(["status" => "FAILED", "reason" => "Missing response string"]);
exit;
}
// 2. Validate X-VERIFY Signature
$computedSignature = hash('sha256', $base64Response . PHONEPE_SALT_KEY) . '###' . PHONEPE_SALT_INDEX;
if (!hash_equals($computedSignature, $receivedXVerify)) {
// Log invalid webhook attempt
error_log("PhonePe Webhook Signature Mismatch! Expected: {$computedSignature}, Got: {$receivedXVerify}");
http_response_code(401);
echo json_encode(["status" => "FAILED", "reason" => "Invalid Signature"]);
exit;
}
// 3. Decode the Base64 Transaction Content
$transactionData = json_decode(base64_decode($base64Response), true);
$code = $transactionData['code'] ?? 'FAILED';
$merchantTransactionId = $transactionData['data']['merchantTransactionId'] ?? null;
$phonepeTxnId = $transactionData['data']['transactionId'] ?? null;
if ($merchantTransactionId) {
$db = getDbConnection();
// 4. Idempotency Check: Retrieve order state before executing updates
$stmt = $db->prepare("SELECT status FROM orders WHERE merchant_transaction_id = ?");
$stmt->execute([$merchantTransactionId]);
$existingOrder = $stmt->fetch();
if ($existingOrder && $existingOrder['status'] !== 'COMPLETED') {
$newStatus = ($code === 'PAYMENT_SUCCESS') ? 'COMPLETED' : 'FAILED';
$updateStmt = $db->prepare("UPDATE orders SET status = ?, phonepe_transaction_id = ? WHERE merchant_transaction_id = ?");
$updateStmt->execute([$newStatus, $phonepeTxnId, $merchantTransactionId]);
if ($newStatus === 'COMPLETED') {
// Trigger local business logic (fulfillment, notification dispatch)
error_log("Order {$merchantTransactionId} marked COMPLETED via Webhook.");
}
}
}
// 5. Acknowledge notification receipt
http_response_code(200);
echo json_encode(["status" => "SUCCESS", "message" => "Webhook processed successfully"]);
Production Deployment Checklist
Before taking your direct REST API integration live:
- Environment Endpoint: Change
PHONEPE_BASE_URLinconfig.phpfromhttps://api-preprod.phonepe.com/apis/pg-sandboxtohttps://api.phonepe.com/apis/hermes. - Production Keys: Replace
PHONEPE_MERCHANT_ID,PHONEPE_SALT_KEY, andPHONEPE_SALT_INDEXwith your live merchant credentials from the PhonePe dashboard. - HTTPS Enforcement: Ensure
PHONEPE_CALLBACK_URLandPHONEPE_REDIRECT_URLuse strictly valid HTTPS certificates. PhonePe will reject non-SSL webhook targets. - Idempotency Safeguards: Verify that receiving multiple webhook calls for the same order ID does not result in duplicated state execution or inventory subtractions.
Frequently asked questions
Why use direct cURL instead of the PhonePe PHP SDK?
Using native cURL eliminates reliance on third-party SDK dependencies and Composer runtime overhead. It allows you to maintain full visibility over signature calculations and simplifies deployment across standard shared hosting or customized microservice environments.
How do I handle pending payment statuses?
When PhonePe returns PAYMENT_PENDING, leave the order in a PENDING state in your database. Do not force the status to failed immediately, as bank settlements for UPI transactions can take several minutes. Depend on incoming events via callback.php or query the status endpoint via a background CRON job to sync states.
What is the maximum length of a merchantTransactionId?
PhonePe allows a maximum length of 63 characters for merchantTransactionId. Supported characters are alphanumeric values, hyphens (-), and underscores (_).
How do I verify webhook authenticity without SDK helpers?
PhonePe supplies an X-VERIFY HTTP header with every webhook payload. Compute the SHA256 hash of the raw Base64 string in $_POST['response'] combined with your PHONEPE_SALT_KEY, append "###" and your PHONEPE_SALT_INDEX, and use hash_equals() to compare the computed hash against the header value.
- #PHP
- #PhonePe
- #Payment Gateway
- #API Integration
- #Backend
Working on something similar?
We help teams design, build and scale software like this. Tell us about your project.
Start a projectKeep reading

How to Use Claude Ship AI Code Review in GitHub PRs
Following Anthropic's historic Nasdaq debut, the launch of Claude Ship introduces autonomous GitHub agents for code reviews, policy enforcement, and PR approvals.

Android Target API 36 Migration: NDK & Layout Guide
A practical engineering guide to migrating Android apps to Target API 36. Rebuild NDK binaries for 16KB memory page alignment, fix broken edge-to-edge layouts, and automate CI verification.
By Imdadullah Babu
iOS 27.3 Developer Features: Siri Actions and AI Integration
iOS 27.3 Developer Features: Siri Actions and AI Integration
Discover how iOS 27.3's new Siri AI and Health API capabilities allow developers to build more integrated, context-aware mobile experiences.
By Imdadullah Babu