Created
May 12, 2022 16:21
-
-
Save MakStashkevich/1a4600819af872420d566a4297ac99df to your computer and use it in GitHub Desktop.
Telegram Web App Bot (Validate hash) on PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$bot_token = '0123456789:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; | |
$data_check_string = 'XXX'; // get from Telegram.WebAppData | |
$data_check_arr = explode('&', rawurldecode($data_check_string)); | |
$needle = 'hash='; | |
$check_hash = FALSE; | |
foreach($data_check_arr AS &$val){ | |
if(substr($val, 0, strlen($needle)) === $needle){ | |
$check_hash = substr_replace($val, '', 0, strlen($needle)); | |
$val = NULL; | |
} | |
} | |
$data_check_arr = array_filter($data_check_arr); | |
sort($data_check_arr); | |
$data_check_string = implode("\n", $data_check_arr); | |
$secret_key = hash_hmac('sha256', $bot_token, "WebAppData", true); | |
$hash = bin2hex(hash_hmac('sha256', $data_check_string, $secret_key, true) ); | |
if(strcmp($hash, $check_hash) === 0){ | |
print('ok'); | |
} else { | |
print('fail'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment