Building a customized e-commerce store, booking engine, or SaaS portal inside Telegram's WebApp container with React provides a crisp, native-feeling user experience. However, a widespread security vulnerability exists in front-end Mini App architectures. When initializing inside Telegram, the browser injects the global window.Telegram.WebApp object. Developers often inspect window.Telegram.WebApp.initDataUnsafe and extract initDataUnsafe.user.id directly in React, forwarding it to a REST API to retrieve orders or balance details.

Because initDataUnsafe is completely exposed to the client browser, anyone can open DevTools, modify JavaScript state, or issue arbitrary POST requests targeting your endpoints with a spoofed user_id. An attacker can read or modify another user's account data simply by altering an integer in an HTTP request payload.

To secure your API, you must validate the raw window.Telegram.WebApp.initData query string on your PHP server using a HMAC-SHA256 signature algorithm before authorizing any backend operations. This tutorial walks through setting up a complete authentication flow: sending raw initData from React via authorization headers, validating it in PHP against your secret Telegram Bot Token, issuing a JSON Web Token (JWT), and using that JWT for all subsequent backend endpoints.

The Architecture of the HMAC Handshake

Passing raw initData on every single REST API request leads to redundant cryptographic overhead. A full initData string contains URL-encoded user profiles, chat metadata, start parameters, and timestamps. Parsing and validating cryptographic signatures on every high-frequency database request increases server latency and litters API code with parsing logic.

A cleaner pattern separates authentication into two distinct phases:

  1. The Exchange Phase: Upon app mount, the React front end reads the unparsed window.Telegram.WebApp.initData string. It sends this string inside an HTTP header (such as X-Telegram-Init-Data) to a dedicated authentication endpoint on your PHP backend (POST /api/auth/telegram).
  2. The Verification & Token Phase: The PHP backend decrypts and verifies the initData payload using a derived HMAC-SHA256 key matching your Telegram Bot Token. If valid and executed within an acceptable timeframe, PHP extracts the user's verified identity, issues a signed JWT containing the verified Telegram User ID, and returns it to React.
  3. The Authenticated Phase: React stores the JWT in memory and attaches it to standard Authorization: Bearer <jwt> headers for all subsequent requests to fetch orders, submit forms, or update account state.
+-----------------------+ +------------------------+ | React Mini App | | PHP REST Server | +-----------------------+ +------------------------+ | | | 1. POST /api/auth/telegram | | (Header: X-Telegram-Init-Data) | |-------------------------------------------->| | | 2. Reconstruct check string | | 3. HMAC-SHA256 hash check | | 4. Validate auth_date freshness | 5. Return JWT token { token: "..." } | 5. Issue JWT payload |<--------------------------------------------| | | 6. GET /api/user/orders | (Header: Authorization: Bearer <JWT>) |-------------------------------------------->| | | 7. Decode JWT signature | 8. Return JSON business payload | 8. Execute DB query |<--------------------------------------------| 

Step 1: Client-Side Authentication Handshake in React

On the React side, we create a specialized hook or context wrapper that executes before rendering the rest of the application. The hook extracts initData, submits it to our authentication service, and exposes an authenticated HTTP client to the rest of the app.

If the Mini App is accessed outside of Telegram (for instance, directly in a standard web browser without parameter injection), window.Telegram.WebApp.initData will be an empty string. The hook must gracefully detect this state and abort backend verification early.

Here is a complete, copy-pasteable React implementation using TypeScript:

import React, { createContext, useContext, useEffect, useState } from 'react'; declare global { interface Window { Telegram?: { WebApp?: { initData: string; ready: () => void; }; }; } } interface AuthContextType { token: string | null; isAuthenticated: boolean; isLoading: boolean; error: string | null; } const AuthContext = createContext<AuthContextType>({ token: null, isAuthenticated: false, isLoading: true, error: null, }); export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => { const [token, setToken] = useState<string | null>(null); const [isLoading, setIsLoading] = useState<boolean>(true); const [error, setError] = useState<string | null>(null); useEffect(() => { const authenticateUser = async () => { const telegram = window.Telegram?.WebApp; if (telegram) { telegram.ready(); } const initData = telegram?.initData; if (!initData) { setError('Application must be launched inside Telegram.'); setIsLoading(false); return; } try { const response = await fetch('/api/auth/telegram.php', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Telegram-Init-Data': initData, }, }); const data = await response.json(); if (!response.ok || !data.success) { throw new Error(data.message || 'Authentication failed'); } setToken(data.token); } catch (err: any) { setError(err.message || 'Network error during identity verification'); } finally { setIsLoading(false); } }; authenticateUser(); }, []); return ( <AuthContext.Provider value={{ token, isAuthenticated: !!token, isLoading, error }}> {children} </AuthContext.Provider> ); }; export const useAuth = () => useContext(AuthContext); 

Step 2: Server-Side HMAC Validation Engine in PHP

To verify initData securely in PHP, we must follow Telegram's exact cryptographic specification:

  1. Parse the query string into key-value pairs (e.g., using parse_str).
  2. Extract the hash parameter and remove it from the array of parameters.
  3. Sort the remaining key-value array alphabetically by key.
  4. Reconstruct a data_check_string where each pair is formatted as key=value, concatenated with newline (\n) characters.
  5. Compute a secret key using HMAC-SHA256 with the constant string WebAppData as key and your Telegram Bot Token as data.
  6. Compute the HMAC-SHA256 signature of the data_check_string using the generated secret key.
  7. Compare your generated hex hash against the original hash parameter using hash_equals() to prevent timing attacks.
  8. Check the auth_date parameter to confirm the token has not expired.

Below is a strict PHP class that encapsulates this validation workflow without external dependencies:

<?php declare(strict_types=1); class TelegramInitDataValidator { private string $botToken; private int $maxLifetimeSeconds; public function __construct(string $botToken, int $maxLifetimeSeconds = 86400) { $this->botToken = $botToken; $this->maxLifetimeSeconds = $maxLifetimeSeconds; } /** * Validates raw initData string and returns the decoded payload array. * @throws Exception if signature is invalid or data is stale. */ public function validate(string $rawInitData): array { if (empty($rawInitData)) { throw new Exception('Missing initialization data.'); } parse_str($rawInitData, $data); if (!isset($data['hash'])) { throw new Exception('Missing hash signature in payload.'); } $receivedHash = $data['hash']; unset($data['hash']); $dataCheckArr = []; foreach ($data as $key => $value) { $dataCheckArr[] = $key . '=' . $value; } sort($dataCheckArr); $dataCheckString = implode(" ", $dataCheckArr); // Step 1: Create key HMAC-SHA256("WebAppData", bot_token) $secretKey = hash_hmac('sha256', $this->botToken, 'WebAppData', true); // Step 2: Compute hash HMAC-SHA256(data_check_string, secret_key) $calculatedHash = hash_hmac('sha256', $dataCheckString, $secretKey); // Step 3: Constant-time string comparison if (!hash_equals($calculatedHash, $receivedHash)) { throw new Exception('Invalid cryptographic signature. Identity spoofing detected.'); } // Step 4: Validate timestamp freshness if (!isset($data['auth_date']) || !is_numeric($data['auth_date'])) { throw new Exception('Missing or invalid auth_date parameter.'); } $authDate = (int) $data['auth_date']; if ((time() - $authDate) > $this->maxLifetimeSeconds) { throw new Exception('Authentication session payload has expired.'); } // Parse embedded user JSON if (isset($data['user'])) { $data['user'] = json_decode($data['user'], true); } return $data; } } 

Step 3: Generating JWT and Authenticating Requests in PHP

Once the cryptographic signature passes, we construct a JSON Web Token (JWT) on the PHP backend containing the verified Telegram User ID. This allows subsequent requests to be verified quickly using standard secret-key JWT decoding.

Here is the controller script (/api/auth/telegram.php) that processes the incoming authorization header, uses our validator class, and returns a signed JWT:

<?php declare(strict_types=1); require_once __DIR__ . '/TelegramInitDataValidator.php'; header('Content-Type: application/json'); $botToken = getenv('TELEGRAM_BOT_TOKEN') ?: ''; $jwtSecret = getenv('JWT_SECRET') ?: ''; if (empty($botToken) || empty($jwtSecret)) { http_response_code(500); echo json_encode(['success' => false, 'message' => 'Server authentication context unconfigured.']); exit; } $rawInitData = $_SERVER['HTTP_X_TELEGRAM_INIT_DATA'] ?? ''; if (empty($rawInitData)) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Missing authorization header.']); exit; } try { $validator = new TelegramInitDataValidator($botToken, 86400); $validatedData = $validator->validate($rawInitData); $user = $validatedData['user'] ?? null; if (!$user || !isset($user['id'])) { throw new Exception('User entity missing inside payload.'); } $telegramId = (int) $user['id']; // Construct JWT Header & Payload $header = base64UrlEncode((string) json_encode(['alg' => 'HS256', 'typ' => 'JWT'])); $payload = base64UrlEncode((string) json_encode([ 'sub' => $telegramId, 'first_name' => $user['first_name'] ?? '', 'iat' => time(), 'exp' => time() + (86400 * 7), // Valid for 7 days ])); $signature = base64UrlEncode(hash_hmac('sha256', "$header.$payload", $jwtSecret, true)); $jwtToken = "$header.$payload.$signature"; echo json_encode([ 'success' => true, 'token' => $jwtToken, 'user' => [ 'id' => $telegramId, 'first_name' => $user['first_name'] ?? '', ], ]); } catch (Exception $e) { http_response_code(403); echo json_encode(['success' => false, 'message' => $e->getMessage()]); } function base64UrlEncode(string $data): string { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); } 

Step 4: Making Authenticated API Calls in React

With our token handshake implemented, we write a custom useApi hook or helper function in React. This fetch wrapper automatically inserts the verified JWT into every outbound REST call targeting internal operational routes.

import { useAuth } from './AuthProvider'; export function useApiClient() { const { token } = useAuth(); const apiFetch = async (endpoint: string, options: RequestInit = {}) => { if (!token) { throw new Error('Attempting to call authenticated API without active JWT session.'); } const headers = new Headers(options.headers || {}); headers.set('Authorization', `Bearer ${token}`); headers.set('Content-Type', 'application/json'); const response = await fetch(endpoint, { ...options, headers, }); if (response.status === 401 || response.status === 403) { throw new Error('Session expired or unauthorized.'); } return response.json(); }; return { apiFetch }; } 

Now, inside components like checkout forms or dashboard views, components execute state modifications cleanly, knowing that the identity parameter is extracted solely from the cryptographically verified JWT payload on the backend:

import React, { useState } from 'react'; import { useApiClient } from './useApiClient'; export const SubmitOrderButton: React.FC<{ cartId: string }> = ({ cartId }) => { const { apiFetch } = useApiClient(); const [loading, setLoading] = useState(false); const handleCheckout = async () => { setLoading(true); try { const result = await apiFetch('/api/orders/create.php', { method: 'POST', body: JSON.stringify({ cartId }), }); alert(`Order created successfully! ID: ${result.orderId}`); } catch (err: any) { alert(`Checkout failed: ${err.message}`); } finally { setLoading(false); } }; return ( <button onClick={handleCheckout} disabled={loading}> {loading ? 'Processing...' : 'Confirm Order'} </button> ); }; 

Production Security Notes

  1. Replay Window Enforcement: Never allow unbounded auth_date parameters. An attacker who intercepts a valid initData payload could replay it to obtain fresh JWTs indefinitely if you don't check auth_date. Setting $maxLifetimeSeconds to 3600 (1 hour) or 86400 (24 hours) limits the window during which stolen initData remains valid.
  2. Always Use hash_equals(): Standard equality operators (== or ===) in PHP are vulnerable to timing attacks. An attacker can analyze microsecond variance during string comparisons to deduce character positions in the signature. hash_equals() performs a constant-time string comparison, eliminating this vulnerability.
  3. Call WebApp.ready() Early: Call window.Telegram.WebApp.ready() as soon as possible inside React's initial mount cycle. If your authorization logic fails or delays execution before calling .ready(), the Telegram Mini App container may display a blank or stuck loading indicator on mobile clients.
  4. Do Not Store Bot Tokens in Front-End Repositories: The HMAC verification key is derived directly from your Telegram Bot Token. If your secret bot token leaks into front-end build artifacts, an attacker can create valid signatures for any arbitrary Telegram User ID. Keep the bot token securely configured inside server environment variables.

Need assistance scaling your bot backends or building robust client integrations? Partner with BotCreator — studio that ships Telegram bots / Mini Apps.