When developing high-load Telegram bots on the Yii2 framework, a key condition for stability is minimal incoming Webhook response time. The Telegram Bot API expects a fast HTTP 200 OK response from the web server (usually within 3 seconds). If the server delays due to executing complex database queries, external CRMs, or generating media files, Telegram drops the connection and starts re-sending the same incoming events (updates).
As a result, the bot starts sending duplicate messages to the user, and the server falls under a cascading overload. In this article, we will look at building the proper architectural layer: we will create an isolated Webhook controller in Yii2, disable standard CSRF validation, implement X-Telegram-Bot-Api-Secret-Token header verification, protect against duplicates using a log table, and offload logic execution to Yii Queue.
1. Requirements for a Webhook Controller in Yii2
For the controller to function smoothly under any load, it must meet the following criteria:
- No CSRF check: Telegram sends POST requests without Yii2 session tokens, so the built-in `enableCsrfValidation` protection must be disabled for the webhook action.
- Source authentication: Validation of the
X-Telegram-Bot-Api-Secret-Tokenheader protects the endpoint from third-party scanners and forged HTTP POST requests. - Idempotency (deduplication): Atomic writing of
update_idto the database to prevent duplicate processing of the same update during network failures. - Asynchrony: Instant response return of
{"status":"ok"}and delegation of the payload to an internal queue (Yii Queue + Redis/AMQP/MySQL).
2. Creating WebhookController and Verifying the Secret Token
Below is a working Yii2 controller. It disables CSRF validation, verifies the X-Telegram-Bot-Api-Secret-Token header, and registers the update_id in the database before pushing the job to the queue.
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\Response;
use yii\web\ForbiddenHttpException;
use app\jobs\ProcessTelegramUpdateJob;
class WebhookController extends Controller
{
/**
* Отключаем CSRF валидацию для входящих HTTP POST от Telegram API
*/
public $enableCsrfValidation = false;
public function actionIndex(): array
{
Yii::$app->response->format = Response::FORMAT_JSON;
$secretHeader = Yii::$app->request->headers->get('X-Telegram-Bot-Api-Secret-Token');
$expectedSecret = Yii::$app->params['telegram_secret_token'] ?? getenv('TELEGRAM_SECRET_TOKEN');
if (empty($expectedSecret) || !hash_equals((string)$expectedSecret, (string)$secretHeader)) {
Yii::warning('Недействительный Secret Token в Telegram Webhook', 'telegram');
throw new ForbiddenHttpException('Invalid secret token');
}
$rawBody = Yii::$app->request->getRawBody();
$data = json_decode($rawBody, true);
if (json_last_error() !== JSON_ERROR_NONE || !isset($data['update_id'])) {
return ['status' => 'error', 'message' => 'Invalid payload'];
}
$updateId = (int)$data['update_id'];
// Защита от дублей update_id через БД (уникальный индекс на поле update_id)
$transaction = Yii::$app->db->beginTransaction();
try {
Yii::$app->db->createCommand()
->insert('{{%telegram_processed_update}}', [
'update_id' => $updateId,
'created_at' => time(),
])
->execute();
$transaction->commit();
} catch (\Exception $e) {
$transaction->rollBack();
// Повторный update_id — отдаем 200 OK, чтобы Telegram не присылал его снова
return ['status' => 'already_processed', 'update_id' => $updateId];
}
// Передаем весь массив апдейта в Yii Queue
Yii::$app->queue->push(new ProcessTelegramUpdateJob([
'updateData' => $data,
]));
return ['status' => 'ok', 'update_id' => $updateId];
}
}
3. Database Migration for Duplicate Event Protection
To guarantee protection against re-processing duplicate updates, let's create a telegram_processed_update table with a unique primary key or a unique index on the update_id field.
<?php
use yii\db\Migration;
class m240101_100000_create_telegram_processed_update_table extends Migration
{
public function safeUp()
{
$this->createTable('{{%telegram_processed_update}}', [
'update_id' => $this->bigInteger()->notNull(),
'created_at' => $this->integer()->notNull(),
]);
$this->addPrimaryKey('pk_telegram_processed_update', '{{%telegram_processed_update}}', 'update_id');
}
public function safeDown()
{
$this->dropTable('{{%telegram_processed_update}}');
}
}
4. Background Event Processing via Yii Queue Job
After the webhook is saved and confirmed with an HTTP 200 response, the background Yii Queue worker picks up the ProcessTelegramUpdateJob object. This is where the business logic is executed: parsing commands, calling external APIs, and sending messages to users via a secure cURL client.
<?php
namespace app\jobs;
use Yii;
use yii\base\BaseObject;
use yii\queue\JobInterface;
class ProcessTelegramUpdateJob extends BaseObject implements JobInterface
{
public array $updateData = [];
public function execute($queue)
{
if (empty($this->updateData)) {
return;
}
$botToken = Yii::$app->params['telegram_bot_token'] ?? getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
Yii::error('TELEGRAM_BOT_TOKEN не установлен в конфигурации', 'telegram');
return;
}
// Обработка обычного текстового сообщения
if (isset($this->updateData['message'])) {
$message = $this->updateData['message'];
$chatId = $message['chat']['id'] ?? null;
$text = $message['text'] ?? '';
if ($chatId && $text === '/start') {
$this->sendApiRequest($botToken, 'sendMessage', [
'chat_id' => $chatId,
'text' => '<b>Добро пожаловать!</b> Ваш запрос успешно принят.',
'parse_mode' => 'HTML',
]);
}
}
// Обработка callback_query
if (isset($this->updateData['callback_query'])) {
$callback = $this->updateData['callback_query'];
$callbackId = $callback['id'] ?? null;
if ($callbackId) {
$this->sendApiRequest($botToken, 'answerCallbackQuery', [
'callback_query_id' => $callbackId,
'text' => 'Данные обработаны',
'show_alert' => false,
]);
}
}
}
/**
* Безопасный cURL-метод для обращения к Telegram Bot API
*/
private function sendApiRequest(string $token, string $method, array $params): ?array
{
$url = "https://api.telegram.org/bot{$token}/{$method}";
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($params),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 3,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError !== '') {
Yii::error("cURL error во время {$method}: {$curlError}", 'telegram');
return null;
}
if ($httpCode !== 200) {
Yii::error("Telegram API вернул HTTP {$httpCode}: {$response}", 'telegram');
return null;
}
$result = json_decode((string)$response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Yii::error("Ошибка парсинга JSON ответа Telegram API", 'telegram');
return null;
}
if (isset($result['ok']) && $result['ok'] === false) {
$desc = $result['description'] ?? 'неизвестная ошибка';
Yii::error("Telegram API вернул ok:false - {$desc}", 'telegram');
return null;
}
return $result;
}
}
5. Setting Up and Configuring the Webhook in Telegram
To register the HTTP endpoint on Telegram's side, pass the secret_token parameter when calling the setWebhook method. You can do this via a Yii2 console command or a cURL request:
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
-H "Content-Type: application/json" \
-d '{
"url": "https://yourdomain.com/webhook",
"secret_token": "YOUR_STRONG_SECRET_TOKEN_HERE",
"max_connections": 40
}'
6. Common Errors and Operational Recommendations
- Hanging transactions: Do not execute external network requests inside the
actionIndex()method. Any external API timeout will result in repeated calls from Telegram. - Token comparison via ==: Always use
hash_equals()to protect against timing attacks. - Missing max connections limit: Configure the
max_connectionsparameter insetWebhooktaking into account the throughput of your PHP-FPM pool. - Cleaning up update_id logs: Set up a console command (cron job) to regularly delete records from
telegram_processed_updateolder than 7 days to prevent the table from growing excessively.
If you need reliable integration and ready-made services for business automation in messengers, contact the specialists at BotCreator.