Validate Telegram Login Widget Auth Payloads in PHP and Yii2
Integrating the official Telegram Login Widget allows users to authenticate on a web application using their Telegram account. When a user authorizes via the widget, Telegram passes authentication parameters (such as id , first_name , username , auth_date , and hash ) back to your specified redirect URL or JavaScript callback. In this tutorial, we will construct a backend validation mechanism in…
This guide provides instructions on how to validate Telegram Login Widget authentication payloads in PHP and Yii2. The payload contains various authentication parameters such as id, first_name, username, auth_date, and hash, which are passed back to the specified redirect URL or JavaScript callback when a user authorizes via the widget.
The guide outlines the steps to construct the data_check_string, generate a secret key using SHA-256, validate payload signatures using hash_equals(), and bind the verified telegram_id records in Yii2.
The Telegram Login Widget derives its secret key by taking the binary SHA-256 hash of the bot token, which differs from the literal string 'WebAppData' used in Mini App initData verification. The algorithm steps include extracting the hash parameter from the incoming payload, filtering out the hash from the remaining keys, sorting the remaining key-value pairs alphabetically by key name, formatting them as key=value joined by newline characters, and generating the secret key using hash(sha256, $botToken, true).
To validate the payload, compute the hash_hmac(sha256, $dataCheckString, $secretKey) and verify the output against the received hash using hash_equals(). Additionally, check that the auth_date is within an acceptable threshold (e.g., 86,400 seconds). The guide also provides a reusable PHP service class implementing this verification logic and demonstrates how to integrate it into a Yii2 controller action.
The bot token can be fetched from environment variables or Yii::$app->params, and the verification process ensures the authenticity and freshness of the Telegram authentication signature.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.