Building a Telegram Mini App often starts smoothly on the frontend. You load https://telegram.org/js/telegram-web-app.js, open the SDK inside Telegram, and instantly access window.Telegram.WebApp.initDataUnsafe. From initDataUnsafe, you get a pre-populated JavaScript object containing the user's Telegram ID, first name, username, and query parameters.
It is tempting to grab initDataUnsafe.user.id, send it directly to your PHP backend via fetch(), and immediately start processing bookings, loading private user data, or crediting account balances. Doing this introduces a critical vulnerability: initDataUnsafe can be manipulated by anyone with browser developer tools.
Because a Telegram Mini App runs inside an embedded web view, any user can open devtools, rewrite window.Telegram.WebApp.initDataUnsafe.user.id to match a target victim's ID, and send forged requests to your server. If your PHP backend accepts client-provided user IDs without server-side verification, an attacker can impersonate any user in your system.
To prevent identity spoofing, Telegram provides Telegram.WebApp.initData, a raw URL-encoded query string containing the exact user payload paired with a cryptographic HMAC-SHA256 signature generated by Telegram. In this guide, we will break down why client-side validation fails, implement a strict verification pipeline in native PHP, handle timestamp expirations, and set up a secure authentication handshake.
The Flaw: Why Trusting initDataUnsafe Invites Takeover Attacks
Consider an e-commerce Mini App built on PHP. When the user opens the checkout tab, the client JavaScript reads the user details from the Telegram SDK and places an order:
// BAD PRACTICE: Sending raw user fields from client memory
const user = window.Telegram.WebApp.initDataUnsafe.user;
fetch('/api/checkout.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
telegram_id: user.id, // easily spoofed in DevTools
item_id: 42,
amount: 19.99
})
});
On the backend, a naive PHP endpoint takes telegram_id directly from file_get_contents('php://input'):
<?php
// BAD PRACTICE: Trusting untrusted HTTP body attributes
$input = json_decode(file_get_contents('php://input'), true);
$userId = $input['telegram_id'] ?? null;
if (!$userId) {
http_response_code(400);
echo json_encode(['error' => 'Missing user identity']);
exit;
}
// Attacker provided target user's ID -> balance is spent from target account!
deductBalance($userId, $input['amount']);
In this scenario, an attacker does not need to compromise Telegram servers or intercept network traffic. They simply launch your Mini App, open their browser console, execute fetch('/api/checkout.php', { body: JSON.stringify({ telegram_id: 12345678, ... }) }), and your PHP backend processes the payload under victim 12345678.
To prevent this, the client must pass the entire raw string window.Telegram.WebApp.initData to the server, and the server must calculate the hash from scratch using the Telegram Bot Token.
Step-by-Step Backend Verification in Pure PHP
Telegram's verification process uses a specific SHA256 HMAC algorithm. To verify an incoming initData string:
- Parse the URL-encoded query string into individual key-value parameters.
- Extract the
hashfield from the parameters. This is the signature calculated by Telegram. - Remove
hashfrom the array of parameters. - Sort the remaining key-value pairs alphabetically by key.
- Format the sorted array into a newline-delimited string of key-value pairs in the format
key=value. This is called thedata_check_string. - Calculate a secret key using HMAC-SHA256 with the constant string string
"WebAppData"as the key, and your bot token as the message. - Compute the SHA-256 HMAC signature of
data_check_stringusing the generated secret key. - Perform a timing-safe string comparison between the server-calculated hash and the incoming parameter
hash.
Decoding Pitfalls in PHP
A common issue when building this logic in PHP stems from standard query string parsing. Telegram expects the data_check_string values to match the unencoded parameter strings. Using standard parse_str() can sometimes transform periods or spaces incorrectly, or unescape JSON structures in ways that disrupt the signature check.
Below is a pure PHP validation function designed to parse raw query string key-value pairs reliably:
<?php
declare(strict_types=1);
/**
* Validates Telegram WebApp initData against the bot token.
*
* @param string $initData Raw string from window.Telegram.WebApp.initData
* @param string $botToken The bot token retrieved from your environment
* @return array{valid: bool, data: array<string, string>, error?: string}
*/
function verifyTelegramInitData(string $initData, string $botToken): array
{
if (empty($initData)) {
return ['valid' => false, 'data' => [], 'error' => 'Empty initData payload'];
}
// 1. Parse raw query string manually to preserve structure
$rawData = [];
$pairs = explode('&', $initData);
foreach ($pairs as $pair) {
if ($pair === '') {
continue;
}
$parts = explode('=', $pair, 2);
$key = urldecode($parts[0]);
$value = isset($parts[1]) ? urldecode($parts[1]) : '';
$rawData[$key] = $value;
}
if (!isset($rawData['hash'])) {
return ['valid' => false, 'data' => [], 'error' => 'Missing hash parameter'];
}
$providedHash = $rawData['hash'];
unset($rawData['hash']);
// 2. Sort keys alphabetically
ksort($rawData);
// 3. Build data_check_string: "key1=value1
key2=value2"
$checkDataLines = [];
foreach ($rawData as $key => $value) {
$checkDataLines[] = $key . '=' . $value;
}
$dataCheckString = implode("
", $checkDataLines);
// 4. Secret key = HMAC-SHA256("WebAppData", botToken)
$secretKey = hash_hmac('sha256', $botToken, 'WebAppData', true);
// 5. Calculate expected hash = HMAC-SHA256(dataCheckString, secretKey)
$calculatedHash = hash_hmac('sha256', $dataCheckString, $secretKey);
// 6. Use timing-safe comparison to prevent side-channel attacks
if (!hash_equals($calculatedHash, $providedHash)) {
return ['valid' => false, 'data' => [], 'error' => 'Invalid signature match'];
}
return [
'valid' => true,
'data' => $rawData,
];
}
By enforcing hash_equals(), we mitigate timing side-channel attacks where an attacker measures the execution microsecond delta to guess valid hash characters character-by-character.
Enforcing Expiration and Preventing Replay Attacks
HMAC validation ensures that the string was produced by Telegram for your specific bot and that no fields have been altered. However, HMAC validation alone does not stop replay attacks.
If an attacker intercepts a valid initData string sent by a legitimate user over an insecure connection or from stolen logs, that payload will pass cryptographic verification indefinitely unless you check the auth_date timestamp.
The auth_date field is an integer Unix timestamp indicating when Telegram issued the signature. If an incoming authentication request presents an auth_date older than your acceptable threshold (e.g., 24 hours), your backend must reject it.
Here is how to extend our validator to enforce strict expiration limits:
<?php
declare(strict_types=1);
/**
* Validates initData cryptographic integrity and enforces auth_date age limits.
*
* @param string $initData
* @param string $botToken
* @param int $maxAgeSeconds Maximum permitted age of the payload (default: 86400 / 24h)
* @return array{valid: bool, user?: array, raw: array, error?: string}
*/
function authenticateTelegramSession(string $initData, string $botToken, int $maxAgeSeconds = 86400): array
{
$result = verifyTelegramInitData($initData, $botToken);
if (!$result['valid']) {
return ['valid' => false, 'raw' => [], 'error' => $result['error'] ?? 'Verification failed'];
}
$data = $result['data'];
// Check auth_date existence
if (!isset($data['auth_date']) || !is_numeric($data['auth_date'])) {
return ['valid' => false, 'raw' => $data, 'error' => 'Missing or invalid auth_date'];
}
$authTimestamp = (int) $data['auth_date'];
$currentTimestamp = time();
// Check if timestamp is in the future (clock drift protection)
if ($authTimestamp > ($currentTimestamp + 60)) {
return ['valid' => false, 'raw' => $data, 'error' => 'Payload timestamp is in the future'];
}
// Check payload age
if (($currentTimestamp - $authTimestamp) > $maxAgeSeconds) {
return ['valid' => false, 'raw' => $data, 'error' => 'Authentication payload has expired'];
}
// Parse embedded user JSON string
$userData = [];
if (isset($data['user'])) {
$parsedUser = json_decode($data['user'], true);
if (json_last_error() === JSON_ERROR_NONE && is_array($parsedUser)) {
$userData = $parsedUser;
}
}
return [
'valid' => true,
'user' => $userData,
'raw' => $data,
];
}
By enforcing both the HMAC signature and the maximum age check, your server ensures that the payload is genuine and fresh.
Production Integration: Secure Frontend-to-Backend Handshake
Instead of embedding initData inside every POST request body, pass it in the HTTP Authorization header as a custom scheme (e.g., Authorization: TelegramInitData <raw_init_data>) or a Bearer token.
JavaScript Client Setup
// JS: Read raw initData and attach to API calls
async function fetchSecureApi(endpoint, options = {}) {
const initData = window.Telegram.WebApp.initData;
if (!initData) {
throw new Error("Mini App must be opened within Telegram client environment");
}
const headers = {
'Content-Type': 'application/json',
'Authorization': `TelegramInitData ${initData}`,
...(options.headers || {})
};
const response = await fetch(endpoint, { ...options, headers });
if (response.status === 401) {
// Session invalid or expired: trigger Mini App reload or error UI
window.Telegram.WebApp.close();
}
return response.json();
}
PHP Production API Controller
In your PHP entry point or API router, extract the Authorization header, parse the credentials, and extract the verified user context before business logic runs:
<?php
declare(strict_types=1);
// Disable error display in production to prevent leakage
ini_set('display_errors', '0');
header('Content-Type: application/json');
$botToken = getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
http_response_code(500);
echo json_encode(['error' => 'Server configuration error']);
exit;
}
// 1. Extract Authorization header
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/^TelegramInitData\s+(.+)$/', $authHeader, $matches)) {
http_response_code(401);
echo json_encode(['error' => 'Missing or malformed Authorization header']);
exit;
}
$rawInitData = $matches[1];
// 2. Validate hash signature and age (max 2 hours / 7200 sec)
$authResult = authenticateTelegramSession($rawInitData, $botToken, 7200);
if (!$authResult['valid']) {
http_response_code(401);
echo json_encode(['error' => 'Unauthorized: ' . $authResult['error']]);
exit;
}
// 3. User is cryptographically verified!
$telegramUser = $authResult['user'];
$telegramId = $telegramUser['id'] ?? null;
if (!$telegramId) {
http_response_code(400);
echo json_encode(['error' => 'Payload does not contain valid user details']);
exit;
}
// Proceed safely with application logic using $telegramId
echo json_encode([
'status' => 'success',
'authenticated_as' => $telegramId,
'first_name' => $telegramUser['first_name'] ?? ''
]);
Production Notes
-
Keep Bot Tokens Out of Version Control: Always read your bot token via
getenv()or an encrypted configuration store. Never commit bot tokens into your public repository. -
Synchronize System Clocks: Ensure your PHP server uses Network Time Protocol (
ntpdorsystemd-timesyncd). If your system clock drifts backwards by a few minutes, valid requests from clients might get blocked by timestamp checks. -
Short-Lived Sessions: For financial transactions or high-privilege administrative Mini Apps, lower the allowed
auth_datethreshold to 300 seconds (5 minutes) and issue a custom session JWT upon initial handshake. -
MainButton Initialization: Always complete server authentication before attaching click events to
Telegram.WebApp.MainButton. If authentication fails during initialization, hide or disable UI triggers to prevent users from attempting actions while unauthenticated.
If you are shipping custom Telegram integrations, webhooks, or scalable Mini Apps for business, BotCreator provides full-stack engineering services to build and secure production Telegram services.
Top comments (0)