Imagine building an interactive warehouse management bot in pure PHP. A manager receives a message detailing a pending shipment, complete with inline action buttons: "Approve Item", "Reject Item", or "Re-assign Category". Everything works smoothly in early manual testing with dummy records like order ID 1. But as soon as the system hits staging with UUID-based keys or legacy strings like action=approve_shipment&order_id=98765432-ef89-4b2a-891a&dept=logistics, the interface shatters.
Buttons stop responding. Telegram drops requests with an HTTP 400 error Bad Request: BUTTON_DATA_INVALID, or worse, users tap a button and see an infinite loading spinner while your webhooks silently crash behind the scenes. If a user double-taps the pending button during network latency, your PHP script processes the approval logic twice because the old inline keyboard remained clickable.
These failures occur because Telegram's InlineKeyboardMarkup API enforces strict byte constraints, asynchronous query acknowledgments, and state mutation rules that standard web developers frequently misjudge. In this article, you will learn how to design compact payload schemas that survive the 64-byte limit, implement reliable query responses, mutate message states via editMessageText, and catch silent Telegram API failures using pure PHP and cURL.
Compressing Callback Payload Data Under the 64-Byte Limit
The callback_data string attached to an inline button in Telegram has a hard ceiling of 64 bytes. This limit is calculated in raw UTF-8 bytes, not UTF-16 code units or character counts. Passing human-readable strings, verbose JSON, or raw UUIDs rapidly triggers an unrecoverable payload error when rendering the markup.
Consider this common implementation mistake:
<?php // FAILING PATH: Verbose JSON payload exceeds 64 bytes $payload = json_encode([ 'action' => 'approve_warehouse_stock', 'item_uuid' => 'f47ac10b-58cc-4372-a567-0e02b2c3d479', 'admin_id' => 987654321 ]); // strlen($payload) === 104 bytes! // Telegram API returns HTTP 400 Bad Request: BUTTON_DATA_INVALID To resolve this, you must build a deterministic, compact routing schema. Use short single-character delimiters, abbreviated action keys, and integer references or hexadecimal binary identifiers instead of full UUID strings. If you must support dynamic parameters that exceed 30 bytes, write the transient state to a cache backend (like Redis or MySQL) using a 14-character hex key generated via bin2hex(random_bytes(7)) and pass only that key in the button payload.
Below is a lightweight payload encoder and builder pattern in standard PHP:
<?php // src/KeyboardBuilder.php declare(strict_types=1); function buildStockApprovalKeyboard(int $orderId, string $hexToken): array { // Schema: {action_code}:{order_id}:{short_token} // Example payload: "a:10492:8f3a1b" -> 14 bytes total $approveData = sprintf('a:%d:%s', $orderId, $hexToken); $rejectData = sprintf('r:%d:%s', $orderId, $hexToken); if (strlen($approveData) > 64 || strlen($rejectData) > 64) { throw new \InvalidArgumentException('Callback payload exceeds Telegram 64-byte limit.'); } return [ 'inline_keyboard' => [ [ [ 'text' => '✅ Approve Stock', 'callback_data' => $approveData, ], [ 'text' => '❌ Reject', 'callback_data' => $rejectData, ], ] ] ]; } By decoupling large context blobs from the button markup and replacing string keys with minimal schemas, your payloads stay well below 20 bytes. This guarantees that UTF-8 multi-byte characters or integer expansions won't push your string over the 64-byte threshold.
Eliminating Client-Side Loading Spinners with answerCallbackQuery
When a user presses an inline button, Telegram displays a subtle loading clock over the button face. Telegram keeps this loading indicator active until your webhook server explicitly invokes the answerCallbackQuery endpoint for that specific callback_query_id.
If your backend code performs business logic, updates a database, and returns an HTTP 200 response to the webhook call without calling answerCallbackQuery, the client device will spin for up to 60 seconds before showing a generic timeout toast. This creates an awful user experience and leads to frustrated re-clicks.
Furthermore, if your processing fails due to a database exception, Telegram requires you to answer the callback query with an alert popup so the user understands why the action did not take effect.
Here is how to extract incoming query parameters safely and acknowledge them immediately:
<?php // webhook.php declare(strict_types=1); $botToken = getenv('TELEGRAM_BOT_TOKEN'); if (!$botToken) { http_response_code(500); exit('Missing Bot Token configuration'); } $rawInput = file_get_contents('php://input'); if (!$rawInput) { http_response_code(400); exit('Empty body'); } $update = json_decode($rawInput, true); if (json_last_error() !== JSON_ERROR_NONE) { http_response_code(400); exit('Invalid JSON'); } // Ignore non-callback updates if (!isset($update['callback_query'])) { http_response_code(200); echo 'OK'; exit; } $callbackQuery = $update['callback_query']; $callbackQueryId = (string) $callbackQuery['id']; $payloadData = (string) ($callbackQuery['data'] ?? ''); $chatId = (int) $callbackQuery['message']['chat']['id']; $messageId = (int) $callbackQuery['message']['message_id']; // Helper for sending low-level Telegram API requests via cURL function callTelegramApi(string $token, string $method, array $params): array { $url = sprintf('https://api.telegram.org/bot%s/%s', $token, $method); $ch = curl_init($url); $payloadJson = json_encode($params); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Content-Type: application/json'], CURLOPT_POSTFIELDS => $payloadJson, CURLOPT_TIMEOUT => 5, ]); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($response === false || $httpCode !== 200) { return ['ok' => false, 'error_code' => $httpCode]; } $decoded = json_decode((string)$response, true); return is_array($decoded) ? $decoded : ['ok' => false]; } // Parse action schema: "a:10492:8f3a1b" $parts = explode(':', $payloadData); $action = $parts[0] ?? ''; $orderId = isset($parts[1]) ? (int)$parts[1] : 0; if ($action === 'a') { // Acknowledge query immediately with a subtle toast notification callTelegramApi($botToken, 'answerCallbackQuery', [ 'callback_query_id' => $callbackQueryId, 'text' => 'Processing order approval...', 'show_alert' => false, ]); } else { // Surface actionable alerts for invalid or unknown commands callTelegramApi($botToken, 'answerCallbackQuery', [ 'callback_query_id' => $callbackQueryId, 'text' => 'Error: Unknown or expired action button.', 'show_alert' => true, ]); exit; } By placing answerCallbackQuery at the top of your interaction flow, you terminate the client loading spinner in under a second while continuing execution in your PHP script.
Mutating Interface State via editMessageText and cURL
Once a button action has been validated and committed to your storage layer, leaving the old action buttons visible invites race conditions. If two store managers look at the same Telegram message simultaneously, both can click "Approve Stock" if the inline keyboard remains untouched.
To lock down the interface state, mutate the message text and remove or adjust the reply_markup using editMessageText.
When working with HTML parse mode in Telegram messages, any dynamic input from users or backend databases (such as product titles or stock notes) MUST be passed through htmlspecialchars() to prevent broken parse errors when special characters like <, >, or & appear in your strings.
Below is a complete implementation that processes an action, sanitizes text, updates the storage state, and rewrites the interface to prevent duplicate submissions:
<?php // src/ProcessApproval.php declare(strict_types=1); function executeOrderApproval( string $botToken, int $chatId, int $messageId, int $orderId, string $actorUsername ): void { // 1. Perform domain mutations (e.g., MySQL transaction update) // $db->query("UPDATE orders SET status = 'APPROVED' WHERE id = ?", [$orderId]); // Unsanitized string from DB or client input $rawItemName = "Warehouse Unit #4 <Heavy & Fragile>"; // Always escape dynamic data for HTML parse_mode $safeItemName = htmlspecialchars($rawItemName, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); $safeActor = htmlspecialchars($actorUsername, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); $updatedBody = sprintf( "<b>Order #%d Status Updated</b> " . "Item: <code>%s</code> " . "Status: <b>APPROVED</b> " . "Approved by: @%s " . "Timestamp: %s", $orderId, $safeItemName, $safeActor, date('Y-m-d H:i:s') ); // Replace old buttons with an updated interface state (or empty array to drop keyboard) $modifiedMarkup = [ 'inline_keyboard' => [ [ [ 'text' => '🔒 Order Locked (Approved)', 'callback_data' => 'noop', ] ] ] ]; $result = callTelegramApi($botToken, 'editMessageText', [ 'chat_id' => $chatId, 'message_id' => $messageId, 'text' => $updatedBody, 'parse_mode' => 'HTML', 'disable_web_page_preview' => true, 'reply_markup' => $modifiedMarkup, ]); if (!($result['ok'] ?? false)) { // Log Telegram failure detail cleanly error_log(sprintf( 'Telegram API Error during editMessageText: %s', $result['description'] ?? 'Unknown API Exception' )); } } With this pattern, the old buttons are replaced immediately after execution, guaranteeing that secondary taps cannot re-trigger background updates.
Production Engineering Notes
When deploying Telegram inline keyboards to production in PHP environments, several edge cases require additional handling:
- Handling "Message is Not Modified" Exceptions: If a user rapidly taps an inline button or if your server sends identical content to
editMessageText, Telegram returns anHTTP 400 Bad Request: message is not modifiedresponse. Your application should treat this error code as a non-fatal event instead of throwing an unhandled exception or breaking the webhook stream. - State Expiry and Cleanup: Telegram inline buttons persist in chat histories indefinitely. A user can find a message sent six months ago and tap an action button. Never rely solely on short tokens without state checks; verify that the entity referenced in
callback_datais still eligible for modification in your database before executing state changes. - HTML Entity Escaping: Failing to run
htmlspecialchars()over arbitrary values like user nicknames, order descriptions, or inventory names inside HTML-formatted strings causeseditMessageTextto crash with400 Bad Request: can't parse entities. Always escape non-static values.
Building production-grade Telegram interfaces requires predictable data serialization and explicit API error handling. If your team is scaling server-side integrations or complex automated bot architectures, consider consulting with BotCreator — standard-setting engineers who build high-throughput Telegram bots, payment integrations, and Mini Apps. Learn more about custom Bot API solutions at
