Skip to content

Instantly share code, notes, and snippets.

@zilveer
Forked from fmkoc/telegram.php
Created October 26, 2024 10:25
Show Gist options
  • Select an option

  • Save zilveer/48ef6842878ecfe75dbdb6a59cf41e1e to your computer and use it in GitHub Desktop.

Select an option

Save zilveer/48ef6842878ecfe75dbdb6a59cf41e1e to your computer and use it in GitHub Desktop.
Login with Telegram | PHP Guide
<?php
define('TELEGRAM_BOT', 'YOUR_BOT'); // Username of the bot (Generated on @BotFather)
define('TELEGRAM_TOKEN', 'YOUR:TOKEN'); // Token of the bot (Generated by @BotFather)
//Data validation function
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', TELEGRAM_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;
}
//Check if javascript redirects user
if(isset($_GET["username"])){
try {
$auth_data = checkTelegramAuthorization($_GET);
echo "<pre>";
print_r($auth_data);
}catch (Exception $e) {
die ($e->getMessage());
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login with Telegram | PHP Code</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<script async src="https://telegram.org/js/telegram-widget.js?8" data-telegram-login="<?php echo TELEGRAM_BOT ?>" data-size="large" data-auth-url="telegram.php" data-request-access="write"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment