There are two main ways to log in to the site through Telegram: the official widget (the user clicks the button on the site and confirms the login) or through the generation of a one-time code/QR code inside the bot itself.
The simplest and most standard option is described in detail below —official Telegram authorization widget (Telegram Login Widget).
Step 1: Create and configure a bot
For authorization to work, you definitely need a Telegram bot to which your site's domain will be linked.
-
Find the official bot@BotFatherin Telegram and launch it.
-
Create a new bot with the help of the team
/newbot, give it a name and a unique username (for example,my_site_auth_bot). -
Link the site domain to the bot:
-
-Send OFF1 command
/setdomain. -
Select your bot.
-
Enter your website address (ex.
https://example.com).
Note: For local testing, you can specify
https://localhostorhttp://127.0.0.1, but Telegram requires HTTPS for the main production domain. -
Step 2: Get the widget code for the site
Telegram provides a ready-made button designer.
-
Go to the official pageTelegram Login Widget.
-
In the configurator section, enter the username of your bot (without the symbol
@), select button size, avatar display, and authorization type:-
Callback Request— the data will be passed to the JavaScript function directly on the page.
-
Redirect to URL— the user will be redirected to the specified URL after authorization (for example,
https://example.com/tg_auth.php), where the user parameters will be sent by the get request.
-
-
Copy the generated script and paste it into the HTML code of your login page.
Sample code for the redirect button:
<SCRIPT ASYNC src="https://telegram.org/js/telegram-widget.js?22"
data-telegram-login="YOUR_BOT_NAME"
data-size=Large
data-auth-url="https://example.com/tg_auth.php"
data-request-access=WRITE></SCRIPT>
Propertydata-request-access="write"optional, but it allows the bot to send messages to the user in the future).
Step 3: Processing data on the server (Security)
When the user clicks the button and allows login, Telegram redirects him to your script (in the example —tg_auth.php) and transmits profile data in get parameters:id, first_name, username, photo_url, auth_dateAndhash.
It is critical to verify the authenticity of this datato prevent an attacker from forgingidand log into someone else's account.
Security check algorithm (on the example of PHP):
-
All received parameters are collected (except
hash), sorted alphabetically and glued into a format stringKey value, separated by a line break (\n). -
A secret key is created: a SHA256 hash is taken from the token of your bot (which issued @BotFather).
-
The HMAC-SHA256 from the glued data string is calculated using the secret key.
-
The result obtained is compared with the parameter
hashsent by Telegram. If they match, the data is genuine.
PHP(PHP 3, PHP 4)'BOT_TOKEN', 'YOUR_BOT_TOKEN_HERE'); // Token of your bot
$auth_data = get;
$check_hash = $auth_data[hash];
unset($auth_data[hash]);
// 1. Sorting parameters
$data_check_arr = [];
Next ($auth_data as Key => $value$) {
$data_check_arr[] = Key . '=' . $value$sort$data_check_arr);
$data_check_string= implode(No., $data_check_arr);
// 2. Create a secret key from the bot token
Secret KeyhashSHA256, BOT_TOKEN,true);
// 3. Calculate the hash of the data string
hash= hash_hmac(SHA256, $data_check_string, Secret Key);
// 4. Checking the validity and relevance of the data (auth_date should not be too old)
ifstrcmp;hash, $check_hash) !== 0) {
die('Error: Data tampered with!');
}
if- TIME$auth_data['auth_date']) > 86400) {
die('Error: Authorization session has expired.');
}
// The data is correct! Now you can authorize the user on the site
// $tg_id = $auth_data['id'];
// $username = $auth_data['username'];
echo 'Halloa!'htmlspecialchars$auth_data[First name]) . "!";
// Here you open a session (session_start()) and record the user in the database
?>
Alternative method (Via code/link)
If the standard widget does not suit you (for example, you want the user to log in by scanning a QR code or clicking on a Telegram link of the typet.me/your_bot?start=unique_code):
-
When you click on the "Log in via Telegram" button, your site generates a random unique token (authorization token) and saves it to the database with the "pending" status.
-
The site shows the user a link to a bot of the form
https://t.me/my_bot?start=UNIQUE_TOKEN. -
The user goes to the bot and clicksStart.
-
Your bot backend accepts the command
/start UNIQUE_TOKENHe pulls it out.idof the Telegram user and updates the entry in the database of your site: associates this token with the Telegram account and changes the status to "authorized". -
The site (which at this moment checks the status of the token through Ajax/WebSockets) sees that the status has changed, and automatically allows the user to enter the personal account.