Skip to content

Instantly share code, notes, and snippets.

Created February 3, 2018 16:21
Show Gist options
  • Save anonymous/6516521b1fb3b464534fbc30ea3573c2 to your computer and use it in GitHub Desktop.
Save anonymous/6516521b1fb3b464534fbc30ea3573c2 to your computer and use it in GitHub Desktop.
<?php
define('BOT_TOKEN', 'XXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXX'); // place bot token of your bot here
function checkTelegramAuthorization($auth_data) {
$check_hash = $auth_data['hash'];
unset($auth_data['hash']);
$data_check_arr = [];
foreach ($auth_data as $key => $value) {
$data_check_arr[] = $key . '=' . $value;
}
sort($data_check_arr);
$data_check_string = implode("\n", $data_check_arr);
$secret_key = hash('sha256', BOT_TOKEN, true);
$hash = hash_hmac('sha256', $data_check_string, $secret_key);
if (strcmp($hash, $check_hash) !== 0) {
throw new Exception('Data is NOT from Telegram');
}
if ((time() - $auth_data['auth_date']) > 86400) {
throw new Exception('Data is outdated');
}
return $auth_data;
}
function saveTelegramUserData($auth_data) {
$auth_data_json = json_encode($auth_data);
setcookie('tg_user', $auth_data_json);
}
try {
$auth_data = checkTelegramAuthorization($_GET);
saveTelegramUserData($auth_data);
} catch (Exception $e) {
die ($e->getMessage());
}
header('Location: login_example.php');
?>
<?php
define('BOT_USERNAME', 'XXXXXXXXXX'); // place username of your bot here
function getTelegramUserData() {
if (isset($_COOKIE['tg_user'])) {
$auth_data_json = urldecode($_COOKIE['tg_user']);
$auth_data = json_decode($auth_data_json, true);
return $auth_data;
}
return false;
}
if ($_GET['logout']) {
setcookie('tg_user', '');
header('Location: login_example.php');
}
$tg_user = getTelegramUserData();
if ($tg_user !== false) {
$first_name = htmlspecialchars($tg_user['first_name']);
$last_name = htmlspecialchars($tg_user['last_name']);
if (isset($tg_user['username'])) {
$username = htmlspecialchars($tg_user['username']);
$html = "<h1>Hello, <a href=\"https://t.me/{$username}\">{$first_name} {$last_name}</a>!</h1>";
} else {
$html = "<h1>Hello, {$first_name} {$last_name}!</h1>";
}
if (isset($tg_user['photo_url'])) {
$photo_url = htmlspecialchars($tg_user['photo_url']);
$html .= "<img src=\"{$photo_url}\">";
}
$html .= "<p><a href=\"?logout=1\">Log out</a></p>";
} else {
$bot_username = BOT_USERNAME;
$html = <<<HTML
<h1>Hello, anonymous!</h1>
<script async src="https://telegram.org/js/telegram-widget.js?2" data-telegram-login="{$bot_username}" data-size="large" data-auth-url="check_authorization.php"></script>
HTML;
}
echo <<<HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login Widget Example</title>
</head>
<body><center>{$html}</center></body>
</html>
HTML;
?>
@iQiexie
Copy link

iQiexie commented Aug 22, 2023

it works when the data is formatted like this:

request_data = {
  "id": XXXXXXXXX,
  "first_name": "John",
  "last_name": "Smith",
  "username": "john_smith",
  "photo_url": "https://t.me/i/userpic/320/XjskdfasdfHGCAShsfgasdf.jpg",
  "auth_date": 1571890000,
  "hash": "a0c34b50c96acbcbf358b34d30a0ad69c5a5ced90427f34729499938b1faf02e"
}

but doesn't work when it formatted like this:

data = {
  "query_id": "AAAAAAAAAAA",
  "user": {
    "id": XXXXXXXXX,
    "first_name": "John",
    "last_name": "",
    "username": "john_smith",
    "language_code": "en",
    "is_premium": true,
    "allows_write_to_pm": true
  },
  "auth_date": "1692686970",
  "hash": "4317efd665c01a62973e1abd82aabe4128ca73ac67d0dba57d80656b8150dca5"
}

one of them must be data-onauth

@BAIZID-171
Copy link

Jk

@acebergiceberg
Copy link

How can I get code just by email cause my sim is deactivated

@acebergiceberg
Copy link

Can I receive code just by this email- cablindarm@gmail.com cause my number 09772813957 is deactivated due to unregistered sim

@munirwjira89
Copy link

mwjira@gmail.com 0944747844

@datoharry
Copy link

Nice

@070876
Copy link

070876 commented Sep 30, 2023

Сколько будет стоить такой ( папа бот)?

@Shahriyor-m14
Copy link

Сколько будет стоить такой ( папа бот)?

десятка

@mpotrich
Copy link

someone that implemented this in java?

@soni1541
Copy link

Because the fields "id", "first_name", "last_name", "username", "photo_url" and "auth_date" are required (!!!) to build a hash check
I understand :)
Telegrams do not always send all fields

I have the same problem. How did you manage to solve the hash mismatch issue?

@CrazyTapok-bit
Copy link

I have the same problem. How did you manage to solve the hash mismatch issue?

If you write code in PHP, I advise you to use the library tgWebValid to verify the user. It is light, simple and will do everything for you

@culda
Copy link

culda commented Nov 25, 2023

bot token is not necessary. Bot name is enough. see https://github.dev/manzoorwanijk/telegram-auth for a simple TS implementation. It's in React but you can just copy the files and use in any framework

To verify the hash only the bot token's hash is needed, which can be public

@Jaroslove
Copy link

Does anybody know how I can LOGOUT (or terminate session) in my browser tab via js?

@inilim
Copy link

inilim commented Jan 4, 2024

If something, the "id" value can be used as a "chat_id" to send a message via a bot

@ledboot
Copy link

ledboot commented Jan 10, 2024

i got a error Bot domain invalid

@CrazyTapok-bit
Copy link

i got a error Bot domain invalid

Check if you are using https

@Krishnauff
Copy link

#k

@SilRoad72
Copy link

رمز ضروري. اسم بوت كافي انظر https://github.dev/manzoorwanijk/telegram-authTS البسيط. إنه موجود في React ولكن يمكنك فقط نسخ الملفات الموجودة في أي إطار عمل

لأن من المبلغ، لا يتطلب سوى سوى تجزئة الرمز المميز للروبوت، والذي يمكن أن يكون كاملاً

مرحبا. عزي. هل يمكتكي صنع واحد مثاله. اريد اذالك. ان تقوم بمساعدتي. ونشاء واحد خاص فين

@yuma-teb
Copy link

yuma-teb commented Mar 14, 2024

رمز ضروري. اسم بوت كافي انظر https://github.dev/manzoorwanijk/telegram-authTS البسيط. إنه موجود في React ولكن يمكنك فقط نسخ الملفات الموجودة في أي إطار عمل
لأن من المبلغ، لا يتطلب سوى سوى تجزئة الرمز المميز للروبوت، والذي يمكن أن يكون كاملاً

مرحبا. عزي. هل يمكتكي صنع واحد مثاله. اريد اذالك. ان تقوم بمساعدتي. ونشاء واحد خاص فين

Telegram oauth does not have open link to redirect to consent screen for requesting access and the script provide by telegram document can not be rendered as component in front-end(keep return Bot domain is invalid), but when i get /auth/telegram/test from backend which return the html that has the script it works. And I do not want to use the default design button from that render from the script because it does not meet my ui design is there any solution you can suggest me?

@mashutkaxxx
Copy link

Thanks you for code!

@bulbazavr1024
Copy link

Does anyone know why telegram login widget doesn't work on .xyz TLD ?

@Arfanmohamed
Copy link

Thanks

@indiaone
Copy link

Does anybody know how I can LOGOUT (or terminate session) in my browser tab via js?

I am also looking for logout process. Please someone help me in this regard.

@CrazyTapok-bit
Copy link

I'll just leave a link to the TgWebValid library here, maybe someone will need a full-fledged way to check the user and get all the possible data about him in a convenient way and with a modern approach

@QobilZamonov
Copy link

menda xatolik borBot domain invalid

Foydalanayotganingizni tekshiringhttps

QobilZamonov

@QobilZamonov
Copy link

Salom

@maybephilipp
Copy link

Telegram login widget is not working on my web site and i don't understand why. It's just stuck when Telegram must send confirmation message. If i already logged in on telegram.org its working as needed, but i can't receive confirmation via my web site. Enabling cross site cookies does not resolve the problem

@rekkisomo @Comrade19632 if you find any solution, please ping

@maybephilipp
Copy link

Telegram login widget is not working on my web site and i don't understand why. It's just stuck when Telegram must send confirmation message. If i already logged in on telegram.org its working as needed, but i can't receive confirmation via my web site. Enabling cross site cookies does not resolve the problem

@rekkisomo @Comrade19632 if you find any solution, please ping

@rekkisomo @Comrade19632 + anyone with same problem, here is the solution: https://stackoverflow.com/a/74193012/15090151

quote: "I fixed it by changing the domain. I don’t know why, but the telegram login widget does not want to work with the tgmm.xyz domain."

xyz ltd or maybe some other are rejected by Telegram for some reason.

@Imran6478
Copy link

I couldn't receive code through number.why?
Plz help me

@maybephilipp
Copy link

I couldn't receive code through number.why? Plz help me

What is domain zone of your app, .xyz?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment