React Telegram Mini App: @twa-dev/sdk, Secure initData Validation, and MainButton Management

Developing Telegram Mini Apps (TMA) with React requires a clear separation of concerns between the client interface and the backend. The frontend is responsible for an adaptive UI and fast responses to user actions via native Telegram controls, while the backend handles strict authentication and secure execution of business logic. In this article, we will examine in detail the choice of SDK for React, the differences between raw and parsed initialization data, and build an end-to-end order processing workflow with initData validation in PHP.

1. Choosing an SDK: @twa-dev/sdk vs. window.Telegram.WebApp

There are two main approaches to connecting to the Telegram WebApp API in React applications: directly calling the window.Telegram.WebApp object (via the included telegram-web-app.js script) or using the @twa-dev/sdk wrapper (or its alternative @telegram-apps/sdk).

Direct access via window requires the developer to manually declare TypeScript types and track the global window state. The @twa-dev/sdk library provides ready-made typed wrappers, abstracting low-level API calls and preventing errors when accessing uninitialized objects.

  • window.Telegram.WebApp: Requires including <script src="https://telegram.org/js/telegram-web-app.js"></script> in index.html. Suitable for minimal projects without TypeScript.
  • @twa-dev/sdk: Distributed as an npm package. Provides full TypeScript types, tree-shaking, and predictable initialization in SPA applications.

2. The Danger of initDataUnsafe and Why Raw initData Is Required

When opening a Mini App, the Telegram client passes launch parameters to the application via URL hash. The SDK parses these parameters and provides two properties:

  1. initDataUnsafe — A JavaScript object containing user data (ID, name, username), chat, and authorization time.
  2. initData — The original encrypted URL string containing the same data along with the bot's HMAC signature.

Important: The initDataUnsafe object must strictly never be used to make financial decisions, modify access permissions, or write data to a database. Any user can open DevTools in Telegram Desktop or manually spoof `window.Telegram.WebApp.initDataUnsafe`. All legitimate operations must rely solely on validating the raw initData string on your backend.

3. Managing MainButton in the React Lifecycle

Telegram's main button (MainButton) resides outside the React DOM tree and is controlled via the messenger's Native API. A common mistake is attaching onClick listeners without cleaning them up, leading to multiple duplicate triggers (request races) during component re-renders.

The following example demonstrates a checkout component with proper unsubscription from MainButton events, display of a loading indicator, and sending signed initData to the backend.

import React, { useEffect, useState } from 'react';
import WebApp from '@twa-dev/sdk';

interface ApiResponse {
ok: boolean;
lead_id?: string;
error?: string;
}

export const OrderCheckout: React.FC = () => {
const [submitting, setSubmitting] = useState<boolean>(false);

useEffect(() => {
// Сообщаем Telegram, что веб-приложение готово к отображению
WebApp.ready();

// Настраиваем appearance главной кнопки
WebApp.MainButton.setText('ПОДТВЕРДИТЬ ЗАКАЗ');
WebApp.MainButton.show();

const handleSubmit = async () => {
if (submitting) return;

setSubmitting(true);
WebApp.MainButton.showProgress();
WebApp.MainButton.disable();

try {
const response = await fetch('/api/orders/create.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Telegram-Init-Data': WebApp.initData, // Отправляем сырую подписанную строку
},
body: JSON.stringify({
item_id: 'srv_123',
amount: 2500,
}),
});

const result: ApiResponse = await response.json();

if (result.ok) {
WebApp.showAlert(`Заказ №${result.lead_id} успешно создан!`);
WebApp.close();
} else {
WebApp.showAlert(`Ошибка: ${result.error || 'Не удалось оформить заказ'}`);
}
} catch (err) {
WebApp.showAlert('Ошибка сети при отправке данных');
} finally {
WebApp.MainButton.hideProgress();
WebApp.MainButton.enable();
setSubmitting(false);
}
};

// Вешаем слушатель события клика по нативной кнопке
WebApp.MainButton.onClick(handleSubmit);

// Обязательная очистка при размонтировании компонента
return () => {
WebApp.MainButton.offClick(handleSubmit);
WebApp.MainButton.hide();
};
}, [submitting]);

return (
<div style={{ padding: '16px', color: 'var(--tg-theme-text-color)' }}>
<h3>Оформление услуги</h3>
<p>Клиент: {WebApp.initDataUnsafe.user?.first_name || 'Пользователь'}</p>
<p>К оплате: 2500 руб.</p>
</div>
);
};

4. Validating initData in PHP (HMAC-SHA256)

To ensure that the request originated from an authentic Telegram client, the backend must verify the cryptographic hash signature. The verification algorithm consists of the following steps:

  1. Parsing the `initData` string into key-value pairs and extracting the `hash` parameter.
  2. Filtering out `hash` from the array and alphabetically sorting the remaining keys.
  3. Building a check string in the format `key=value key2=value2`.
  4. Calculating `secret_key` = `HMAC-SHA256("WebAppData", bot_token)`.
  5. Calculating the final hash `HMAC-SHA256(data_check_string, secret_key)` and comparing it with the original `hash` using a secure string comparison.
  6. Checking the freshness of `auth_date` (to prevent replay attacks).
<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');

$botToken = getenv('TELEGRAM_BOT_TOKEN') ?: '';
$initDataRaw = $_SERVER['HTTP_X_TELEGRAM_INIT_DATA'] ?? '';

if (empty($botToken) || empty($initDataRaw)) {
http_response_code(400);
echo json_encode(['ok' => false, 'error' => 'Отсутствует initData или конфигурация']);
exit;
}

// 1. Парсим query-строку
parse_str($initDataRaw, $authData);

if (!isset($authData['hash'])) {
http_response_code(403);
echo json_encode(['ok' => false, 'error' => 'Подпись hash не найдена']);
exit;
}

$receivedHash = $authData['hash'];
unset($authData['hash']);

// 2. Сортируем параметры по алфавиту
$dataCheckArr = [];
foreach ($authData as $key => $value) {
$dataCheckArr[] = $key . '=' . $value;
}
sort($dataCheckArr);
$dataCheckString = implode("
", $dataCheckArr);

// 3. Генерируем HMAC ключ с префиксом WebAppData
$secretKey = hash_hmac('sha256', $botToken, 'WebAppData', true);
$calculatedHash = hash_hmac('sha256', $dataCheckString, $secretKey);

// 4. Безопасная сверка хешей (timing attack proof)
if (!hash_equals($calculatedHash, $receivedHash)) {
http_response_code(403);
echo json_encode(['ok' => false, 'error' => 'Недействительная подпись initData']);
exit;
}

// 5. Проверка устаревания данных (например, не старше 86400 секунд / 24 часа)
$authDate = (int)($authData['auth_date'] ?? 0);
if ((time() - $authDate) > 86400) {
http_response_code(403);
echo json_encode(['ok' => false, 'error' => 'Срок действия авторизации истек']);
exit;
}

// Данные подлинны, извлекаем объект пользователя
$userData = json_decode($authData['user'] ?? '{}', true);
$telegramUserId = $userData['id'] ?? null;

if (!$telegramUserId) {
http_response_code(422);
echo json_encode(['ok' => false, 'error' => 'Не удалось прочитать user ID']);
exit;
}

// Генерируем уникальный lead_id
$leadId = bin2hex(random_bytes(7));

// Логика сохранения заказа в БД...

echo json_encode([
'ok' => true,
'lead_id' => $leadId,
'telegram_user_id' => $telegramUserId,
]);

5. Sending Messages to the User via Telegram Bot API Using cURL

After a successful transaction on the backend, it is often necessary to notify the user in the bot chat. For API calls from PHP, cURL should be used with checks for HTTP status codes, JSON format errors, and the `ok: true` response structure.

<?php
declare(strict_types=1);

function sendTelegramMessage(int|string $chatId, string $text): bool
{
$botToken = getenv('TELEGRAM_BOT_TOKEN') ?: '';
if (empty($botToken)) {
return false;
}

$url = "https://api.telegram.org/bot{$botToken}/sendMessage";
$payload = [
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'HTML',
];

$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_TIMEOUT => 5,
CURLOPT_CONNECTTIMEOUT => 3,
]);

$response = curl_exec($ch);
$curlErrno = curl_errno($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($curlErrno !== 0 || $httpCode !== 200 || !$response) {
return false;
}

$decoded = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE || !($decoded['ok'] ?? false)) {
return false;
}

return true;
}

Conclusion

When building a Telegram Mini App with React, keep the client side completely isolated from making user validity decisions. Use @twa-dev/sdk for convenient integration with the messenger interface (MainButton, HapticFeedback, ThemeParams), but transmit critical data via request headers as a raw initData string and verify HMAC-SHA256 подпись in PHP.

If you need to build a fault-tolerant Telegram Mini App or integrate a bot with an existing CRM system, the BotCreator team will develop a solution tailored to your business needs.

New articles on Telegram

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