October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Build a Lightweight Telegram Webhook Handler in Laravel 13 with Queues and Feature Tests

A practical Laravel 13 guide to verifying Telegram webhook requests, queueing updates outside the HTTP request, writing feature tests, and checking deployment settings.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a lightweight Telegram webhook in Laravel, verify Telegram’s configured secret token, dispatch the decoded update to a queued job, and return a successful HTTP response without doing the business work in the request. This keeps delivery handling separate from slower processing and makes the endpoint straightforward to cover with feature tests. The examples below target Laravel 13.x; check your installed Laravel version before copying route, middleware, or testing APIs because application structures differ across releases.

How do I create a Telegram webhook in Laravel?

Telegram sends an HTTPS POST containing a JSON-serialized Update to the URL registered with setWebhook. The Laravel endpoint should do only the work needed to authenticate the request, obtain a usable update, enqueue it, and acknowledge receipt.

As an Amazon Associate I earn from qualifying purchases.

For Laravel 13.x, add a POST route in the route file used for your application’s public HTTP endpoints. Laravel project structures and middleware configuration vary by version, so confirm the appropriate route file and middleware behavior in the documentation for your installed release.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
use AppHttpControllersTelegramWebhookController;
use IlluminateSupportFacadesRoute;

Route::post('/telegram/webhook', TelegramWebhookController::class);

A controller can keep the request path small by validating the header before dispatching a job. Put the bot API token and webhook secret in server-side configuration, such as environment-backed config; do not hard-code either value in source control.

namespace AppHttpControllers;

use AppJobsProcessTelegramUpdate;
use IlluminateHttpRequest;
use SymfonyComponentHttpFoundationResponse;

class TelegramWebhookController
{
    public function __invoke(Request $request): Response
    {
        $expectedSecret = config('services.telegram.webhook_secret');
        $providedSecret = $request->header('X-Telegram-Bot-Api-Secret-Token');

        if (! is_string($expectedSecret) || $expectedSecret === '' ||
            ! is_string($providedSecret) || ! hash_equals($expectedSecret, $providedSecret)) {
            abort(403);
        }

        $update = $request->json()->all();
        if ($update === []) {
            abort(400, 'Invalid Telegram update.');
        }

        ProcessTelegramUpdate::dispatch($update);

        return response()->noContent();
    }
}

This example returns HTTP 204 for an accepted update. A successful 2xx response acknowledges delivery; returning a non-2xx response causes Telegram to retry delivery and eventually abandon it after a reasonable number of attempts. Telegram does not specify a precise retry schedule, so avoid designing logic around a fixed retry interval. See the Telegram Bot API.

The empty-array check is only a minimal shape guard. If your application requires a particular update structure, validate that contract explicitly and return a client error for invalid payloads. A job should also be safe to run more than once if duplicate delivery could cause duplicate side effects.

How do I verify the Telegram webhook secret token?

When registering the webhook, configure a distinct secret_token. Telegram sends its value in the X-Telegram-Bot-Api-Secret-Token header, which the controller compares with the server-side secret before dispatching anything. Do not use the bot API token as this webhook secret: the two credentials serve different purposes.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Telegram’s Bot API documents this header behavior in setWebhook. The constant-time comparison in the example uses PHP’s hash_equals; also ensure the configured secret is present, as shown, rather than treating an absent configuration value as valid.

The Telegram Bots FAQ also recommends a hard-to-guess secret path as an additional way to make the webhook URL less discoverable. A secret path can supplement header verification, not replace it or sound secret storage.

How do I queue Telegram bot updates in Laravel?

Keep business logic in a job rather than running it during the webhook request. A queue lets the endpoint hand off time-intensive work and respond promptly; Laravel presents a common queue API across backends such as Amazon SQS, Redis, and a relational database. Choose the connection that fits the application’s existing deployment rather than treating any particular backend as a Telegram requirement. See Laravel’s queue documentation.

namespace AppJobs;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;
use IlluminateQueueInteractsWithQueue;
use IlluminateQueueSerializesModels;

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

    public function __construct(public array $update)
    {
    }

    public function handle(): void
    {
        // Apply application-specific update handling here.
    }
}

Configure the queue connection and run the worker using the setup appropriate to that backend and deployment. A queue fake in a feature test proves that the request dispatched the job; it does not execute or prove the job’s update-handling logic. Test that logic separately.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I test a Laravel webhook with feature tests?

Laravel’s HTTP testing tools simulate requests inside the application, so the webhook can be tested without a real Telegram delivery. Use postJson to send the JSON request and queue fakes and assertions to verify dispatch behavior. Laravel documents these APIs in HTTP Tests and Queues.

The following examples assume the controller, route, and job above, and a test environment in which the configured secret is test-webhook-secret. They show one HTTP request per feature test.

namespace TestsFeature;

use AppJobsProcessTelegramUpdate;
use IlluminateSupportFacadesQueue;
use TestsTestCase;

class TelegramWebhookTest extends TestCase
{
    public function test_valid_update_is_queued(): void
    {
        Queue::fake();
        config(['services.telegram.webhook_secret' => 'test-webhook-secret']);

        $update = ['update_id' => 123, 'message' => ['text' => 'Hello']];

        $this->postJson('/telegram/webhook', $update, [
            'X-Telegram-Bot-Api-Secret-Token' => 'test-webhook-secret',
        ])->assertNoContent();

        Queue::assertPushed(ProcessTelegramUpdate::class, function ($job) use ($update) {
            return $job->update === $update;
        });
        Queue::assertPushed(ProcessTelegramUpdate::class, 1);
    }

    public function test_missing_or_incorrect_secret_is_rejected_without_queueing(): void
    {
        Queue::fake();
        config(['services.telegram.webhook_secret' => 'test-webhook-secret']);

        $this->postJson('/telegram/webhook', ['update_id' => 123], [
            'X-Telegram-Bot-Api-Secret-Token' => 'wrong-secret',
        ])->assertForbidden();

        Queue::assertNothingPushed();
    }
}

Keep missing-secret and incorrect-secret requests as separate tests if you want each failure case explicit; the example groups them for brevity and demonstrates the incorrect-secret case. For the missing-header case, omit the header argument and assert the same rejection and no-job behavior. If the controller validates update shape, add a malformed-payload case that asserts the chosen client-error response and confirms no job was queued. Laravel’s testing guidance covers feature tests and its supported Pest and PHPUnit workflows at Testing.

These are documented-API test patterns, not claims that the examples have been executed against a particular project. Adapt namespaces, route location, configuration, and status assertions to your application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

How do I configure and verify the deployed Telegram webhook?

Register an HTTPS URL and the same secret value used by Laravel. Telegram’s Bot API identifies supported public webhook ports as 443, 80, 88, and 8443. Its webhook guide requires TLS 1.2 or later and a certificate whose identity matches the webhook host; redirects are unsupported. Check the current webhook guide before deployment, especially if your firewall relies on Telegram IP ranges, because those ranges may change.

For example, the API request body for setWebhook can include the URL, secret, and only the update types the bot needs:

{
  "url": "https://example.com/telegram/webhook",
  "secret_token": "your-server-side-webhook-secret",
  "allowed_updates": ["message", "callback_query"]
}

Send that JSON to Telegram’s setWebhook method using the bot API token in the method URL or request authorization as specified by Telegram. Keep the bot token private. The sample deliberately uses a placeholder domain and secret; replace them with your deployment’s HTTPS endpoint and independently generated secret.

Select allowed_updates according to features your bot actually handles. Telegram notes that an empty list excludes some update types, including chat_member, message_reaction, and message_reaction_count; omitting the parameter preserves the previous setting. Telegram’s current Bot API page, version 10.3 dated August 24, 2026, documents max_connections from 1 to 100 with a default of 40. This is an API option, not a universal throughput recommendation; choose deliberately for your deployment and re-check the current specification.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

After registering the webhook, call getWebhookInfo and inspect the returned URL, pending update count, and any last error details. This helps distinguish an application-level rejection from an endpoint, certificate, or delivery problem. Consult Telegram’s current Bot API documentation for the live fields and setup behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.