· 6 years ago · Oct 22, 2019, 03:42 PM
1<?php
2
3define('BOT_TOKEN', 'XXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXX'); // place bot token of your bot here
4
5function checkTelegramAuthorization($auth_data) {
6 $check_hash = $auth_data['hash'];
7 unset($auth_data['hash']);
8 $data_check_arr = [];
9 foreach ($auth_data as $key => $value) {
10 $data_check_arr[] = $key . '=' . $value;
11 }
12 sort($data_check_arr);
13 $data_check_string = implode("\n", $data_check_arr);
14 $secret_key = hash('sha256', BOT_TOKEN, true);
15 $hash = hash_hmac('sha256', $data_check_string, $secret_key);
16 if (strcmp($hash, $check_hash) !== 0) {
17 throw new Exception('Data is NOT from Telegram');
18 }
19 if ((time() - $auth_data['auth_date']) > 86400) {
20 throw new Exception('Data is outdated');
21 }
22 return $auth_data;
23}
24
25function saveTelegramUserData($auth_data) {
26 $auth_data_json = json_encode($auth_data);
27 setcookie('tg_user', $auth_data_json);
28}
29
30
31try {
32 $auth_data = checkTelegramAuthorization($_GET);
33 saveTelegramUserData($auth_data);
34} catch (Exception $e) {
35 die ($e->getMessage());
36}
37
38header('Location: login_example.php');
39
40?>