TokenBasedRequestHandler
extends BaseRequestHandler
in package
Multi-bot webhook handler that extracts the bot token from the URL path.
Port of aiogram.webhook.aiohttp_server.TokenBasedRequestHandler (lines 249–305).
URL pattern requirement
The registered path must contain the literal placeholder {bot_token}
(snake_case, matching upstream), e.g. /webhook/{bot_token}. The
register() method enforces this and throws InvalidArgumentException
when the placeholder is absent.
Security caveat
This handler is not recommended in production because the bot token is available in the URL and can be logged by a reverse proxy server or other middleware. Use SimpleRequestHandler for single-bot deployments where the token does not appear in the URL.
Bot factory (deviation from upstream)
Upstream accepts a bot_settings dict and spreads it into Bot(token=…, **bot_settings). PHP does not allow new Bot($token, ...$settings) for
named-argument spread, so this port accepts a Closure(string $token): Bot
factory instead. The factory receives the raw token extracted from the URL
and may apply any default session/parse-mode/etc configuration before
returning the Bot instance. This is the PHP-idiomatic equivalent of
Python's **kwargs-spread construction pattern.
Secret-token validation
verifySecret always returns true. In multi-bot mode, the URL-embedded
token is the authentication surface — there is no shared Telegram secret
token to validate against.
Bot caching
resolveBot lazily instantiates Bot objects via the factory on first use
for each token, then caches them for the lifetime of the handler.
Table of Contents
Constants
- MAX_BODY_BYTES : mixed = 5 * 1024 * 1024
- Maximum number of bytes buffered from the request body.
Properties
- $data : array<string, mixed>
- Extra workflow kwargs forwarded to `Dispatcher::feedWebhookUpdate` / `feedRawUpdate` on every request.
- $dispatcher : Dispatcher
- $handleInBackground : bool
- $botFactory : Closure
- $bots : array<string, Bot>
- Lazily-constructed Bot instances keyed by their token string.
Methods
- __construct() : mixed
- awaitBackgroundTasks() : void
- Await all in-flight background tasks spawned by handleRequestBackground().
- close() : void
- Close every cached bot's underlying HTTP session and clear the cache.
- handleRequest() : Response
- Entry-point called by amphp/http-server for every incoming POST.
- register() : void
- Validate that `$path` contains the `{bot_token}` placeholder and register this handler via the supplied routing callback.
- resolveBot() : Bot
- Resolve (or lazily create) the `Bot` instance for the token found in the request attributes.
- verifySecret() : bool
- Always returns `true`.
Constants
MAX_BODY_BYTES
Maximum number of bytes buffered from the request body.
public
mixed
MAX_BODY_BYTES
= 5 * 1024 * 1024
5 MiB is far larger than any Telegram update (typically < 64 KiB) and prevents an unbounded-buffer DoS from a malicious client.
Properties
$data read-only
Extra workflow kwargs forwarded to `Dispatcher::feedWebhookUpdate` / `feedRawUpdate` on every request.
protected
array<string, mixed>
$data
$dispatcher read-only
protected
Dispatcher
$dispatcher
$handleInBackground read-only
protected
bool
$handleInBackground
= false
$botFactory read-only
private
Closure
$botFactory
$bots
Lazily-constructed Bot instances keyed by their token string.
private
array<string, Bot>
$bots
= []
Methods
__construct()
public
__construct(Dispatcher $dispatcher, callable(string $token): Bot $botFactory[, bool $handleInBackground = true ][, array<string, mixed> $data = [] ]) : mixed
Parameters
- $dispatcher : Dispatcher
- $botFactory : callable(string $token): Bot
-
Factory that builds (and optionally configures) a Bot for a given token string. Mirrors upstream's
bot_settingsdict that was spread into the Bot constructor — the factory carries the same information but is PHP- idiomatic. - $handleInBackground : bool = true
- $data : array<string, mixed> = []
-
Extra kwargs forwarded to feedWebhookUpdate.
awaitBackgroundTasks()
Await all in-flight background tasks spawned by handleRequestBackground().
public
awaitBackgroundTasks() : void
Call this during graceful shutdown (Setup::register and AmphpServer::run wire it into the onStop callback) to ensure FSM writes and outbound API calls complete before the server shuts down.
close()
Close every cached bot's underlying HTTP session and clear the cache.
public
close() : void
Called during webhook server shutdown. Safe to call when no bots have been resolved (no-op).
handleRequest()
Entry-point called by amphp/http-server for every incoming POST.
public
final handleRequest(Request $request) : Response
Flow:
- Resolve the bot for this request.
- Check the secret token header.
- Dispatch in-line or in the background depending on
$handleInBackground.
Parameters
- $request : Request
Return values
Responseregister()
Validate that `$path` contains the `{bot_token}` placeholder and register this handler via the supplied routing callback.
public
register(callable(string, RequestHandler): void $registerRoute, string $path) : void
Parameters
- $registerRoute : callable(string, RequestHandler): void
-
Callback that registers a POST route for the given path.
- $path : string
-
URL path to bind; must contain
{bot_token}(e.g./webhook/{bot_token}).
Tags
resolveBot()
Resolve (or lazily create) the `Bot` instance for the token found in the request attributes.
public
resolveBot(Request $request) : Bot
The {bot_token} value must have been captured from the URL pattern and
stored on the request as an attribute by PathRouter (or a
compatible router). Calling this method when that attribute is absent
indicates a misconfigured route registration and throws immediately.
Parameters
- $request : Request
-
The incoming HTTP request.
Tags
Return values
BotverifySecret()
Always returns `true`.
public
verifySecret(string $telegramSecretToken, Bot $bot) : bool
In multi-bot mode the URL-embedded token is the authentication surface; there is no per-bot secret token to validate.
Parameters
- $telegramSecretToken : string
-
The raw
X-Telegram-Bot-Api-Secret-Tokenheader value (ignored). - $bot : Bot
-
The resolved bot for this request (ignored).