-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidate.php
More file actions
47 lines (41 loc) · 1.56 KB
/
validate.php
File metadata and controls
47 lines (41 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<?php
class Validate
{
/**
* validate initData to ensure that it is from Telegram.
*
* @param string $botToken your bot token
* @param string $initData init data from Telegram (`Telegram.WebApp.initData`)
*
* @return bool return true if its from Telegram otherwise false
*/
public static function isSafe(string $botToken, string $initData): bool
{
[$checksum, $sortedInitData] = self::convertInitData($initData);
$secretKey = hash_hmac('sha256', $botToken, 'WebAppData', true);
$hash = bin2hex(hash_hmac('sha256', $sortedInitData, $secretKey, true));
return 0 === strcmp($hash, $checksum);
}
/**
* convert init data to `key=value` and sort it `alphabetically`.
*
* @param string $initData init data from Telegram (`Telegram.WebApp.initData`)
*
* @return string[] return hash and sorted init data
*/
private static function convertInitData(string $initData): array
{
$initDataArray = explode('&', rawurldecode($initData));
$needle = 'hash=';
$hash = '';
foreach ($initDataArray as &$data) {
if (substr($data, 0, \strlen($needle)) === $needle) {
$hash = substr_replace($data, '', 0, \strlen($needle));
$data = null;
}
}
$initDataArray = array_filter($initDataArray);
sort($initDataArray);
return [$hash, implode("\n", $initDataArray)];
}
}