Integrating digital payments inside a Telegram bot using Telegram Stars (XTR) looks simple on paper: you dispatch an invoice using sendInvoice, respond to a confirmation check, and grant the purchased digital item when a successful payment payload arrives. However, naïve implementations frequently introduce high-severity failure modes.

If your PHP backend assumes that a successful_payment payload is authentic without backend payload verification, malicious users can spoof requests or trigger duplicate resource grants. If your server drops or fails to answer a pre_checkout_query within Telegram's strict 10-second window, the user interface locks up with a permanent loading spinner. Furthermore, if your application processes webhook updates without database-level locks, automatic retry mechanisms from Telegram can cause duplicate fulfillments for a single payment charge.

In this tutorial, we will build a production-grade Telegram Stars backend in pure PHP. We will trace the complete transaction lifecycle, dissect common architectural flaws, and implement secure payload signing, pre-checkout verification, and idempotent database handlers.

Constructing Tamper-Proof Invoices with XTR Currency

When initiating a payment for digital goods in Telegram, your bot calls the sendInvoice API method. Telegram Stars use the fixed ISO-4217 currency code XTR. Unlike standard fiat currencies (where 100 represents 1.00 USD in cents), 1 unit of XTR corresponds directly to 1 Telegram Star.

The critical vulnerability at this stage is payload tampering. The payload parameter is an arbitrary string attached to the invoice. It travels to Telegram's servers and returns untouched in both pre_checkout_query and successful_payment updates. If you pass unverified string values like order_id=452 in plain text without a cryptographic signature, an attacker who intercepts or predicts payload formatting might attempt to manipulate order metadata.

To prevent payload forgery, combine your internal database order ID with an HMAC hash calculated from your bot token. Save the pending order record in your database before invoking sendInvoice.

Here is how to create a signed invoice payload and dispatch it via native cURL in PHP:

<?php declare(strict_types=1); function sendStarsInvoice( string $botToken, int $chatId, string $orderId, string $itemTitle, string $itemDescription, int $starAmount ): array { $url = "https://api.telegram.org/bot{$botToken}/sendInvoice"; // Create a cryptographically signed payload $signature = hash_hmac('sha256', $orderId, $botToken); $payloadData = json_encode([ 'order_id' => $orderId, 'sig' => $signature ]); $body = [ 'chat_id' => $chatId, 'title' => $itemTitle, 'description' => $itemDescription, 'payload' => $payloadData, 'currency' => 'XTR', 'prices' => [ [ 'label' => $itemTitle, 'amount' => $starAmount ] ] ]; $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_POSTFIELDS => json_encode($body), CURLOPT_TIMEOUT => 10, ]); $response = curl_exec($ch); if ($response === false) { $error = curl_error($ch); curl_close($ch); throw new RuntimeException("cURL execution failed: {$error}"); } $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode !== 200) { throw new RuntimeException("Telegram API HTTP status {$httpCode}: {$response}"); } $decoded = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE || !isset($decoded['ok']) || $decoded['ok'] !== true) { $msg = $decoded['description'] ?? 'Unknown API error'; throw new RuntimeException("Telegram API returned failure: {$msg}"); } return $decoded['result']; } 

Notice the strict HTTP status code check and json_last_error() validation. Never assume a cURL call succeeded merely because $response is non-empty. If Telegram returns an error (such as an invalid currency or malformed payload), your backend must handle it before marking the local order state.

Handling Pre-Checkout Queries to Prevent Out-of-Stock Fulfillments

When a user taps the pay button inside Telegram, Telegram sends a pre_checkout_query update to your bot webhook. This is your backend's final opportunity to validate whether the transaction should proceed before the user's Stars are deducted.

You must answer this query within 10 seconds by invoking answerPreCheckoutQuery. If your server throws an uncaught exception, times out, or fails to respond, Telegram will abort the transaction, leaving the user with an uninformative error dialog.

During pre_checkout_query processing, your PHP application must execute three validation steps:

  1. Payload Signature Verification: Decode the JSON payload and verify that hash_hmac('sha256', $orderId, $botToken) matches the provided signature.
  2. Database Order Inspection: Fetch the corresponding order record from your database using a SELECT ... FOR UPDATE query to prevent concurrent state changes.
  3. Price and Currency Integrity: Assert that query.currency is strictly 'XTR' and query.total_amount equals the star_amount stored in your local DB record.

Here is the PHP handler for the pre_checkout_query update:

<?php declare(strict_types=1); function handlePreCheckoutQuery(PDO $pdo, string $botToken, array $query): void { $queryId = $query['id']; $currency = $query['currency'] ?? ''; $totalAmount = (int)($query['total_amount'] ?? 0); $rawPayload = $query['invoice_payload'] ?? ''; $payload = json_decode($rawPayload, true); if (json_last_error() !== JSON_ERROR_NONE || !isset($payload['order_id'], $payload['sig'])) { answerPreCheckout($botToken, $queryId, false, "Invalid invoice payload payload structural schema."); return; } // Verify HMAC signature integrity $expectedSig = hash_hmac('sha256', $payload['order_id'], $botToken); if (!hash_equals($expectedSig, $payload['sig'])) { answerPreCheckout($botToken, $queryId, false, "Security check failed: payload signature invalid."); return; } if ($currency !== 'XTR') { answerPreCheckout($botToken, $queryId, false, "Unsupported currency requested."); return; } // Check local store inventory and order status $stmt = $pdo->prepare("SELECT status, star_amount FROM orders WHERE id = :id FOR UPDATE"); $stmt->execute([':id' => $payload['order_id']]); $order = $stmt->fetch(PDO::FETCH_ASSOC); if (!$order) { answerPreCheckout($botToken, $queryId, false, "Order record not found in system."); return; } if ($order['status'] !== 'pending') { answerPreCheckout($botToken, $queryId, false, "Order has expired or is already processed."); return; } if ((int)$order['star_amount'] !== $totalAmount) { answerPreCheckout($botToken, $queryId, false, "Order price mismatch detected."); return; } // Approve checkout answerPreCheckout($botToken, $queryId, true); } function answerPreCheckout(string $botToken, string $queryId, bool $ok, string $errorMessage = ''): void { $url = "https://api.telegram.org/bot{$botToken}/answerPreCheckoutQuery"; $body = [ 'pre_checkout_query_id' => $queryId, 'ok' => $ok, ]; if (!$ok) { $body['error_message'] = $errorMessage; } $ch = curl_init($url); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_POSTFIELDS => json_encode($body), CURLOPT_TIMEOUT => 5, ]); curl_exec($ch); curl_close($ch); } 

If inventory is depleted or the order status is invalid, setting ok => false alongside a descriptive error_message notifies the user gracefully within the client application UI.

Fulfilling Successful Payments Idempotently

Once the user's Stars are debited, Telegram dispatches a standard Message update containing a successful_payment object to your webhook.

A dangerous flaw in many PHP webhooks is the lack of idempotency. Webhook deliveries over HTTP are subject to network timeouts, dropped packets, and automatic retries. If your server encounters a database delay or network lag when acknowledging a webhook, Telegram will retry delivering the successful_payment update. Without transactional locks, your bot might award digital goods multiple times for a single payment.

To ensure complete idempotency, you must store Telegram's unique transaction identifier: telegram_payment_charge_id. Perform the status transition inside an isolated SQL transaction using explicit row locking (FOR UPDATE).

Here is a complete, production-ready PHP webhook endpoint that validates incoming secret tokens and processes payment confirmations safely:

<?php declare(strict_types=1); // 1. Validate Webhook Secret Header $secretHeader = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? ''; $expectedSecret = getenv('TELEGRAM_WEBHOOK_SECRET'); if (empty($expectedSecret) || !hash_equals($expectedSecret, $secretHeader)) { http_response_code(403); echo json_encode(['error' => 'Unauthorized request origin']); exit; } // 2. Parse Incoming Webhook Body $rawInput = file_get_contents('php://input'); $update = json_decode($rawInput, true); if (json_last_error() !== JSON_ERROR_NONE || !is_array($update)) { http_response_code(400); echo json_encode(['error' => 'Malformed JSON payload']); exit; } $botToken = (string)getenv('TELEGRAM_BOT_TOKEN'); $dsn = (string)getenv('DATABASE_DSN'); $pdo = new PDO($dsn, (string)getenv('DB_USER'), (string)getenv('DB_PASS'), [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]); // 3. Route Pre-Checkout Query if (isset($update['pre_checkout_query'])) { handlePreCheckoutQuery($pdo, $botToken, $update['pre_checkout_query']); http_response_code(200); echo 'OK'; exit; } // 4. Route Successful Payment if (isset($update['message']['successful_payment'])) { $payment = $update['message']['successful_payment']; $chargeId = $payment['telegram_payment_charge_id'] ?? ''; $rawPayload = $payment['invoice_payload'] ?? ''; $totalAmount = (int)($payment['total_amount'] ?? 0); $currency = $payment['currency'] ?? ''; $payload = json_decode($rawPayload, true); $orderId = $payload['order_id'] ?? null; $sig = $payload['sig'] ?? null; if (!$orderId || !$sig || $currency !== 'XTR') { // Acknowledge update to prevent continuous retry loops for invalid data http_response_code(200); echo 'OK'; exit; } // Verify payload signature again $expectedSig = hash_hmac('sha256', $orderId, $botToken); if (!hash_equals($expectedSig, $sig)) { http_response_code(200); echo 'OK'; exit; } // Atomic fulfillment transaction $pdo->beginTransaction(); try { $stmt = $pdo->prepare("SELECT status, star_amount, telegram_charge_id FROM orders WHERE id = :id FOR UPDATE"); $stmt->execute([':id' => $orderId]); $order = $stmt->fetch(); if ($order && $order['status'] === 'pending' && (int)$order['star_amount'] === $totalAmount) { // Update order status and attach Telegram charge ID $updateStmt = $pdo->prepare( "UPDATE orders SET status = 'paid', telegram_charge_id = :charge_id, paid_at = NOW() WHERE id = :id" ); $updateStmt->execute([ ':charge_id' => $chargeId, ':id' => $orderId ]); // Execute business logic: Provision user access, issue digital key, etc. // deliverDigitalGoods($pdo, $orderId); $pdo->commit(); } else { // Order was already fulfilled or amount mismatched $pdo->rollBack(); } } catch (Throwable $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } error_log("Payment processing error for order {$orderId}: " . $e->getMessage()); // Optionally throw $e to issue 500 status code if you want Telegram to retry later } http_response_code(200); echo 'OK'; exit; } // Always default to 200 OK for irrelevant updates http_response_code(200); echo 'OK'; 

Production Notes & Error Handling Edge Cases

Building payment integrations requires accounting for failures occurring after funds leave the user's wallet:

  1. Webhook Secret Validation: Always verify the X-Telegram-Bot-Api-Secret-Token header using hash_equals(). Never rely on URL obfuscation alone. If an attacker sends simulated successful_payment updates directly to your PHP endpoint, strict secret token verification drops unauthorized HTTP requests immediately.

  2. Handling Refunds with refundStarPayment: If your system fails to grant a digital service after a successful transaction (for instance, an external API key generator fails), you must automatically refund the user's Stars. Telegram provides the refundStarPayment API method, which takes user_id and telegram_payment_charge_id parameters.

  3. Database Timeout Limits: Ensure your cURL execution timeout inside handlePreCheckoutQuery is lower than 5 seconds. Telegram enforces a strict 10-second ceiling on responses to pre_checkout_query. If your database connection stalls or a lock waits too long, the cURL request will abort, preventing hanging processes.

  4. Database Schema Considerations: Ensure your SQL table enforces uniqueness on telegram_charge_id (allowing null for unpaid records). This database constraint acts as a final defense against dual-fulfillment bugs during application-level race conditions.

Building reliable payment systems requires strict server-side validation and failure handling. If you need assistance scaling payment automation or constructing custom Telegram solutions, reach out to BotCreator — studio that ships Telegram bots / Mini Apps.

For additional protocol specifics regarding Bot API execution flow, refer to