UPI Payment Integration in PHP: Order, QR and Webhook

Learn upi payment integration in php with a complete PaymentSetu flow for API orders, hosted QR checkout, signed webhooks, status checks and credits.
A blue PHP payment integration illustration with a phone, UPI QR code, rupee symbol and webhook checkmark.

UPI payment integration in PHP is a practical way to add a QR-based checkout to a custom website while keeping your order state on your own server. This guide shows the complete PaymentSetu flow: create an order, send the customer to its QR page, verify the signed webhook, and mark the order paid only after your server checks the event.

What you’ll build

The integration has two server-side paths and one customer-facing page:

  1. Your PHP application creates an order with a unique order ID and amount in paisa.
  2. PaymentSetu returns a payment_url; your application redirects the customer to it.
  3. The customer scans the QR and pays directly to your connected merchant account.
  4. PaymentSetu sends a signed JSON webhook to your PHP endpoint.
  5. Your endpoint verifies the signature, checks the order and amount, then marks the order paid once.

The QR is displayed on the hosted payment_url. You do not need to put your API key into JavaScript or manually create a QR image in the browser. PaymentSetu is a payment verification service, not a payment gateway: the payment goes to your own Paytm Business or PhonePe Business merchant account, while the service matches the payment to the order and notifies your application.

This separation matters. The browser can start the checkout, but only your server should create orders, hold the API key, accept webhooks and change fulfilment state.

What you need before starting

Prepare these items before writing the PHP endpoint:

  • A PHP website with HTTPS and the cURL extension enabled.
  • A PaymentSetu account with a connected Paytm Business or PhonePe Business merchant account.
  • An API key created in the PaymentSetu dashboard.
  • A public HTTPS webhook URL, such as https://example.com/paymentsetu/webhook.php.
  • An orders table or equivalent application storage with order_id, expected amount, payment status and transaction UTR fields.

Create your account from the PaymentSetu registration page, then review the official API documentation. Keep the key in a server environment variable or a secrets manager. Never commit it to Git, place it in a public JavaScript bundle, or print it in an error page.

PaymentSetu Pro costs ₹999 per 30 days and includes 1,000 credits. One credit represents one successful payment verified. The plan also includes the API, webhooks, dynamic QR and a unified dashboard; the pricing page shows the current plan details.

Step 1: Configure the API key and webhook

Why: every API request needs authentication, and the webhook must be registered before a payment can update your order automatically.

Store the key outside the web root. For a simple PHP deployment, an environment variable is enough:

<?php

$apiKey = getenv('PAYMENTSETU_API_KEY');

if (!$apiKey) {
    throw new RuntimeException('PaymentSetu API key is not configured.');
}

In your PaymentSetu dashboard, create an API key and configure the public URL of your webhook. The API base URL is:

https://paymentsetu.com/api

Every API call uses this header:

Authorization: Bearer YOUR_PAYMENTSETU_API_KEY

Success looks like this: a request from your PHP server reaches the API over HTTPS, while a request made from a browser cannot see the secret key. Open the webhook URL in your browser only to confirm that the route exists; the actual handler should accept POST requests and read the raw request body.

Step 2: Create an order with PHP

Why: the order ID and amount are the link between your checkout, the QR payment and the webhook event.

Use a unique ID from your own order record. Convert rupees to integer paisa before sending the request: ₹100 is 10000 paisa. The redirect_url is where the customer is sent after the hosted payment page; it is not proof that the payment succeeded.

<?php

function paymentSetuRequest(string $method, string $url, string $apiKey, ?array $body = null): array
{
    $ch = curl_init($url);

    $headers = [
        'Accept: application/json',
        'Authorization: Bearer ' . $apiKey,
    ];

    $options = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_TIMEOUT => 20,
    ];

    if ($body !== null) {
        $json = json_encode($body, JSON_THROW_ON_ERROR);
        $options[CURLOPT_POSTFIELDS] = $json;
        $options[CURLOPT_HTTPHEADER][] = 'Content-Type: application/json';
    }

    curl_setopt_array($ch, $options);
    $responseBody = curl_exec($ch);

    if ($responseBody === false) {
        throw new RuntimeException('PaymentSetu request failed: ' . curl_error($ch));
    }

    $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $response = json_decode($responseBody, true);

    if (!is_array($response)) {
        throw new RuntimeException('PaymentSetu returned invalid JSON.');
    }

    if ($httpStatus < 200 || $httpStatus >= 300 || ($response['status'] ?? false) !== true) {
        $message = $response['msg'] ?? 'PaymentSetu returned an error.';
        throw new RuntimeException($message);
    }

    return $response;
}

$apiKey = getenv('PAYMENTSETU_API_KEY');
$orderId = 'ORDER-' . bin2hex(random_bytes(8)); // Replace with your stored order ID.
$amountInPaisa = 10000; // ₹100.00

// Save the order as pending in your database before sending the request.
$result = paymentSetuRequest(
    'POST',
    'https://paymentsetu.com/api/create_order',
    $apiKey,
    [
        'order_id' => $orderId,
        'amount' => $amountInPaisa,
        'redirect_url' => 'https://example.com/payment-return',
        'customer_name' => 'Asha Sharma',
        'customer_email' => '[email protected]',
        'customer_mobile' => '9876543210',
        'remarks' => 'Order ' . $orderId,
    ]
);

header('Location: ' . $result['payment_url'], true, 303);
exit;

The PHP cURL documentation shows the same core pattern: initialise cURL, send JSON with CURLOPT_POSTFIELDS, set the JSON content type, return the response and handle transport errors.

Success looks like a JSON response with status: true and a payment_url. Save the order ID and expected amount before the redirect. If the response is an error, show a generic checkout message to the customer and log the server-side response without exposing the API key.

Important order rules:

  • Use a unique order_id for each payment intent.
  • Send amount as an integer number of paisa, not a formatted string such as ₹100.
  • Creating a payment link uses one credit.
  • If an order is already paid, do not create another payment link for it.

Step 3: Show the QR checkout to the customer

Why: the hosted payment URL gives the customer a QR checkout without exposing your API credentials or requiring a client-side API call.

The Location header in the previous step sends the customer to the returned payment_url. If your checkout uses JavaScript, keep the URL in a server-generated response and redirect the browser only after your PHP server has created the order. Do not call create_order directly from a public script with the bearer key.

Your checkout can send a normal POST request to a server-side create-order.php route:

POST /create-order.php
cart_token=YOUR_INTERNAL_CART_TOKEN

Your application should look up the cart on the server, calculate the amount from trusted product data, create the order, and then redirect to payment_url. Do not accept the payable amount only from a hidden input; a hidden field is visible to the customer and can be changed.

Success looks like the customer reaching the PaymentSetu payment page and seeing the QR for that order. The return page is useful for showing “We are checking your payment”, but it must not fulfil the order by itself. The signed webhook is the server-to-server confirmation.

Step 4: Verify the signed webhook in PHP

Why: a browser redirect or a screenshot is not a trusted payment confirmation; the webhook signature proves that the event was created with your API key and has not been changed in transit.

PaymentSetu sends these headers:

  • X-PaymentSetu-Timestamp: the Unix timestamp for the event.
  • X-PaymentSetu-Signature: the hexadecimal HMAC-SHA256 signature.

The signed message is the timestamp, a dot, and the exact raw JSON body. Read php://input before decoding JSON, because re-encoding the decoded array can change whitespace or key ordering and produce a different signature.

<?php

function verifyPaymentSetuWebhook(
    string $signature,
    string $timestamp,
    string $rawPayload,
    string $apiKey
): bool {
    if ($timestamp === '' || !ctype_digit($timestamp)) {
        return false;
    }

    // Reject old events; the API documentation uses a five-minute window.
    if (abs(time() - (int) $timestamp) > 300) {
        return false;
    }

    $expected = hash_hmac(
        'sha256',
        $timestamp . '.' . $rawPayload,
        $apiKey
    );

    return $signature !== '' && hash_equals($expected, $signature);
}

$apiKey = getenv('PAYMENTSETU_API_KEY');
$signature = $_SERVER['HTTP_X_PAYMENTSETU_SIGNATURE'] ?? '';
$timestamp = $_SERVER['HTTP_X_PAYMENTSETU_TIMESTAMP'] ?? '';
$rawPayload = file_get_contents('php://input');

if (!is_string($rawPayload) || !verifyPaymentSetuWebhook($signature, $timestamp, $rawPayload, $apiKey)) {
    http_response_code(401);
    echo json_encode(['status' => false, 'error' => 'Invalid signature']);
    exit;
}

$data = json_decode($rawPayload, true);

if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['status' => false, 'error' => 'Invalid JSON']);
    exit;
}

$orderId = (string) ($data['order_id'] ?? '');
$receivedAmount = (int) ($data['amount'] ?? 0);
$status = (string) ($data['status'] ?? '');
$utr = (string) ($data['txn_utr'] ?? '');

// Load the pending order by $orderId from your database here.
// Compare its expected amount with $receivedAmount before fulfilment.
// Store $utr and make the update idempotent so duplicate events are harmless.

if ($status === 'success' && $orderId !== '' && $utr !== '') {
    // markOrderPaidOnce($orderId, $receivedAmount, $utr);
}

http_response_code(200);
echo json_encode(['status' => true]);

The PHP hash_hmac function generates the keyed digest, and hash_equals performs a timing-safe comparison. The webhook payload includes the order ID, amount, status and transaction UTR. Use those values to find the pending order, compare the amount in paisa, and record the UTR before releasing a product, service or download.

Make markOrderPaidOnce idempotent. A safe database operation should update an order only when its current state is pending, and should keep a unique record for the UTR or webhook event. If the same webhook arrives again, return HTTP 200 without sending the fulfilment a second time.

Step 5: Check payment status from the server

Why: status checks give your return page or a scheduled reconciliation task a second server-side view of an order; they are not a replacement for webhook verification.

The integration brief exposes this endpoint:

GET /api/order_status/{client_txn_id}

Call it from PHP with the same bearer header. URL-encode the transaction identifier and never put the API key in the browser:

<?php

$clientTxnId = 'ORDER-abc123'; // Use the identifier stored for this payment.
$url = 'https://paymentsetu.com/api/order_status/' . rawurlencode($clientTxnId);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPGET => true,
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Authorization: Bearer ' . getenv('PAYMENTSETU_API_KEY'),
    ],
    CURLOPT_TIMEOUT => 20,
]);

$responseBody = curl_exec($ch);

if ($responseBody === false) {
    throw new RuntimeException(curl_error($ch));
}

$httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$statusResponse = json_decode($responseBody, true);

if ($httpStatus >= 200 && $httpStatus < 300 && is_array($statusResponse)) {
    // Inspect the documented response for this order and reconcile locally.
    error_log(json_encode($statusResponse));
}

Use the webhook as the normal event path. A status check is useful when the customer returns before the webhook handler finishes or when you are reconciling pending records. Your application should still validate that the returned identifier and amount belong to the local order before changing state.

Step 6: Monitor credits with PHP

Why: each payment link creation consumes one credit, so a small server-side check helps you see whether the account can create more links.

The credits endpoint needs no request body:

<?php

$ch = curl_init('https://paymentsetu.com/api/check_credits');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPGET => true,
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Authorization: Bearer ' . getenv('PAYMENTSETU_API_KEY'),
    ],
    CURLOPT_TIMEOUT => 20,
]);

$responseBody = curl_exec($ch);

if ($responseBody === false) {
    throw new RuntimeException(curl_error($ch));
}

curl_close($ch);

$result = json_decode($responseBody, true);
$remaining = $result['credits']['remaining_credits'] ?? null;

if (($result['status'] ?? false) === true && is_int($remaining)) {
    echo 'Remaining credits: ' . $remaining;
}

The response contains remaining, total and used credits, along with subscription status and expiry information. Display the count in an admin-only page or log it for operations; do not expose the API key or private account details to customers.

Verify the complete PHP flow

Run through one low-value test order before connecting fulfilment:

  1. Submit your checkout form and confirm that your server stores a pending order.
  2. Confirm that create_order returns status: true and a payment_url.
  3. Scan the QR and complete the UPI payment from the customer side.
  4. Check your webhook logs for the raw body, timestamp and signature headers. Do not log the API key.
  5. Confirm that the signature passes before JSON business logic runs.
  6. Confirm that the local order ID and paisa amount match the webhook.
  7. Confirm that the order becomes paid once and stores the UTR.
  8. Replay the same event in a safe test environment and verify that it does not fulfil twice.
  9. Use the status endpoint to reconcile the order, then check the credits endpoint from an admin-only command or page.

Troubleshooting common PHP integration errors

curl_exec returns false

Check that the PHP cURL extension is enabled, the server can make outbound HTTPS requests, and the host has a valid CA certificate bundle. Log curl_error($ch) on the server, but show the customer a short retry message rather than the internal error.

The API rejects the amount

Send an integer in paisa. For example, ₹249 becomes 24900; do not send 249, "₹249", or a value with a comma. Calculate the amount from trusted server-side order data.

The webhook says “Invalid signature”

Verify that you are using the exact raw body, the same API key, the timestamp string from the header, and the message format timestamp.payload. Do not run json_encode on the decoded payload before hashing. Also check that your server clock is accurate and that your web server passes the X-PaymentSetu-* headers to PHP.

The customer returns but the order is still pending

The return URL is only a navigation step. Check the webhook handler logs, confirm that the endpoint is public over HTTPS, and use the server-side status endpoint for reconciliation. Keep the order pending until a verified event or trusted status response matches the local order.

A webhook fulfils the same order twice

Add a database guard around the paid transition and store the transaction UTR with a unique constraint. Process only a pending order; if it is already paid, acknowledge the event and stop before sending another email, download or service activation.

FAQ

Can I integrate UPI payments in a plain PHP website?

Yes. A plain PHP site can use cURL to create an order, redirect to the returned payment URL and receive the webhook on a PHP route. You do not need WordPress, WooCommerce or a framework for the API flow.

Is PaymentSetu a payment gateway for PHP?

No. PaymentSetu is a payment verification service. The customer pays directly into your connected Paytm Business or PhonePe Business merchant account, and PaymentSetu matches the transaction and sends your server a webhook.

Should I trust the payment return URL or a screenshot?

No. Treat both as customer-facing signals only. Verify the HMAC-signed webhook, match the order ID and amount, and make the database update idempotent before fulfilling the order.

What amount format does the PHP API use?

The amount field is an integer in paisa, so 100 paisa equals ₹1 and 10000 paisa equals ₹100. Convert and validate the amount on your server before calling POST /api/create_order.

How many credits does a PHP order use?

Each payment link creation consumes one credit. You can call GET /api/check_credits with your bearer API key to read the remaining, total and used credit counts.

DONE upi-payment-integration-php words=1915

Previous Article

NEFT vs RTGS vs UPI: Which Should Your Business Use?

Next Article

Paytm Business QR Code: Get, Print and Use It

Write a Comment

Leave a Comment

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