P
P
PigData2022-04-21 17:08:02
PHP
PigData, 2022-04-21 17:08:02

Telegram webapps - how to check hash from Telegram.WebApp.initData in php?

Can't check hash, probably because of nested user array

https://core.telegram.org/bots/webapps#validating-...

To check hash when logging in via widget , my php code works

function check_hash($token){
    $arr = $_GET;
    $check_hash = $arr['hash'];
    unset($arr['hash']);
    foreach($arr as $k => $v) $check_arr[]=$k.'='.$v; 
    @sort($check_arr);

    $string = @implode("\n", $check_arr);
    $secret_key = hash('sha256', $token, true);
    $hash = hash_hmac('sha256', $string, $secret_key);
    if (strcmp($hash, $check_hash) !== 0)  return false;
    return true;
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jean, 2022-04-22
@zhan0

try like this:

function check_hash($token){
    $arr = $_GET;
    $check_hash = $arr['hash'];
    unset($arr['hash']);
    $data_check_arr = explode('&', rawurldecode($check_hash));
    $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);

    $check_hash = implode("\n", $data_check_arr);
    $secret_key = hash_hmac( 'sha256', $token, "WebAppData", TRUE );
    $hash = bin2hex( hash_hmac( 'sha256', $check_hash, $secret_key, TRUE ) );

    if(strcmp($hash, $check_hash) === 0){
        return true;
    }else{
        return false;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question