Using Webhook mode in Telegram Bot API is significantly more efficient than server polling via getUpdates (Long Polling) under high and medium loads. Telegram servers automatically send incoming updates (HTTP POST) to the specified URL as soon as they appear. However, implementing Webhook in pure PHP requires strict code hygiene: validating the authenticity of incoming requests, handling network failures, and strictly controlling idempotency.
In this practical guide, we will cover the entire cycle from configuring a webhook with a secret token to securely receiving the payload via php://input and working with a database.
1. Setting Up Webhook via setWebhook Using cURL
Entry point registration is performed by calling the setWebhook method. When sending the request, it is recommended to immediately include the optional but critically important secret_token parameter. This token (1 to 256 characters long) will arrive in every HTTP request from Telegram in the X-Telegram-Bot-Api-Secret-Token header.
To send requests to the Telegram API in pure PHP, you must use the cURL extension. No file_get_contents for external HTTP requests — they do not provide convenient control over HTTP statuses and network timeouts.
<?php
declare(strict_types=1);
$botToken = getenv('BOT_TOKEN');
$secretToken = getenv('WEBHOOK_SECRET');
$webhookUrl = getenv('WEBHOOK_URL');
if (!$botToken || !$secretToken || !$webhookUrl) {
fwrite(STDERR, "Ошибка: Не заданы переменные окружения BOT_TOKEN, WEBHOOK_SECRET или WEBHOOK_URL\n");
exit(1);
}
$apiUrl = "https://api.telegram.org/bot{$botToken}/setWebhook";
$payload = [
'url' => $webhookUrl,
'secret_token' => $secretToken,
'allowed_updates' => json_encode(['message', 'callback_query']),
'drop_pending_updates' => false];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $apiUrl,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $payload,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5]);
$response = curl_exec($ch);
$curlErrno = curl_errno($ch);
$curlError = curl_error($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($curlErrno !== 0) {
throw new RuntimeException("cURL Error ({$curlErrno}): {$curlError}");
}
if ($httpCode !== 200) {
throw new RuntimeException("Telegram API вернул HTTP-код {$httpCode}: {$response}");
}
$data = json_decode((string)$response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException("Ошибка парсинга JSON ответа: " . json_last_error_msg());
}
if (empty($data['ok'])) {
$description = $data['description'] ?? 'Неизвестная ошибка';
throw new RuntimeException("Telegram API Error: {$description}");
}
echo "Webhook успешно установлен! Ответ Telegram: " . $data['description'] . "\n";
2. Validating the X-Telegram-Bot-Api-Secret-Token Header
Your handler script is exposed to the entire internet. Any attacker who guesses or finds out the script URL can send fake POST requests. To ensure that the request actually came from the Telegram gateway, you should check the X-Telegram-Bot-Api-Secret-Token header.
In PHP (when running via Nginx/Apache), this header ends up in the superglobal $_SERVER array under the HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN key. For safe string comparison, you should use the hash_equals() function, which protects against timing attacks.
3. Reading php://input and Checking Idempotency
Telegram sends data in the POST request body in JSON format. The $_POST array will be empty in this case, because the data is transmitted with Content-Type: application/json. You need to read the body from the php://input stream.
Due to network timeouts or redelivery attempts (retries), Telegram may send the same update multiple times. To prevent the bot from performing duplicate actions (for example, double-charging or registering a request twice), you must check the update_id parameter for idempotency using a DBMS.
Below is the complete incoming update handler script webhook.php:
<?php
declare(strict_types=1);
// 1. Проверка метода HTTP
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
http_response_code(405);
echo 'Method Not Allowed';
exit;
}
// 2. Валидация Secret Token
$expectedSecret = (string)getenv('WEBHOOK_SECRET');
$receivedSecret = $_SERVER['HTTP_X_TELEGRAM_BOT_API_SECRET_TOKEN'] ?? '';
if ($expectedSecret === '' || !hash_equals($expectedSecret, $receivedSecret)) {
http_response_code(403);
echo 'Access Denied: Invalid Secret Token';
exit;
}
// 3. Чтение сырого JSON из потока php://input
$rawInput = file_get_contents('php://input');
if ($rawInput === false || $rawInput === '') {
http_response_code(400);
echo 'Bad Request: Empty Body';
exit;
}
$update = json_decode($rawInput, true);
if (json_last_error() !== JSON_ERROR_NONE || !is_array($update)) {
http_response_code(400);
echo 'Bad Request: Invalid JSON';
exit;
}
$updateId = (int)($update['update_id'] ?? 0);
if ($updateId <= 0) {
http_response_code(400);
echo 'Bad Request: Missing update_id';
exit;
}
// 4. Подключение к БД и дедупликация update_id
try {
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', getenv('DB_HOST'), getenv('DB_NAME'));
$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]);
// Атомарная попытка вставки update_id (требуется UNIQUE KEY на поле update_id)
$stmt = $pdo->prepare('INSERT IGNORE INTO processed_updates (update_id, created_at) VALUES (:update_id, NOW())');
$stmt->execute([':update_id' => $updateId]);
if ($stmt->rowCount() === 0) {
// Запрос уже обрабатывался ранее
http_response_code(200);
echo 'OK (Duplicate update_id)';
exit;
}
} catch (PDOException $e) {
error_log('Webhook DB Error: ' . $e->getMessage());
// При ошибке БД отдаем 500, чтобы Telegram повторил попытку позже
http_response_code(500);
echo 'Internal Server Error';
exit;
}
// 5. Быстрый ответ 200 OK для Telegram
http_response_code(200);
echo 'OK';
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
// 6. Бизнес-логика после закрытия соединения
handleUpdate($pdo, $update);
function handleUpdate(PDO $pdo, array $update): void {
if (isset($update['message']['text']) && strpos($update['message']['text'], '/start') === 0) {
$chatId = (int)$update['message']['chat']['id'];
$leadId = bin2hex(random_bytes(7)); // Уникальный идентификатор лида
$stmt = $pdo->prepare('INSERT INTO leads (lead_id, telegram_chat_id, created_at) VALUES (:lead_id, :chat_id, NOW())');
$stmt->execute([
':lead_id' => $leadId,
':chat_id' => $chatId]);
sendTelegramMessage($chatId, "Заявка зарегистрирована! Номер: <b>{$leadId}</b>");
}
}
4. Fast 200 OK Response and Closing the FastCGI Connection
Telegram sets a strict timeout for awaiting an HTTP response from a webhook. If the script does not respond with a 200 OK code within a few seconds, Telegram will consider the delivery failed and will start resending the same update with an exponential delay.
For pure PHP scripts based on PHP-FPM, the best practice is to call the fastcgi_finish_request() function immediately after outputting headers and the text OK. This function instantly closes the HTTP connection with the Telegram server, allowing the script to continue running in the background (executing long requests to external APIs, working with the database, etc.).
5. Sending Response Messages via cURL
Below is a helper function, sendTelegramMessage, using cURL with full verification of HTTP codes and API responses:
<?php
declare(strict_types=1);
function sendTelegramMessage(int $chatId, string $text): bool {
$botToken = getenv('BOT_TOKEN');
if (!$botToken) {
error_log('sendTelegramMessage Error: BOT_TOKEN is empty');
return false;
}
$url = "https://api.telegram.org/bot{$botToken}/sendMessage";
$payload = [
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'HTML'];
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($payload),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 2]);
$response = curl_exec($ch);
$curlErrno = curl_errno($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($curlErrno !== 0 || $httpCode !== 200 || $response === false) {
error_log("Telegram sendMessage cURL Error HTTP {$httpCode}: {$response}");
return false;
}
$result = json_decode((string)$response, true);
if (!isset($result['ok']) || $result['ok'] !== true) {
error_log("Telegram API error response: {$response}");
return false;
}
return true;
}
6. Common Webhook Implementation Mistakes
- Using file_get_contents for the API: Requests to
api.telegram.orgviafile_get_contentslead to critical errors on connection loss and do not allow tracking the429 Retry-AfterHTTP code. - Lack of secret_token filtering: Without verifying this header, the public webhook URL can be exposed to DoS attacks or fake user action emulations.
- Long processing before the 200 OK response: If heavy operations (generating reports, querying a CRM) are executed before finishing the HTTP response, Telegram cancels the connection on timeout and loops the delivery of the same
update_id. - Хранение токенов in the script body: Secret keys must be loaded exclusively from environment variables (via
getenv()or$_ENV).
If you need professional development of fault-tolerant Telegram bots or webhook integration with your company's internal CRM system, contact the specialists at BotCreator.