Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober 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 Scan×
Skip to content
World desk7 min

Build a Secure, Queued Telegram Webhook Controller in Yii2

A secure Yii2 Telegram webhook authenticates the secret header, validates and durably enqueues each update before returning success, then relies on idempotent jobs and supervised workers.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Yii2, authenticate Telegram’s webhook request with the configured X-Telegram-Bot-Api-Secret-Token header, validate the JSON update, persist it to a queue, and only then return a 2xx response. Keep CSRF protection enabled everywhere else, make job effects idempotent, and run the queue worker under supervision. Telegram documents the HTTPS POST, secret header, and retries for unsuccessful responses; the queue-and-acknowledge design is an application reliability pattern built around those behaviors.

How the webhook should work

Telegram sends an HTTPS POST containing a JSON-serialized Update object. If a webhook response is outside the 2xx range, Telegram retries delivery and eventually stops after a “reasonable amount of attempts”; its Bot API description does not specify a fixed retry count or retention window. That makes a fast response useful, but acknowledging before the update is safely accepted risks losing work.

As an Amazon Associate I earn from qualifying purchases.

  1. Receive a POST at one dedicated route.
  2. Check Telegram’s configured secret header before parsing or processing the update.
  3. Validate the update envelope and enqueue it durably, or persist an inbox record for later processing.
  4. Return 2xx only after that durable acceptance succeeds.
  5. Let a supervised worker perform slower application work, with idempotency protections for duplicate deliveries and queue retries.

Telegram documents the delivery and retry behavior. Enqueue-before-acknowledgement is a reliability recommendation, not a Telegram or Yii requirement. It does not make the whole workflow exactly-once: a process can accept a job and fail before Telegram receives the response, causing Telegram to send the same update again.

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

Register one POST route and limit the CSRF exception

Keep the endpoint separate from browser-facing actions. For example, add an explicit POST rule in the application’s URL manager:

#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.
'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        'POST webhook/telegram' => 'telegram-webhook/receive',
    ],
],

Yii recommends leaving CSRF protection enabled generally. Its security guide warns that disabling it allows any site to send POST requests to the application. If the machine-to-machine callback must bypass Yii’s browser-oriented CSRF check, disable it only for this action and use independent authentication—the Telegram secret header—on every request. The following controller uses the action-sensitive lifecycle pattern shown in Yii’s security guidance:

<?php

namespace appcontrollers;

use Yii;
use yiiwebController;
use yiiwebResponse;
use appjobsProcessTelegramUpdateJob;

class TelegramWebhookController extends Controller
{
    public function beforeAction($action)
    {
        if ($action->id === 'receive') {
            $this->enableCsrfValidation = false;
        }

        return parent::beforeAction($action);
    }

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

        $expectedSecret = getenv('TELEGRAM_WEBHOOK_SECRET');
        $receivedSecret = Yii::$app->request->headers
            ->get('X-Telegram-Bot-Api-Secret-Token');

        if (!is_string($expectedSecret) || $expectedSecret === ''
            || !is_string($receivedSecret) || $receivedSecret === ''
            || !hash_equals($expectedSecret, $receivedSecret)) {
            Yii::$app->response->statusCode = 401;
            return ['error' => 'unauthorized'];
        }

        $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 ['error' => 'invalid_update'];
        }

        try {
            Yii::$app->queue->push(new ProcessTelegramUpdateJob([
                'update' => $update,
            ]));
        } catch (Throwable $e) {
            // Log a safe diagnostic; do not log the secret or raw update.
            Yii::error([
                'message' => 'Telegram webhook enqueue failed',
                'exception_class' => get_class($e),
            ]);
            Yii::$app->response->statusCode = 503;
            return ['error' => 'temporarily_unavailable'];
        }

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

The example checks that the body decodes to an object-like associative array with an integer update_id. It deliberately does not assume every update contains a message: Telegram updates can represent different event types. Add validation for the update types your application handles, and decide how to record valid but unsupported types so they do not trigger needless retries. A malformed request receives a non-2xx response; a valid request should be accepted or deliberately recorded before acknowledgement.

Configure and verify Telegram’s webhook

Call the Bot API setWebhook method with the public endpoint, the optional secret_token, and the update types the bot needs. Telegram’s documented secret-token value is 1–256 characters and may contain Latin letters, digits, underscores, and hyphens. Keep it distinct from the Bot API token; store both in protected deployment configuration rather than source code, public URLs, or logs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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

Telegram requires HTTPS and currently documents webhook ports 443, 80, 88, and 8443. The endpoint needs a valid certificate and hostname, and Telegram must be able to reach it directly. The webhook URL should resolve to the callback without redirects; Telegram’s FAQ identifies redirects and certificate or hostname mismatches as common causes of trouble. For a non-default supported port, include that port in the configured URL. Self-signed certificate setups require certificate upload as described in Telegram’s webhook instructions. Recheck Telegram’s current networking documentation at deployment time because these details can change.

Use allowed_updates to request only event types the bot processes. Telegram documents max_connections as accepting 1–100, with a default of 40. Treat that as a delivery-concurrency setting, not as a queue throughput guarantee: choose it in light of web-server capacity and the speed with which the endpoint can authenticate and enqueue requests.

Choose a queue driver for the operational constraints

Yii2 Queue supports several driver families, including database, Redis, RabbitMQ, AMQP Interop, and Beanstalk, depending on the installed extension version. There is no universally best backend established for every bot. Match the driver to infrastructure already operated reliably and evaluate these factors before configuring it:

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*
  • Persistence and recovery: determine what happens to accepted jobs during a process restart, host failure, or backend recovery.
  • Retry and failure handling: verify how the selected driver handles attempts, reserved jobs, failures, and any dead-letter or inspection workflow you need.
  • Worker deployment: confirm whether the driver supports a persistent listener, one-shot execution, or both in the installed extension version.
  • Visibility: decide how operators will observe queue depth, job failures, and worker health.
  • Operations fit: account for existing monitoring, backup, access-control, and maintenance practices for the backend.

The controller’s push() call is not proof that a chosen backend has the durability characteristics your application needs. Configure and operate the backend accordingly, and check the guide matching the installed Yii2 Queue version and driver. The official extension documentation describes component-level time-to-reserve and attempt defaults, per-job customization through RetryableJobInterface, and driver-specific limitations.

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

Make queued work safe to retry

Use Telegram’s update_id as the input to an application-level idempotency strategy. Duplicate jobs can arise both when Telegram retries after an uncertain response and when a worker retries a failed job. A job should not repeat an irreversible business effect just because it runs again.

  • For database effects, record processed update IDs with a unique constraint and make the state change transactional where practical. Avoid a check-then-act sequence that lets two workers race.
  • For external side effects, use the destination service’s idempotency mechanism where available, or persist an outbox/state transition that lets the application safely resume.
  • Distinguish transient failures, such as a temporarily unavailable dependency, from permanent invalid work. Retry only the former according to an explicit policy.
  • Set a bounded attempt policy and time-to-reserve (TTR) based on the job’s expected maximum execution time and the selected driver’s semantics. A reservation that expires while a job is still running can permit concurrent processing.
  • Keep job payloads to the necessary update data or a durable reference. Telegram updates may contain user data; avoid logging raw payloads unless there is a deliberate privacy and retention policy.

A minimal job class can implement Yii2 Queue’s retry interface; adapt its retry rules and signatures to 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 yiibaseBaseObject;
use yiiqueueRetryableJobInterface;

class ProcessTelegramUpdateJob extends BaseObject implements RetryableJobInterface
{
    public $update;

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

        // Use an atomic, persistent idempotency check before side effects.
        // Dispatch only update types this application supports.
    }

    public function getTtr()
    {
        return 120;
    }

    public function canRetry($attempt, $error)
    {
        return $attempt < 5 && $this->isTransientFailure($error);
    }

    private function isTransientFailure($error)
    {
        // Classify exceptions from this application's dependencies.
        return false;
    }
}

The values in this illustrative job are policy examples, not universal Yii defaults or tested deployment values. Coordinate the job’s TTR and retry decisions with queue component defaults and the driver’s actual behavior. Do not automatically retry every exception: a permanent validation or programming error can otherwise cycle pointlessly.

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

Run and supervise the worker

Enqueueing alone does not execute jobs. Start the worker process for the selected driver and keep it alive with a process supervisor such as Supervisor or systemd when persistent workers are supported. Yii2 Queue also documents scheduled or one-shot operation for supported drivers; the exact command semantics depend on the installed extension and driver.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
php yii queue/listen
php yii queue/run

Use the command appropriate to the deployment: a listener is intended for a persistent worker model, while a one-shot command can be run by a scheduler where supported. Before copying either command into production, confirm the installed extension version, driver support, PHP runtime requirements, and shutdown behavior in the matching Yii2 Queue guide. Configure the supervisor to restart failed workers and route logs to an operationally monitored destination; alert on repeated restarts and persistent job failures.

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

Diagnose delivery and processing separately

Start with Telegram’s getWebhookInfo when updates do not appear. The Bot API exposes the configured webhook URL, pending update count, current IP address, and the latest delivery error timestamp where available. Pair that with application-side checks:

  • Inspect reverse-proxy access logs for requests to the exact webhook route, status codes, and redirects.
  • Inspect authentication and validation outcomes without recording the secret header, Bot API token, or full update body.
  • Check queue depth and enqueue failures to determine whether requests reached the application but were not accepted by the backend.
  • Check worker health, exception logs, retry counts, and idempotency records to locate failures after enqueueing.

If Telegram reports delivery errors, verify the public URL, TLS certificate and hostname, supported port, direct routing, and route method first. If Telegram reports no current delivery problem but the queue is growing, focus on worker availability and processing failures rather than changing webhook authentication.

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

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.

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

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
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

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.