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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Use a dedicated Yii2 endpoint that accepts only POST requests, authenticates Telegram’s secret-token header, validates the JSON update, and places a job on a durable queue before returning a 2xx response. A worker then processes the update with idempotent side effects. This keeps slow work out of the webhook request and lets Telegram retry when delivery fails.

How the webhook-to-queue flow should work

Telegram sends HTTPS POST requests containing JSON-serialized Update objects. Configure a secret_token with setWebhook, then check the X-Telegram-Bot-Api-Secret-Token header at the application boundary. Authenticate before parsing or enqueueing the update.

The request path should do only enough work to decide whether the update is valid and to persist it for later processing. Return success only after enqueueing succeeds. Telegram retries unsuccessful webhook deliveries, but does not document a fixed retry count or retention period. Queueing before acknowledgement is a reliability design recommendation based on that retry behavior, not a Telegram or Yii requirement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Route the webhook to a dedicated POST-only endpoint.
  2. Verify the configured secret header without logging its value.
  3. Decode and check the update’s expected structure.
  4. Enqueue the update or a durable reference to it.
  5. Return a 2xx response after the queue confirms acceptance.
  6. Process it in a supervised worker, making side effects safe to repeat.

Configure one narrow POST endpoint

Use a dedicated controller for the callback rather than weakening CSRF handling across browser-facing controllers. In Yii, a controller-level CSRF exception applies to all its actions, so keep this controller limited to the webhook. A verb filter restricts the action to POST; a URL rule makes the application route explicit.

#1 Best Overall
Sale
Amazon Basics Wired QWERTY Keyboard, Works with Windows, Plug and Play, Easy to Use with Media Control, Full-Sized, Black
  • KEYBOARD: The keyboard works for Windows with hot keys that enable easy access to Media, My Computer, Mute, Volume up/down, and Calculator
  • EASY SETUP: Experience simple installation with the USB wired connection
  • VERSATILE COMPATIBILITY: This keyboard is designed to work with multiple Windows versions, including Vista, 7, 8, 10 offering broad compatibility across devices.
  • SLEEK DESIGN: The elegant black color of the wired keyboard complements your tech and decor, adding a stylish and cohesive look to any setup without sacrificing function.
  • FULL-SIZED CONVENIENCE: The standard QWERTY layout of this keyboard set offers a familiar typing experience, ideal for both professional tasks and personal use.
// config/web.php (relevant fragments)
return [
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                'telegram/webhook' => 'telegram-webhook/index',
            ],
        ],
    ],
];
<?php

namespace appcontrollers;

use Yii;
use yiifiltersVerbFilter;
use yiiwebController;
use yiiwebResponse;

final class TelegramWebhookController extends Controller
{
    // This controller must contain only machine-to-machine webhook actions.
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return array_merge(parent::behaviors(), [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'index' => ['POST'],
                ],
            ],
        ]);
    }

    public function actionIndex()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $expected = (string) Yii::$app->params['telegramWebhookSecret'];
        $received = (string) Yii::$app->request
            ->getHeaders()
            ->get('X-Telegram-Bot-Api-Secret-Token', '');

        if ($expected === '' || $received === '' || !hash_equals($expected, $received)) {
            Yii::$app->response->statusCode = 403;
            return ['ok' => false];
        }

        $rawBody = Yii::$app->request->getRawBody();
        $update = json_decode($rawBody, true);

        if (json_last_error() !== JSON_ERROR_NONE || !is_array($update)
            || !isset($update['update_id']) || !is_int($update['update_id'])) {
            Yii::$app->response->statusCode = 400;
            return ['ok' => false];
        }

        if (!$this->hasSupportedUpdate($update)) {
            Yii::$app->response->statusCode = 400;
            return ['ok' => false];
        }

        try {
            Yii::$app->queue->push(new appjobsProcessTelegramUpdateJob($update));
        } catch (Throwable $e) {
            // Log operational context, never the secret header or bot token.
            Yii::error([
                'message' => 'Could not enqueue Telegram update',
                'update_id' => $update['update_id'],
                'exception' => get_class($e),
            ], __METHOD__);

            Yii::$app->response->statusCode = 503;
            return ['ok' => false];
        }

        Yii::$app->response->statusCode = 200;
        return ['ok' => true];
    }

    private function hasSupportedUpdate(array $update)
    {
        // Replace with the update types this bot actually handles.
        foreach (['message', 'edited_message', 'callback_query'] as $key) {
            if (isset($update[$key]) && is_array($update[$key])) {
                return true;
            }
        }

        return false;
    }
}

The example assumes a Yii queue component named queue is configured and PHP has the standard JSON extension. Adapt the supported update list to the bot; Telegram’s Update object has multiple optional update fields, and accepting a field here does not mean the job must perform every possible action. Do not call external APIs or do other slow work in the controller.

Store and verify the webhook secret safely

Telegram documents the secret_token parameter as 1–256 characters, using the letters A-Z and a-z, digits, underscores, and hyphens. Keep that value and the bot API token in protected deployment configuration, not committed source code, public URLs, error messages, or request logs. Compare the supplied header with the configured value using a constant-time comparison such as PHP’s hash_equals.

For example, load the secret from an environment variable through your protected application configuration:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
// config/params.php
return [
    'telegramWebhookSecret' => getenv('TELEGRAM_WEBHOOK_SECRET') ?: '',
];

Fail closed if the expected secret is missing. A secret path can provide another recognition layer, as Telegram’s FAQ suggests, but it should not replace the header check or contain the bot API token. Treat the path as sensitive too: URLs can appear in access logs and monitoring systems.

Rank #2
Sale
Logitech MK270 Full Size Wireless Keyboard and Mouse Combo - Black
  • Reliable Plug and Play: The USB receiver provides a reliable wireless connection up to 33 ft (1), so you can forget about drop-outs and delays and you can take it wherever you use your computer
  • Type in Comfort: The design of this keyboard creates a comfortable typing experience thanks to the low-profile, quiet keys and standard layout with full-size F-keys, number pad, and arrow keys
  • Durable and Resilient: This full-size wireless keyboard features a spill-resistant design (2), durable keys and sturdy tilt legs with adjustable height
  • Long Battery Life: MK270 combo features a 36-month keyboard and 12-month mouse battery life (3), along with on/off switches allowing you to go months without the hassle of changing batteries
  • Easy to Use: This wireless keyboard and mouse combo features 8 multimedia hotkeys for instant access to the Internet, email, play/pause, and volume so you can easily check out your favorite sites

Keep CSRF protection enabled everywhere else

Yii recommends keeping CSRF protection enabled generally. Disabling it allows other sites to send POST requests to the application, so the exception should be confined to the webhook controller and paired with independent authentication. The sample uses a dedicated controller-level exception; do not add normal browser form actions to that controller.

If an application must share a controller, use an action-scoped approach supported by its Yii version, and preserve the normal controller lifecycle when overriding beforeAction(). Verify the framework’s request and controller behavior for the installed version rather than changing the request-wide CSRF setting without restoring it. Browser-facing actions should continue to use Yii’s normal CSRF validation.

Validate the update before enqueueing it

The header check must happen before JSON parsing or queue work. Then reject malformed JSON, a missing or wrongly typed update_id, and update shapes the application does not support. A non-2xx response can trigger another Telegram delivery, so validation should be deliberate: do not repeatedly reject a valid update merely because a downstream dependency is temporarily unavailable.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Keep validation limited to the JSON structure and update types the webhook contract requires.
  • Do not trust message text, usernames, callback data, or other user-controlled fields because the request authenticated successfully.
  • Return a non-2xx status for unauthenticated or invalid requests; do not reveal secrets or internal exception details in the response.
  • Log useful non-secret diagnostics, such as the update identifier and rejection category, according to your retention policy.

Telegram’s JSON body is an Update object; the bot should also configure allowed_updates to request only the update types it processes. That reduces unnecessary deliveries but does not replace application-side validation.

Rank #3
Sale
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
  • All-day Comfort: The design of this standard keyboard creates a comfortable typing experience thanks to the deep-profile keys and full-size standard layout with F-keys and number pad
  • Easy to Set-up and Use: Set-up couldn't be easier, you simply plug in this corded keyboard via USB on your desktop or laptop and start using right away without any software installation
  • Compatibility: This full-size keyboard is compatible with Windows 7, 8, 10 or later, plus it's a reliable and durable partner for your desk at home, or at work
  • Spill-proof: This durable keyboard features a spill-resistant design (1), anti-fade keys and sturdy tilt legs with adjustable height, meaning this keyboard is built to last
  • Plastic parts in K120 include 51% certified post-consumer recycled plastic*

Enqueue durably, then acknowledge

Yii::$app->queue->push() submits a job to the configured Yii2 Queue component; it does not make the work happen in the webhook process. The acknowledgement belongs after a successful push. If pushing throws or the queue cannot accept the job, return a non-2xx response so Telegram can retry rather than falsely treating an unpersisted update as handled.

For stronger durability, use a queue driver and configuration whose persistence and recovery properties meet the application’s needs. If the job payload is large or contains sensitive data, persist the update in application storage and enqueue a reference instead. Be explicit about the failure boundary: a database write and a separate queue push are not automatically one atomic transaction. If losing an update between those operations is unacceptable, use a durable handoff design, such as an outbox recorded transactionally and dispatched by a separate process.

Make job execution idempotent and bounded

Telegram can redeliver an update, and a queue can retry a failed job. The worker must therefore tolerate receiving the same update more than once. Use Telegram’s update_id as a deduplication key, backed by a database uniqueness constraint or another atomic claim mechanism. A check-then-act sequence without an atomic constraint can race when two copies run concurrently.

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

A job skeleton can implement Yii Queue’s retryable-job interface. The exact retry support and behavior depend on the installed extension version and driver.

Rank #4
Sale
Redragon K521 Upgrade Rainbow LED Gaming Keyboard, 104 Keys Wired Mechanical Feeling Keyboard with Multimedia Keys, One-Touch Backlit, Anti-Ghosting, Compatible with PC, Mac, PS4/5, Xbox
  • 【Dreamy Rainbow Gaming Keyboard】K521 Gaming Keyboard Adopts a Different LED Backlight Design, Upgraded on the Traditional LED Backlight Effect, Making the Light More Penetrating, Giving You a More Dazzling Visual Effect, Making Your Gaming Process More Enjoyable
  • 【One Touch Opens & Visual Feast】The K521 Red Dragon Keyboard has a One-Touch on/off Lighting Button for Added Convenience. It also has a Three-Position Adjustable Breathing Mode and a Four-Position Adjustable Brightness Lighting Mode
  • 【Mechanical Feeling & Fast Tapping】The PC Keyboard Keys are Designed for Mechanical Feeling, Giving You a Better Feel During Use and the Ability to Trigger Keys Quickly, Allowing You to Win All Your Games
  • 【19 Keys Anti-Ghosting Keyboard】Anti-Ghosting Ensures Every Button Can Be Triggered. This Allows You to Trigger Key Combinations In The Game Accurately, And Each Skill Can Be Accurately Released to Increase Your Winning Rate. Redragon K521 Will Be Your Perfect Partner
  • 【12 Multimedia Combination Keys】The K521 Wired Gaming Keyboard is Equipped with 12 Multimedia Keys That Can Greatly Enhance Your Gaming/Office Efficiency and Make It More Convenient to Use
<?php

namespace appjobs;

use yiiqueueRetryableJobInterface;

final class ProcessTelegramUpdateJob implements RetryableJobInterface
{
    public $update;

    public function __construct(array $update)
    {
        $this->update = $update;
    }

    public function execute($queue)
    {
        $updateId = $this->update['update_id'];

        // Implement this with an atomic insert/claim guarded by a unique
        // constraint on update_id. If already completed, return safely.
        if (!$this->claimUpdateOnce($updateId)) {
            return;
        }

        // Process supported update types. Coordinate external side effects
        // with durable state or provider-side idempotency where available.
        $this->processUpdate($this->update);
    }

    public function getTtr()
    {
        return 120;
    }

    public function canRetry($attempt, $error)
    {
        // Example policy only: tune to the job and configured backend.
        return $attempt < 5 && $this->isTemporaryFailure($error);
    }

    private function claimUpdateOnce($updateId) { /* application-specific */ }
    private function processUpdate(array $update) { /* application-specific */ }
    private function isTemporaryFailure(Throwable $error) { /* application-specific */ }
}

The methods marked application-specific are deliberate: Yii and the queue driver cannot determine how your database transaction or external side effects should behave. If processing an update must both record completion and perform an external action, a crash can occur between those steps. Use a transactional outbox, an idempotency key supported by the downstream service, or a recoverable state machine to close that gap.

Set time-to-reserve (TTR) long enough for a normal execution but bounded, and limit attempts. Separate temporary dependency failures, which may succeed on retry, from permanent invalid jobs, which should not retry indefinitely. Yii Queue exposes component defaults and per-job retry behavior, but retry/status capabilities vary across backends; consult the guide matching the installed extension version and selected driver before relying on a particular feature.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Select and operate a queue driver

Yii2 Queue documents driver families including database, Redis, RabbitMQ, AMQP Interop, and Beanstalk, with availability and behavior depending on extension version. There is no universal best driver for a Telegram bot. Choose based on what the team already operates and can recover, plus the persistence guarantees, retry or dead-letter behavior, worker model, observability, and status features the workload needs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Decision factor What to verify
Existing infrastructure Whether the team can operate, secure, back up, and restore the selected service.
Persistence and recovery What happens to queued and in-flight jobs after process or host failure, and how recovery is performed.
Retries and failed jobs Whether the installed driver supports the retry, attempt, TTR, and status behavior your policy requires.
Workers Whether the driver supports a persistent listener or requires a different execution pattern.
Observability How operators inspect queue depth, failures, job age, and worker health.

Confirm the installed Yii2 Queue extension version, driver documentation, and PHP/runtime requirements before copying worker commands. A queue component configured in the web application is not a substitute for running the worker.

Best Value
Sale
Logitech K270 Full Size Wireless Keyboard for Windows - Black
  • All-day Comfort: This USB keyboard creates a comfortable and familiar typing experience thanks to the deep-profile keys and standard full-size layout with all F-keys, number pad and arrow keys
  • Built to Last: The spill-proof (2) design and durable print characters keep you on track for years to come despite any on-the-job mishaps; it’s a reliable partner for your desk at home, or at work
  • Long-lasting Battery Life: A 24-month battery life (4) means you can go for 2 years without the hassle of changing batteries of your wireless full-size keyboard
  • Simply plug the USB receiver into a USB port on your desktop, laptop or netbook computer and start using the keyboard right away without any software installation
  • Simply Wireless: Forget about drop-outs and delays thanks to a strong, reliable wireless connection with up to 33 ft range (5); K270 is compatible with Windows 7, 8, 10 or later

Run workers under supervision

For drivers that support persistent workers, run the queue listener under a process supervisor such as Supervisor or systemd so a crash or reboot does not silently stop processing. The Yii Queue documentation also describes scheduled execution patterns, including queue/run for supported drivers. Use the command and mode documented for the actual driver and extension version; do not assume every backend behaves identically.

  • Run workers with a dedicated, least-privilege operating-system account.
  • Set process restart behavior and shutdown handling appropriate to the job workload.
  • Monitor worker liveness, queue depth, oldest pending job, and repeated failures.
  • Ensure deployments restart workers when code or configuration changes.
  • Keep worker logs free of bot tokens, webhook secrets, and unnecessary personal data.

Configure Telegram delivery and troubleshoot failures

The Telegram Bot API accepts a max_connections value from 1 to 100 and documents a default of 40. Choose a value that fits the server’s ability to accept requests and persist jobs; it is not a queue throughput guarantee. Include allowed_updates in setWebhook when only a subset of update types is needed.

Telegram requires HTTPS for webhooks and currently lists ports 443, 80, 88, and 8443. A non-default supported port must appear in the webhook URL. The endpoint needs a valid certificate and direct routing; redirects and certificate or hostname mismatches are common causes of delivery trouble. Telegram’s instructions call for certificate upload in self-signed setups. Recheck the current official networking instructions when deploying, since these details can change.

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

Start diagnosis with Telegram’s getWebhookInfo, which exposes the configured URL, pending update count, current IP address, and most recent delivery error timestamp when available. Then inspect reverse-proxy access logs, application rejection logs without secrets, queue depth, and worker failures.

Quick Recap

SaleBestseller No. 1
SaleBestseller No. 3
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
Logitech K120 Full Size Wired Keyboard USB Plug-and-Play Windows - Black
Plastic parts in K120 include 51% certified post-consumer recycled plastic*; Product carbon footprint: 4.02 kg CO2e
$12.39
SaleBestseller No. 5
Logitech K270 Full Size Wireless Keyboard for Windows - Black
Logitech K270 Full Size Wireless Keyboard for Windows - Black
Plastic parts in K270 include 38% certified post-consumer recycled plastic; Eight hot keys: For instant access to the Internet, e-mail, music volume and more
$21.48
  • No request reaches the application: Check the webhook URL, DNS/routing, HTTPS certificate and hostname, supported port, and proxy logs.
  • Requests arrive but are rejected: Confirm the secret was configured with setWebhook, the proxy preserves the header, and the app reads the same header name. Never print the value while debugging.
  • Telegram reports delivery errors or pending updates grow: Check response status codes and whether the queue push completed before acknowledgement.
  • Queue depth grows while webhook requests succeed: Verify the worker is running, its driver configuration matches the web application, and failed jobs or dependencies are not blocking progress.
  • Updates appear more than once: Treat delivery and job execution as at-least-once in practice; confirm the update identifier is protected by atomic deduplication and side effects are retry-safe.

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.