Verify Telegram Login Widget in PHP and Yii2: HMAC-SHA-256, auth_date, and telegram_id binding

The Telegram Login Widget returns profile fields plus a hash signed with the bot token. Every field in the payload is attacker-controllable — including id, auth_date, and first_name. Only server-side signature verification proves the payload came from Telegram.

This guide ships a verification path you can use in production:

  • receive the widget payload (id, first_name, last_name, username, photo_url, auth_date, hash);
  • recompute HMAC-SHA-256 and compare it with hash_equals;
  • enforce an auth_date window so a stolen payload cannot be replayed forever;
  • bind telegram_id to your Yii2 user (create on first login).

The widget is an identity assertion, not a full auth system. You still issue your own session.

What the widget sends

After login, Telegram appends fields as query parameters to your data-onauth callback (or JS callback). Typical payload:

id=12345678
first_name=Alex
last_name=Ivanov
username=alex_ivanov
photo_url=https%3A%2F%2Ft.me%2Fi%2Fuserpic%2F...%2F...jpg
auth_date=1716300000
hash=9f2c5b1e8a4f4d0c...e6

id arrives as a string but is always a numeric user id. auth_date is Unix seconds. hash is hex-encoded HMAC-SHA-256 (64 chars).

Verification algorithm

Build the check string from all fields except hash: key=value lines sorted by key, joined with \n. Drop empty values.

secret_key = SHA256(bot_token)   // raw 32 bytes
computed = HMAC-SHA-256(secret_key, data_check_string) // hex

The HMAC key is the binary SHA-256 of the bot token (hash('sha256', $botToken, true)). Forgetting true is the most common tutorial bug.

No Bot API call is required — everything runs locally.

Plain-PHP verifier

<?php
declare(strict_types=1);

final class TelegramLoginVerifier
{
private const CLOCK_SKEW_SECONDS = 300; // 5 minutes

public function __construct(
private readonly string $botToken,
private readonly int $now,
) {}

/**
* @param array<string, string> $payload
* @return array{ok: bool, reason?: string, profile?: array{id: int, first_name: string, last_name: ?string, username: ?string, photo_url: ?string}}
*/
public function verify(array $payload): array
{
$hash = $payload['hash'] ?? '';
unset($payload['hash']);

if ($hash === '' || !preg_match('/^[a-f0-9]{64}$/', $hash)) {
return ['ok' => false, 'reason' => 'bad_hash_format'];
}

$authDate = (int) ($payload['auth_date'] ?? 0);
if ($authDate <= 0 || abs($this->now - $authDate) > self::CLOCK_SKEW_SECONDS) {
return ['ok' => false, 'reason' => 'auth_date_expired'];
}

$pairs = [];
foreach ($payload as $k => $v) {
if ($v === '' || $v === null) {
continue;
}
$pairs[] = $k . '=' . $v;
}
sort($pairs, SORT_STRING);
$dataCheckString = implode("\n", $pairs);

$secretKey = hash('sha256', $this->botToken, true);
$computed = hash_hmac('sha256', $dataCheckString, $secretKey);

if (!hash_equals($computed, $hash)) {
return ['ok' => false, 'reason' => 'bad_signature'];
}

return [
'ok' => true,
'profile' => [
'id' => (int) $payload['id'],
'first_name' => (string) $payload['first_name'],
'last_name' => $payload['last_name'] ?? null,
'username' => $payload['username'] ?? null,
'photo_url' => $payload['photo_url'] ?? null,
],
];
}
}

Always compare the signature with hash_equals.

Wire it into Yii2

Keep the bot token in params/ENV only:

// config/params.php
return [
'telegramBotToken' => getenv('TELEGRAM_BOT_TOKEN') ?: '',
];

Add telegram_id (BIGINT UNIQUE NULL) and last_telegram_login_at to the user model. Controller:

<?php
declare(strict_types=1);

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\User;
use app\security\TelegramLoginVerifier;

final class TelegramAuthController extends Controller
{
public function actionCallback(): \yii\web\Response
{
$token = (string) Yii::$app->params['telegramBotToken'];
if ($token === '') {
throw new \yii\web\HttpException(500, 'Bot token not configured');
}

$payload = Yii::$app->request->get();
$verifier = new TelegramLoginVerifier($token, time());
$result = $verifier->verify($payload);

if (!$result['ok']) {
Yii::warning('Telegram login rejected: ' . $result['reason'], __METHOD__);
return $this->redirect(['site/login', 'error' => 'telegram_verification_failed']);
}

$profile = $result['profile'];
$user = User::findOne(['telegram_id' => $profile['id']]);

if ($user === null) {
$user = new User([
'telegram_id' => $profile['id'],
'username' => $profile['username'] ?? ('tg_' . $profile['id']),
'first_name' => $profile['first_name'],
'last_name' => $profile['last_name'],
'last_telegram_login_at' => time(),
]);
if (!$user->save(false)) {
throw new \yii\web\HttpException(500, 'Cannot create user');
}
} else {
$user->last_telegram_login_at = time();
$user->save(false, ['last_telegram_login_at']);
}

Yii::$app->user->login($user, 3600 * 24 * 30);
return $this->redirect(['site/index']);
}
}

Once telegram_id is bound, look users up only by that id. You may refresh name/username; never let the widget pick a different user row.

Production notes

  • Clock window. Five minutes is a sane default. Smaller windows break slow confirmations; larger windows widen the replay surface.
  • Token rotation. After rotating the bot token, old widget signatures fail. There is no graceful dual-token path — rotate only if you can force re-login.
  • Login Widget domain. Configure it on my.telegram.org, not BotFather. The same bot can serve the widget and Bot API; the widget does not require /start.
  • Logout. Yii::$app->user->logout() is enough. Telegram does not know your session.
  • No “double-check” Bot API calls. Skip getChat / getProfilePhotos: the hash is already a server-side signature. Extra HTTP only risks logging the token and adds latency.

If you need both Login Widget and a Mini App / bot chat for the same person, store telegram_id on your internal record from day one — that is the join key.

Need a production site ↔ Telegram login setup? Talk to BotCreator.

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.