Search code examples
phptelegram

Can't validate Telegram Web App for Bots user


I've tried to do user verification script for telegram web app for bots. I have no idea how to fix it. The hash and encoded string are similar but not the same.

Telegram article (documentation): https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app


$bot_token="5368097647:AAFU8jBho71pglrzDeGw6LawrVuMmxaxpEQ";
$data_check_string=$_POST['a'];
$data_check_string=explode("&", urldecode($data_check_string));

foreach ($data_check_string as &$arrvalue) {
    $hash="";
    if (substr($arrvalue, 0, 4)=='hash'){
        $hash=explode("=", $arrvalue)[1];
        break;
    }
}

sort($data_check_string);

$data_check_string=implode('\\n', $data_check_string);
$secret_key = $sig = hash_hmac('sha256', $bot_token, "WebAppData");

if (hash_hmac('sha256', $data_check_string, $secret_key) == $hash) {
    print("fromtg");
}
else{
    print("notg");
}

?>

Solution

    • Join the array with implode("\n", $data_check_arr);
    • in the hash_mac functions set the fourth param to TRUE (outputs raw binary data);
    • before compare the two hash apply bin2hex function to calculated hash to convert binary data into hexadecimal representation;

    Here my code:

    <?php
    
    $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;
        }
    }
    
    // if( $check_hash === FALSE ) return FALSE;
    $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 ){
        // validation success
    }else{
        // validation failed
    }