Imagine building an inventory management bot or a multi-step booking system in Telegram using PHP. A supervisor taps an "Approve Request" button inside an inline keyboard. Instead of seeing an instant update, the button displays a continuous loading clock icon for ten seconds before fading away without any visible action. Behind the scenes, your PHP application threw a backend exception while fetching user rights, or your script sent a full JSON string in the button payload that exceeded Telegram's strict data caps.
When working with inline keyboards, two distinct technical constraints frequently cause silent failures. First, Telegram expects an explicit acknowledgment via answerCallbackQuery for every user tap. If your backend delays this call due to slow SQL queries or network overhead, the Telegram client keeps the loading spinner active until it times out. Second, Telegram limits the callback_data string of an inline button to exactly 64 bytes. Exceeding this limit causes the sendMessage or editMessageReplyMarkup API call to fail with a 400 Bad Request: BUTTON_DATA_INVALID error before the message is even delivered.
To build a reliable user interface, you must handle incoming callback_query payloads asynchronously, shorten payload schemas to fit comfortably under the limit, and handle in-place message modifications cleanly without triggering API exceptions.
Resolving UI Freezes with Immediate answerCallbackQuery Responses
When a user taps an inline button, Telegram does not send a standard message update. Instead, it dispatches an Update object containing a callback_query. The user's app displays a small spinner on the button until your server invokes the answerCallbackQuery endpoint using the corresponding callback_query_id.
If your code executes heavy business logic—such as processing a payment or contacting an external API—before answering the callback query, the user experiences UI latency. Worse, if your script encounters a fatal error or times out before calling answerCallbackQuery, the spinner remains visible until the client app hits its internal timeout threshold.
To fix this, process the callback query acknowledgment as early as possible in your request lifecycle, or ensure every execution branch triggers an answer call.
Here is how to extract incoming webhook data in PHP and respond immediately before running application logic:
<?php
declare(strict_types=1);
$rawInput = file_get_contents('php://input');
if ($rawInput === false || $rawInput === '') {
http_response_code(400);
exit('Empty request');
}
$update = json_decode($rawInput, true);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
exit('Invalid JSON');
}
$botToken = getenv('BOT_TOKEN');
if (!$botToken) {
http_response_code(500);
exit('Bot token not configured');
}
// Extract callback query if present
if (isset($update['callback_query'])) {
$callbackQuery = $update['callback_query'];
$callbackId = $callbackQuery['id'];
$callbackData = $callbackQuery['data'] ?? '';
$chatId = $callbackQuery['message']['chat']['id'] ?? null;
$messageId = $callbackQuery['message']['message_id'] ?? null;
// Acknowledge the tap immediately to clear the loading spinner on the client
$ackResult = sendTelegramApi($botToken, 'answerCallbackQuery', [
'callback_query_id' => $callbackId,
'text' => 'Processing request...',
'show_alert' => false
]);
if (!$ackResult['ok']) {
error_log('Failed to answer callback query: ' . $ackResult['description']);
}
// Continue with domain logic safely...
handleCallbackAction($botToken, $chatId, $messageId, $callbackData);
}
function sendTelegramApi(string $token, string $method, array $params): array
{
$url = sprintf('https://api.telegram.org/bot%s/%s', $token, $method);
$ch = curl_init($url);
$payload = json_encode($params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, 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, 'description' => 'HTTP request failed with code ' . $httpCode];
}
$decoded = json_decode((string)$response, true);
return $decoded ?? ['ok' => false, 'description' => 'Invalid response payload'];
}
By placing answerCallbackQuery at the beginning of the handler, you decouple UI feedback from database or network performance. Setting show_alert => true will present a modal alert box instead of a toast notification, which is useful when explaining permission failures or validation errors.
Structuring Compact Callback Data Below the 64-Byte Hard Limit
A common developer mistake is treating callback_data like a web URL query string or a serialized JSON object. Developers often attempt payloads such as:
action=approve_checkout&order_id=98234123&user_id=1023912&status=confirmed
This string is 71 bytes long. Telegram will reject the payload when you attempt to send the message containing the keyboard markup.
To avoid hitting the 64-byte ceiling while preserving routing capability, you must design a compact data serialization pattern. Use short single-character action codes and positional delimiters instead of key-value identifiers.
For instance, map the action approve_checkout to act:app. Instead of passing user IDs and verbose parameters, pass only the primary internal ID or an encoded token.
Here is a dedicated PHP helper class that packs and unpacks short callback payloads safely:
<?php
declare(strict_types=1);
class CallbackPayloadFormatter
{
private const DELIMITER = ':';
/**
* Packs an action alias and parameters into a sub-64-byte string.
* Example: pack('app', ['98234123', '1']) -> "app:98234123:1"
*/
public static function pack(string $actionCode, array $params = []): string
{
$parts = array_merge([$actionCode], $params);
$payload = implode(self::DELIMITER, $parts);
if (strlen($payload) > 64) {
throw new \InvalidArgumentException(
sprintf('Callback data exceeds 64-byte limit (%d bytes): "%s"', strlen($payload), $payload)
);
}
return $payload;
}
/**
* Unpacks a callback data string back into action and arguments.
*/
public static function unpack(string $payload): array
{
$parts = explode(self::DELIMITER, $payload);
$action = array_shift($parts) ?? '';
return [
'action' => $action,
'params' => $parts
];
}
}
// Example Usage: Building an inline keyboard safely
$orderId = 98234123;
$page = 2;
$approvePayload = CallbackPayloadFormatter::pack('a', [(string)$orderId, (string)$page]); // "a:98234123:2" (12 bytes)
$rejectPayload = CallbackPayloadFormatter::pack('r', [(string)$orderId, (string)$page]); // "r:98234123:2" (12 bytes)
$keyboard = [
'inline_keyboard' => [
[
['text' => '✅ Approve', 'callback_data' => $approvePayload],
['text' => '❌ Reject', 'callback_data' => $rejectPayload],
]
]
];
If your application requires passing complex state (such as dynamic multi-select filters in a shop), do not store state inside callback_data. Instead, store the selection state in Redis or your database under a unique short token (e.g., a 12-character hex generated via bin2hex(random_bytes(6))) and pass only that token in the button: flt:a1f89c02b3e4.
Updating Inline Keyboards In-Place with editMessageText
After receiving a callback query and processing the action, sending a brand-new message to the chat creates visual clutter. The preferred UX approach is to update the existing message in-place using editMessageText or editMessageReplyMarkup.
However, Telegram enforces a strict constraint on message editing: if you submit an editMessageText request where neither the text nor the keyboard markup changes from the original state, Telegram returns an HTTP 400 response with the error string 400 Bad Request: message is not modified.
If your code treats all non-200 responses as unhandled exceptions, duplicate button taps will trigger error alerts in your logging system.
The following code demonstrates a resilient message updater that handles callback logic, updates text and inline options, and ignores harmless "message is not modified" exceptions:
<?php
declare(strict_types=1);
function handleCallbackAction(string $botToken, int $chatId, int $messageId, string $payload): void
{
$parsed = CallbackPayloadFormatter::unpack($payload);
$action = $parsed['action'];
$params = $parsed['params'];
if ($action === 'a') {
$orderId = $params[0] ?? '0';
$statusText = sprintf("<b>Order #%s</b>
Status: <i>Approved</i>", htmlspecialchars($orderId, ENT_QUOTES, 'UTF-8'));
$updatedKeyboard = [
'inline_keyboard' => [
[
['text' => '📦 View Shipping Details', 'callback_data' => CallbackPayloadFormatter::pack('shp', [$orderId])]
]
]
];
$response = sendTelegramApi($botToken, 'editMessageText', [
'chat_id' => $chatId,
'message_id' => $messageId,
'text' => $statusText,
'parse_mode' => 'HTML',
'reply_markup' => $updatedKeyboard
]);
if (!$response['ok']) {
$description = $response['description'] ?? '';
// Catch and suppress the duplicate edit error
if (str_istr($description, 'message is not modified') !== false) {
error_log(sprintf('Ignored redundant edit for message %d in chat %d', $messageId, $chatId));
return;
}
error_log(sprintf('Failed to edit message %d: %s', $messageId, $description));
}
}
}
Always pass parse_mode => 'HTML' when using HTML tags like <b> or <i>, and sanitize dynamic string variables using htmlspecialchars to avoid broken syntax errors (400 Bad Request: can't parse entities).
Production Readiness: Idempotency, Stale Callbacks, and Network Robustness
When running your Telegram bot in production, keep the following backend guarantees in mind:
1. Webhook Idempotency
Telegram guarantees at-least-once delivery for webhooks. If your server encounters network hiccups or responds with a non-200 status code, Telegram re-sends the same update multiple times. Always record processed update_id values in Redis or a relational database table with a unique constraint. If an incoming update_id has already been marked as processed, return an immediate HTTP 200 OK response without running business actions again.
2. Handling Stale Inline Messages
Users can tap inline buttons on messages sent days or weeks ago. Your backend must handle situations where the associated database records no longer exist or the state has changed. Always validate entity existence when parsing payload IDs. If an order was already processed or deleted, inform the user cleanly using answerCallbackQuery with show_alert => true:
if (!$orderExists) {
sendTelegramApi($botToken, 'answerCallbackQuery', [
'callback_query_id' => $callbackId,
'text' => 'This order is no longer active.',
'show_alert' => true
]);
return;
}
3. Verification of Secret Tokens
Protect your PHP webhook entry point from untrusted external requests. Define a webhook secret token when setting up your webhook via setWebhook with the secret_token parameter. Verify the header in your PHP script before processing input:
$headers = getallheaders();
$telegramHeader = $headers['X-Telegram-Bot-Api-Secret-Token'] ?? '';
if ($telegramHeader !== getenv('WEBHOOK_SECRET')) {
http_response_code(403);
exit('Unauthorized access');
}
Building custom interactive flows and complex state trees requires careful management of API limits and asynchronous communication patterns. For complex deployments, production support, or customized Mini App architectures, consider consulting with BotCreator — studio that ships Telegram bots / Mini Apps.
Top comments (0)