Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<?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;
?>

ximik777 commented Feb 7, 2018

Does not work. =(

ximik777 commented Feb 7, 2018

Already working! =)

ingria commented Feb 7, 2018

Doesn't work in Firefox

Error: NOT_ALLOWED

Good!

jumong commented Feb 7, 2018

Bot domain empty ? Why ?

kapter commented Feb 7, 2018

"Bot domain empty"??

jumong commented Feb 7, 2018

Bot domain empty error

@jumong, you should set domain by @Botfather

Does not work on firefox, it returns Error: NOT_ALLOWED (in response payload), and does not redirect to data-auth-url.
No visible information for user in browser.

kapter commented Feb 7, 2018

@ruslanmedia, i send /setdomain command, choose my bot but have error "Bot domain empty". What's wrong?

jumong commented Feb 7, 2018

@ruslanmedia Рахмат котта!

aLkRicha commented Feb 7, 2018

i also have error Bot domain empty

jumong commented Feb 7, 2018

Who know? How to set own button name ?

diseks commented Feb 7, 2018

Hi. Does anyone known how to use custom button (without text, only custom image)?

lensws commented Feb 7, 2018

Waiting wordpress login

juananpe commented Feb 7, 2018

Same "Bot domain empty" problem here.

ximik777 commented Feb 7, 2018

++

Doesn't work in Firefox
Error: NOT_ALLOWED

9kopb commented Feb 7, 2018

you need to link your domain to the bot first

juananpe commented Feb 7, 2018

Ah! Thanks @9kopb... I was going to answer that I've already done that but then I tried again and this time it worked! For the record:

Start a conversation with the BotFather. Type "/mybots". Select your bot. Select "Bot settings". Select "Domain". Then type your domain name. You'll get a feedback message from BotFather like this: "Success! Domain updated. /help"

akkez commented Feb 7, 2018

Дуров верни дуровдурова

lifeact commented Feb 7, 2018

How about asp mvc?

Serdg commented Feb 7, 2018

How about iOS and Android login with Telegram?

t4hor3 commented Feb 7, 2018

It does not work, error 500. What version of PHP is necessary?

oxmix commented Feb 7, 2018

FF 58.0.1
bug! return string get -> "...username=Oxmix&photo_url=**https:/**t.me/i/userpic/320/Oxmix.jpg&auth_date=151..."
below a temporary fix
$data_check_arr[] = $key . '=' . str_replace('https:/t', 'https://t', $value);
without this fix, hash_hmac checking fail

mhd4mr commented Feb 7, 2018

Working good :)

madl-ash commented Feb 7, 2018

im trying to port this to python but hash_hmac fails.
docs says Data-check-string is a concatenation of all received fields, sorted in alphabetical order
now all fields are id, first_name, last_name, username, photo_url, auth_date and hash;
which fields should i include and in what order exactly?

roxblnfk commented Feb 8, 2018

Does anyone know how to force a telegram to redirect a user to my page (without using a widget)?
Need a workflow similar to OAuth2

I just send the user to https://oauth.telegram.org/bot_id=****

After confirming the user redirects to https://oauth.telegram.org/close

I tried to find the GET param as redirect_uri - unsuccessfully.

Also it would be good to receive POST data

m0cmc commented Feb 8, 2018

Great feature!
But returns "Bot domain invalid" for a ".LIVE" domain (which is set on the bot using BotFather). What's wrong ?

How I can send message to user if allow access to send messages?

Any easy way to set a local development environment domain?

http://localhost:1337 for example would not register as a domain

6o6p1k commented Feb 9, 2018

How set localhost as domain??
BotFather return: "The message should contain one domain name."

6o6p1k commented Feb 9, 2018

PS Use http://127.0.0.1:youPort/ if you need localhost

you most limit GET key to only your key
your key is 'username' , 'auth_date' ,'first_name', 'last_name' ,'photo_url' ,'id'
please fix this
it is correct

function checkTelegramAuthorization($auth_data) {
$allow_key= array('username' , 'auth_date' ,'first_name', 'last_name' ,'photo_url' ,'id');
  $check_hash = $auth_data['hash'];
  unset($auth_data['hash']);
  $data_check_arr = [];
  foreach ($auth_data as $key => $value) {
      if( in_array( $key , $allow_key)){
            $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;
}

Aliham commented Feb 10, 2018

پاسخ نداد

emadweb commented Feb 11, 2018

$check_hash an $hash will not be the same

xen commented Feb 12, 2018

In case somebody needs python version https://gist.github.com/xen/e4bea72487d34caa28c762776cf655a3

tcapb commented Feb 13, 2018

Unusable to me. It allows to add only one domain per bot. I couldn't even use it with multiple subdomains. If i set domain.com - i can use authorization from domain.com page, but cannot - from sub.domain.com page.

GoLang version of checkTelegramAuthorization: https://gist.github.com/recoilme/a1b9059b5d5f12c18a63bae58b3bc659

@tcapb similar problem. I will redirect login on main domain, set cookie for main domain and subdomains and redirect back. Not finished right now - http://recoilmeblog.tggram.com/

Login widget does not work in Safari (iOS) - it opens new page with "Origin required" text

bun4uk commented Feb 15, 2018

How is it possible to test on localhost?
I crated a bot and conected a domain to it.
image
image

new page with "Origin required" text

Same issue on Android System Webview

This is corrected and running without problem ;-)

hi, how to use these files and code in wordpress?
do i insert codes in which ones: theme file? or text widget in sidbar?
i want to write code and dont want to use plugin. thanx.

jhuesser commented Feb 21, 2018

new page with "Origin required" text

Have this problem to, mostly after I deleted cookies of telegram.org & my page. Still works fine in Chrome on same the same iOS device

Here is sample implement for React: https://github.com/hprobotic/react-telegram-login

vchaptsev commented Feb 24, 2018

Here is Vue component, if someone need it :)

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