Telegram Integration in Laravel Without Magic: Building a Thin HTTP Client, Webhook, Queues, and Testing

Developers integrating Telegram Bot API into Laravel applications often make one of two mistakes: they either pull in a heavy third-party SDK with an outdated Singleton pattern, or turn the Webhook controller into a monolithic script that performs synchronous HTTP requests and heavy business logic right during incoming request processing.

In this article, we will walk through a production-ready architecture for Laravel: we will build a thin wrapper client on top of Illuminate\Support\Facades\Http, configure Secret Token verification for Webhooks, set up idempotent update processing in queues, and cover it all with fast Feature tests without making real network requests to Telegram.

Choosing an Architecture: Off-the-Shelf SDK or Custom HTTP Client?

Popular packages like irazasyed/telegram-bot-sdk or nutgram/nutgram offer out-of-the-box command routing patterns inside the bot. However, in large Laravel projects (CRM, SaaS, Mini Apps) where Telegram is just one of several communication channels, ready-made packages create unnecessary issues:

  • Customization complexity: intercepting HTTP errors, additional logging, and integration with metrics (Prometheus/Bugsnag) require overriding the deep internals of a third-party package.
  • Testing challenges: mocking third-party package facades in Laravel unit and integration tests is harder than using the framework's standard HTTP mocking mechanisms.
  • Redundancy: Laravel's built-in Http facade provides more than enough capabilities for sending notifications, generating keyboards, and receiving Webhooks.

Using your own HTTP client gives you full control over logging, timeouts, retry policies, and data typing.

Step 1. Configuration and Thin TelegramHttpClient

Let's create a service for sending requests to the Telegram Bot API. We will extract the bot token and secret webhook token to config/services.php and load them strictly via переменные окружения getenv() or .env.

namespace App\Services\Telegram;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use RuntimeException;

class TelegramClient
{
protected string $baseUrl;

public function __construct(
protected string $token,
protected int $timeout = 5
) {
$this->baseUrl = "https://api.telegram.org/bot{$this->token}";
}

public function sendMessage(int|string $chatId, string $text, array $replyMarkup = []): array
{
return $this->request('sendMessage', [
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'HTML',
'reply_markup' => $replyMarkup ? json_encode($replyMarkup) : null,
]);
}

public function request(string $method, array $params = []): array
{
$response = Http::timeout($this->timeout)
->retry(3, 100, fn ($exception) => $exception instanceof \Illuminate\Http\Client\ConnectionException)
->post("{$this->baseUrl}/{$method}", array_filter($params, fn ($val) => $val !== null));

if (!$response->successful()) {
Log::error("Telegram API HTTP Error: {$response->status()}", ['body' => $response->body()]);
throw new RuntimeException("Telegram HTTP Request failed with status {$response->status()}");
}

$data = $response->json();
if (!is_array($data) || !($data['ok'] ?? false)) {
Log::error('Telegram API Logical Error', ['response' => $data]);
throw new RuntimeException('Telegram API Error: ' . ($data['description'] ?? 'Unknown error'));
}

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

Let's register the service in AppServiceProvider for automatic Dependency Injection:

$this->app->singleton(TelegramClient::class, function () {
return new TelegramClient(config('services.telegram.bot_token'));
});

Step 2. Secure Webhook Controller and Idempotency

Telegram requires the Webhook endpoint to respond with a 200 OK status code within a few seconds. Any long-running operations (database queries, external APIs, calculations) will cause a timeout on Telegram's side and lead to resending the same event.

The controller must fulfill three tasks: verify the secret X-Telegram-Bot-Api-Secret-Token header, protect against duplicates by update_id, and dispatch the incoming array to a processing queue.

namespace App\Http\Controllers;

use App\Jobs\ProcessTelegramUpdateJob;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class TelegramWebhookController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
$secretToken = config('services.telegram.secret_token');
$headerToken = $request->header('X-Telegram-Bot-Api-Secret-Token');

if ($secretToken && !hash_equals($secretToken, (string) $headerToken)) {
return response()->json(['error' => 'Invalid secret token'], 403);
}

$update = $request->all();
$updateId = $update['update_id'] ?? null;

if (!$updateId) {
return response()->json(['status' => 'ignored'], 200);
}

// Защита от дублирования через атомарный замок Redis/Cache
$lockKey = "telegram_update_lock:{$updateId}";
if (!Cache::add($lockKey, true, 3600)) {
return response()->json(['status' => 'duplicate_ignored'], 200);
}

ProcessTelegramUpdateJob::dispatch($update);

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

Step 3. Background Job for Business Logic and Command Processing

All user interaction logic moves to a Laravel Queue Job. When processing deep-link parameters like t.me/Bot?start=payload, we extract the start argument, generate a unique request identifier, and save it to PostgreSQL/MySQL.

namespace App\Jobs;

use App\Services\Telegram\TelegramClient;
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\DB;

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

public function __construct(public array $update) {}

public function handle(TelegramClient $telegram): void
{
$message = $this->update['message'] ?? null;
if (!$message || !isset($message['text'])) {
return;
}

$chatId = $message['chat']['id'];
$text = trim($message['text']);

if (str_starts_with($text, '/start')) {
$payload = trim(substr($text, 6));
$leadId = null;

if ($payload !== '') {
$leadId = bin2hex(random_bytes(7));
DB::table('leads')->insert([
'lead_id' => $leadId,
'chat_id' => $chatId,
'source_payload' => $payload,
'created_at' => now(),
]);
}

$replyText = $leadId
? "Здравствуйте! Ваша заявка <b>#{$leadId}</b> принята в работу."
: "Добро пожаловать! Чем мы можем вам помочь?";

$telegram->sendMessage($chatId, $replyText);
}
}
}

Step 4. Testing Without External Network Requests

Thanks to the Http facade and Laravel queues, you can fully test the "Webhook -> Queue -> Telegram API" chain in milliseconds without sending real network requests.

namespace Tests\Feature;

use App\Jobs\ProcessTelegramUpdateJob;
use App\Services\Telegram\TelegramClient;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;

class TelegramIntegrationTest extends TestCase
{
use RefreshDatabase;

public function test_webhook_validates_secret_token_and_dispatches_job(): void
{
Bus::fake();

$secret = 'super_secret_string';
config(['services.telegram.secret_token' => $secret]);

$payload = [
'update_id' => 9991234,
'message' => [
'message_id' => 10,
'chat' => ['id' => 777000, 'type' => 'private'],
'text' => '/start ref_promo_2024',
],
];

$response = $this->withHeaders([
'X-Telegram-Bot-Api-Secret-Token' => $secret,
])->postJson('/api/telegram/webhook', $payload);

$response->assertStatus(200)->assertJson(['status' => 'queued']);

Bus::assertDispatched(ProcessTelegramUpdateJob::class, function ($job) {
return $job->update['update_id'] === 9991234;
});
}

public function test_telegram_client_handles_send_message_correctly(): void
{
Http::fake([
'https://api.telegram.org/bot*/sendMessage' => Http::response([
'ok' => true,
'result' => ['message_id' => 555],
], 200),
]);

$client = new TelegramClient('fake_token');
$result = $client->sendMessage(777000, 'Тестовое сообщение');

$this->assertEquals(555, $result['message_id']);

Http::assertSent(function ($request) {
return str_contains($request->url(), '/sendMessage')
&& $request['chat_id'] === 777000
&& $request['text'] === 'Тестовое сообщение';
});
}
}

Common Pitfalls and Performance Nuances

  • Forgotten CSRF exclusion: The Webhook в Laravel route must be placed in routes/api.php or excluded from the ValidateCsrfToken middleware if registered in the web group.
  • Synchronous data fetching: Never make the Webhook wait for a third-party CRM response or PDF generation. The controller must send the response status and terminate the HTTP connection immediately.
  • Lack of HTTP 429 handling: When sending messages to multiple chats, Telegram may return a 429 Too Many Requests error. Using the retry() method with a pause in your client protects your application from losing messages during brief traffic spikes.

If you need expert assistance in designing high-load Telegram bots and integrating Telegram Mini Apps with your infrastructure, 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.