Telegram Webhook in Laravel: Route::post, VerifyTelegramSecret Middleware, ShouldQueue Jobs, and Redis

Under high load or an unstable network, synchronous processing of incoming Telegram webhooks in the main HTTP thread leads to duplicate messages, timeouts, and hangs. If the server takes more than a few seconds to respond, Telegram considers the request failed and retries sending the same update_id over and over again.

A proper webhook architecture in Laravel is built on three principles: instant validation of incoming data, fast response with HTTP status 200 OK while dispatching the incoming array to a Queue, and проверка идемпотентности on the worker side.

1. Configuring the Route and Secret Token Protection Middleware

The Telegram Bot API allows setting a secret_token parameter (1 to 256 characters, containing A-Z, a-z, 0-9, _, and -) when calling setWebhook. Telegram sends it in every HTTP request in the X-Telegram-Bot-Api-Secret-Token header. This eliminates the need to expose a public controller without verifying the source's authenticity.

In the config/services.php configuration file, specify the bot credentials:

'telegram' => [
'bot_token' => env('TELEGRAM_BOT_TOKEN'),
'secret_token' => env('TELEGRAM_SECRET_TOKEN'),
],

Create a Middleware to verify the security header using the hash_equals function, which protects against timing attacks:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class VerifyTelegramSecret
{
public function handle(Request $request, Closure $next): Response
{
$headerSecret = $request->header('X-Telegram-Bot-Api-Secret-Token');
$expectedSecret = config('services.telegram.secret_token');

if (empty($expectedSecret) || !hash_equals($expectedSecret, (string) $headerSecret)) {
return response()->json(['error' => 'Unauthorized'], 403);
}

return $next($request);
}
}

Register the route in routes/api.php. Since API routes in Laravel do not include CSRF protection by default, you do not need to disable it manually:

use App\Http\Controllers\TelegramWebhookController;
use App\Http\Middleware\VerifyTelegramSecret;
use Illuminate\Support\Facades\Route;

Route::post('/telegram/webhook', TelegramWebhookController::class)
->middleware(VerifyTelegramSecret::class);

2. Fast 200 OK Response and Webhook Controller

The controller's job is to accept the incoming payload, verify the presence of minimal required fields (such as update_id), quickly dispatch the task to the queue, and return a successful response. The controller must not contain any database queries or external API calls.

namespace App\Http\Controllers;

use App\Jobs\ProcessTelegramUpdateJob;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class TelegramWebhookController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
$data = $request->all();

if (!isset($data['update_id'])) {
return response()->json(['error' => 'Invalid update payload'], 400);
}

ProcessTelegramUpdateJob::dispatch($data);

return response()->json(['status' => 'ok'], 200);
}
}

3. Idempotency and update_id Deduplication via Redis

Even if your server responds with a 200 status, network failures between Telegram and your provider can cause the same update_id to be redelivered. If the bot, for example, deducts a user's balance or creates an order, re-processing will lead to duplicate operations.

To ensure idempotency, we will use Redis. We'll use the SET key value EX 86400 NX command (in Laravel via Redis::set with EX and NX flags), which sets the key only if it does not already exist.

namespace App\Jobs;

use App\Services\TelegramApiService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;

class ProcessTelegramUpdateJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

public int $tries = 3;
public int $backoff = 5;

public function __construct(protected array $update) {}

public function handle(TelegramApiService $telegramService): void
{
$updateId = $this->update['update_id'] ?? null;
if (!$updateId) {
return;
}

$cacheKey = "tg_update:{$updateId}";

// Устанавливаем ключ на 24 часа (86400 сек) только если он не существовал
$isSet = Redis::set($cacheKey, 1, 'EX', 86400, 'NX');

if (!$isSet) {
Log::warning("Duplicate update_id skipped: {$updateId}");
return;
}

$this->processUpdate($telegramService);
}

protected function processUpdate(TelegramApiService $telegramService): void
{
if (isset($this->update['message'])) {
$message = $this->update['message'];
$chatId = $message['chat']['id'] ?? null;
$text = $message['text'] ?? '';

if ($chatId && $text === '/start') {
$telegramService->sendMessage([
'chat_id' => $chatId,
'text' => 'Ваш запрос успешно обработан через фоновую очередь!',
'parse_mode' => 'HTML',
]);
}
}
}
}

4. Secure cURL Client for the Bot API

In accordance with professional development standards, you should not use file_get_contents to make HTTP requests to the Telegram API. We will write a TelegramApiService with cURL requests, HTTP status code validation, JSON error checks, and logging of ok: false responses.

namespace App\Services;

use Illuminate\Support\Facades\Log;

class TelegramApiService
{
public function sendMessage(array $params): ?array
{
return $this->callApi('sendMessage', $params);
}

public function callApi(string $method, array $params = []): ?array
{
$token = config('services.telegram.bot_token');
if (empty($token)) {
Log::error('Telegram Bot Token is not set in config.');
return null;
}

$url = "https://api.telegram.org/bot{$token}/{$method}";

$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($params),
CURLOPT_TIMEOUT => 10,
CURLOPT_CONNECTTIMEOUT => 5,
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);

if ($response === false) {
Log::error("cURL error calling Telegram method {$method}: {$curlError}");
return null;
}

$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Log::error("Failed to decode Telegram JSON response for {$method}: " . json_last_error_msg());
return null;
}

if ($httpCode === 429) {
$retryAfter = $data['parameters']['retry_after'] ?? 1;
Log::warning("Telegram 429 Rate Limit for {$method}. Retry after {$retryAfter} seconds.");
return null;
}

if ($httpCode !== 200 || !($data['ok'] ?? false)) {
Log::error("Telegram API Error response for {$method}", ['response' => $data]);
return null;
}

return $data['result'] ?? [];
}
}

Common Errors When Working with Webhooks in Laravel

  • Processing third-party logic inside the controller: calling external CRMs or generating PDFs inside the controller leads to Telegram response timeouts (Telegram's wait timeout is typically around 5–10 seconds).
  • Missing secret_token: an open webhook URL without header verification allows attackers to send forged messages to your server.
  • Using file cache instead of atomic Redis operations: checking Cache::has() followed by Cache::put() is prone to race conditions in multi-threaded workers (Supervisor). The Redis::set(..., 'NX') command performs this operation atomically.

If you need assistance in developing fault-tolerant Telegram Mini Apps and complex integrations, contact the specialists at BotCreator.

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.