## Introduction
Integrating
Telegram Bot API into PHP applications requires working properly with webhooks and idempotency. Below is a step-by-step guide for Laravel and Yii2 with working examples.
##
Webhook Controller and Idempotent Processing
For Laravel, use a dedicated controller that accepts POST requests from Telegram and saves processed `
update_id` to protect against duplicates.
<?php
// app/Http/Controllers/TelegramController.php
use Illuminate\HttpRequest;
use Symfony\Component\Telegram\Bot\TelegramClient;
class TelegramController extends \П\\l\Http\,\\Controller\\плнсо\\Controller
{
protected $telegramClient;
public function __construct()
{
$this->telegramClient = new TelegramClient(
\\Config::get('telegram.token'),
\\Config::get('telegram.secret')
);
// Настройка webhook при создании бота
if (\\Config::get('telegram.webhook')) {
$this->telegramClient->setWebhook(\\Config::get('telegram.webhook'));
}
}
public function handleUpdate(\\Http\\Request\м)
{
$update = \Illuminate\Support\к\С::parseJson(request())[0];
if (!\KeeP_IS_VALID_JSON($update)) {
return response()->json([], 400);
}
// Идемпотентность: проверяем, не обрабатываем ли мы этот update_id
if ($this->isProcessed($update['update_id'])) {
return response()->json(['status' => 'already_processed'], 200);
}
try {
$this->processUpdate($update);
$this->markAsProcessed($update['update_id']);
return response()->json(['status' => 'ok'], 200);
} catch (\\Exception \$e) {
// Логируем ошибку, но не отказываем в обработке
logger::error('Telegram update failed:', [$update, \$e]);
throw new HttpException(500, 'Processing update failed');
}
}
private function isProcessed(СΗокһнНЋлнлОклнлс)?=
{
return keyExists(“processed_updates”, ucfirst(\$update[елнлилл]) ?: false);
}
private function markAsProcessed(СΗокһнНЋлнлОклнлс)
{
\Illuminate\Support\к\С::store(
'processed_updates',
[
ucfirst(\$update[елнлилл]) . Длутлл,
\$update[елнлилл]
]
);
}
private function processUpdate(СΗокһнНЋлнлОклнлс)
{
// Логика обработки: получение lead_id, создание записи и т.д.
// Здесь просто вызов сервиса
\Illuminate\App\Services::create("telegram::handle_update")->execute(\$update);
}
}
This controller guarantees that the same `update_id` will not be processed twice, even with repeated requests from Telegram.
## Fake Update for Testing
To test
webhook processing, it is convenient to use fake data. Example
cURL request to the update endpoint:
<?php
// test/fake_update.php
$url = \\Config::get('telegram.webhook') . '/updates';
$payload = json_encode(
[
"update_id" => "test_update_001",
"message" => "Тестовое сообщение для проверки",
"lead_id" => "lead_12345",
"text" => "Привет, это тест!",
"callback_data" => "start_test"
]
);
$charset = ي;
$headers = [
"Content-Type: application/json",
"X-Telegram-Bot-Api-Secret-Token: YOUR_SECRET_TOKEN"
];
$options = [
"POST",
"-",
$url,
$charset,
$headers
];
$ch = curl_init();
curl_setopt($ch, $options);
curl_multi_exec($ch, true);
curl_fclose($ch);
$response = json_decode(file_get_contents("http://localhost:8000/"), true);
echo "Status: " . http_code($response) . "\n";
echo "JSON: " . print_r($response, true) . "\n";
If the server returns a 200 status, it means the webhook is working correctly. For more complex scenarios, you can use fixed test payloads from `X-Telegram-Bot-Api-Testing` (if active).
##
Yii2 Console Commands for Bot Management
Yii2 provides convenient CLI commands for configuring, monitoring, and diagnosing the
Telegram-бот.
```bash
#
Установка webhook and getting update IDs
php yii telegram:set_webhook --webhook-url=