Skip to main content

Token Validation Mechanism

WebApps use a token validation mechanism to ensure the integrity and authenticity of the data passed to the WebApp. This is done through a hash-based signature validation process.

YoPhone provides an initData parameter, which contains signed user information. The WebApp must validate this data to prevent tampering or unauthorized access.

Steps for Token Validation​

  1. Extract initData
    When a WebApp is launched, it provides an initData string, which includes:
    • User ID, username, and other details
    • Timestamp of the session
    • Hash signature

Example initData:

auth_date=1234567890&hash=53a0fd101d226d24139793ebdca6cf0bfba3c062ab52c97eabf6ce163c65ca29&query_id=72d4e9cc-f80a-4822-b109-6db1046685eb&user={"first_name":"yo","id":"0192bcf9-4dda-7843-99a1-14535971bc14","language_code":"en","last_name":""}
  1. Compute the Valid Hash
    To verify the integrity of the data:
    • Sort all parameters (except hash) in alphabetical order.
    • Concatenate them into a string in key=value format.
    • Generate an HMAC-SHA256 hash using the bot’s access token as the secret key.

Token Validation Examples​

Use one of the following language examples to validate initData.

<?php
// The initialization data received (replace {initData} with actual data)
$initData = '{initData}';
$botAccessToken = 'botToken'; // Bot token used for authentication

// Extract the hash value from the received data
$checkHash = $initData["hash"];
unset($initData["hash"]); // Remove the hash key to avoid including it in the verification process

$keyValuePairs = [];

foreach ($initData as $key => $value) {
// Combine each key-value pair into "key=value" format
$keyValuePairs[] = $key . "=" . $value;
}

// Sort key-value pairs alphabetically by key
sort($keyValuePairs);

// Create the data string to be hashed
$dataCheckString = implode("\n", $keyValuePairs);

// Calculate the secret key using the bot token
$secretKey = hash_hmac('sha256', "WebAppData", $botAccessToken, true);

// Generate the hash to compare with the received hash
$hash = hash_hmac('sha256', $dataCheckString, $secretKey);

// Now, you can compare $hash with $checkHash to verify data integrity
if (hash_equals($hash, $checkHash)) {
echo "Data is valid!";
} else {
echo "Data is invalid!";
}
?>

Security Considerations​

  • Always validate initData on the server-side to prevent spoofing.
  • Use HTTPS to prevent MITM attacks.
  • Ensure that auth_date is recent to prevent replay attacks.