Validating initData in Telegram Mini Apps Using PHP: Protecting Against user.id Spoofing and Activating MainButton

When developing Telegram Mini Apps, beginner developers often make a critical mistake: they take user data directly from the JS SDK via the window.Telegram.WebApp.initDataUnsafe object and trust it on the backend. Since client-side code executes in a browser (WebView), an attacker can open the application page outside of Telegram, forge the user.id object, substitute someone else's identifier, and gain access to another user's data or balance.

To protect against this, Telegram passes a signed initData string. In this article, we will examine how client-side data spoofing works, implement strict HMAC-SHA-256 validation with timing-safe сравнение in PHP, and configure MainButton control on the frontend only after authorization is confirmed by the server.

initDataUnsafe Vulnerability and Payload Forgery

The initDataUnsafe object is parsed on the JS side and contains no authenticity guarantees. Any user can open DevTools or send requests directly to your API by generating a fake JSON with any user.id.

An example of a fake string that an attacker could send to your server disguised as legitimate initData:

query_id=AAH12345&user=%7B%22id%22%3A99999999%2C%22first_name%22%3A%22Attacker%22%2C%22username%22%3A%22hacker%22%7D&auth_date=1710000000&hash=fake_hash_value_string

If the server accepts the user.id parameter from a request without verifying the hash signature, the system is compromised. To avoid this, the server must accept only the raw initData string and perform cryptographic verification.

HMAC-SHA-256 Validation Algorithm on the Backend

Telegram initData authentication consists of the following steps:

  1. Extracting the hash parameter from the query string.
  2. Sorting all remaining key=value pairs alphabetically and concatenating them with a newline character \n. This forms the data_check_string.
  3. Calculating the secret key: HMAC-SHA-256 of the bot token using the constant string WebAppData as the key.
  4. Calculating the check HMAC of the data_check_string using the derived secret key.
  5. Comparing the calculated hash with the provided hash using the hash_equals() function to protect against timing attacks.
  6. Checking the freshness of auth_date to prevent the reuse of old intercepted strings (Replay Attack).

Implementation of the Authorization Endpoint in PHP

Let's create an /api/auth.php handler that accepts initData, performs validation, and returns an HTTP status of 200 OK on success or 401 Unauthorized on error.

<?php
declare(strict_types=1);

header('Content-Type: application/json');

$botToken = getenv('BOT_TOKEN');
if (!$botToken) {
http_response_code(500);
echo json_encode(['ok' => false, 'error' => 'Server configuration error']);
exit;
}

$rawInput = file_get_contents('php://input');
$data = json_decode($rawInput, true);

if (json_last_error() !== JSON_ERROR_NONE || empty($data['initData'])) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Invalid JSON or missing initData']);
exit;
}

$initDataRaw = $data['initData'];
parse_str($initDataRaw, $parsedData);

if (!isset($parsedData['hash'], $parsedData['auth_date'])) {
http_response_code(401);
echo json_encode(['ok' => false, 'error' => 'Missing required HMAC parameters']);
exit;
}

$receivedHash = $parsedData['hash'];
$authDate = (int)$parsedData['auth_date'];
unset($parsedData['hash']);

// Проверка на устаревшие данные (максимум 24 часа = 86400 сек)
if ((time() - $authDate) > 86400) {
http_response_code(401);
echo json_encode(['ok' => false, 'error' => 'Authentication data is expired']);
exit;
}

// Формирование data_check_string
$dataCheckArray = [];
foreach ($parsedData as $key => $value) {
$dataCheckArray[] = $key . '=' . $value;
}
sort($dataCheckArray);
$dataCheckString = implode("
", $dataCheckArray);

// Генерация HMAC-SHA-256
$secretKey = hash_hmac('sha256', $botToken, 'WebAppData', true);
$calculatedHash = hash_hmac('sha256', $dataCheckString, $secretKey);

// Timing-safe сравнение хэшей
if (!hash_equals($calculatedHash, $receivedHash)) {
http_response_code(401);
echo json_encode(['ok' => false, 'error' => 'Invalid HMAC signature']);
exit;
}

$userData = json_decode($parsedData['user'] ?? '{}', true);

// Запрос успешен, создаем сессию или выдаем JWT
http_response_code(200);
echo json_encode([
'ok' => true,
'user' => [
'id' => $userData['id'] ?? null,
'first_name' => $userData['first_name'] ?? '',
'username' => $userData['username'] ?? ''
]
]);

Secure MainButton Management on the Frontend

Until the server has confirmed the validity of initData and returned HTTP 200, the application interface should remain locked. The main UI button, Telegram.WebApp.MainButton, should be kept hidden or disabled to prevent any target actions by an unauthorized user.

Example of a secure Mini App initialization JS script:

document.addEventListener('DOMContentLoaded', async () => {
const tg = window.Telegram?.WebApp;

if (!tg) {
console.error('Telegram WebApp SDK not found');
return;
}

tg.ready();
tg.expand();

// По умолчанию скрываем и отключаем MainButton
tg.MainButton.hide();
tg.MainButton.disable();

const initData = tg.initData;

if (!initData) {
alert('Ошибка: запуск разрешен только внутри Telegram Mini App');
return;
}

try {
const response = await fetch('/api/auth.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ initData: initData })
});

const result = await response.json();

if (response.status === 200 && result.ok) {
// Активируем интерфейс только после успешного 200 OK от API
tg.MainButton.setText('Оформить заказ');
tg.MainButton.show();
tg.MainButton.enable();

tg.MainButton.onClick(() => {
alert(`Авторизован пользователь ID: ${result.user.id}`);
});
} else {
tg.MainButton.hide();
alert(`Ошибка авторизации: ${result.error || 'Доступ запрещен'}`);
}
} catch (error) {
tg.MainButton.hide();
console.error('Network or auth error:', error);
alert('Не удалось связаться с сервером авторизации');
}
});

Testing Spoofing Protection with cURL

To test how the backend reacts to a forged payload with an invalid signature, run the following cURL command from your terminal:

curl -X POST https://your-domain.com/api/auth.php \
-H "Content-Type: application/json" \
-d '{
"initData": "query_id=AAG12345&user=%7B%22id%22%3A99999999%2C%22first_name%22%3A%22FakeUser%22%7D&auth_date=1710000000&hash=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
}'

The server will recalculate the HMAC for the substituted user.id=99999999, detect the mismatch with the passed hash, and return an HTTP response status of 401 Unauthorized:

{
"ok": false,
"error": "Invalid HMAC signature"
}

Thus, even if an attacker changes a single character in user.id, auth_date, or any other field, they won't be able to forge the signature without knowing your bot's token, which is stored on the backend.

If you are developing complex Telegram solutions or need scalable infrastructure for Mini Apps, check out the solutions from BotCreator.

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.