Validate Telegram.WebApp.initData on your server before you trust any of it. Parse the query string, take out hash, sort the remaining fields into key=value lines and compute an HMAC-SHA256 of that text. The key is itself an HMAC-SHA256 of your bot token, keyed with the string WebAppData. If the hex result equals hash, the data came from Telegram. Facts below come from Telegram’s Mini Apps page and the Bot API reference, version 10.3 of August 24, 2026 (both accessed 2026-11-04).
Ways to launch a Mini App
A Mini App is a web page that Telegram opens inside its client. WebAppInfo.url must be “An HTTPS URL”, so serve the page over HTTPS. How you launch it decides what the app receives and how it can answer the bot.
| Launch | How you set it | What changes |
|---|---|---|
| Keyboard button | KeyboardButton.web_app, private chats only |
The app can call sendData; no query_id |
| Inline keyboard button | InlineKeyboardButton.web_app, private chats only |
The app gets a query_id; the bot answers with answerWebAppQuery |
| Menu button | BotFather /setmenubutton, or setChatMenuButton |
Behaves like the inline button launch |
| Inline mode | button parameter of answerInlineQuery |
The app can call switchInlineQuery; no access to the chat |
| Main Mini App | BotFather; “Launch app” on the bot profile | Opens from t.me/<bot>?startapp links |
| Direct link | t.me/<bot>/<appname> |
No access to the chat; full-screen by default |
| Attachment menu | BotFather /setattach, startattach links |
Major advertisers on the Telegram Ad Platform only, any bot in the test environment |
Inline keyboard launches carry one more restriction. InlineKeyboardButton.web_app is “Not supported for messages sent on behalf of a business account”, which matters if you also run a Telegram Business bot. Per the Mini Apps page, direct links have opened full-screen by default since Bot API 7.6, and mode=compact opens them at half height. Bot API 10.1 added a launch for guard bots on chat join requests, sendChatJoinRequestWebApp.
This request sets the default menu button for every private chat with the bot. The JSON is built from the setChatMenuButton and MenuButtonWebApp field tables, since Telegram doesn’t publish a sample:
curl -s "https://api.telegram.org/bot$BOT_TOKEN/setChatMenuButton" \
-H "Content-Type: application/json" \
-d '{"menu_button": {"type": "web_app", "text": "Open app", "web_app": {"url": "https://example.com/app"}}}'
Leave out chat_id to change the default, or pass one to change a single private chat. The other menu button types, and setMyCommands, are covered in the Telegram commands menu post. Regular inline buttons, including web_app, are in Telegram inline keyboards and callback queries.
Set up Telegram.WebApp in the page
Load Telegram’s script in <head> “before any other scripts”. It creates window.Telegram.WebApp. Call ready() as early as you can, because Telegram keeps its loading placeholder on screen until you do or until the page finishes loading. expand() opens the app to full height and close() closes it. MainButton controls the button at the bottom of the app, with setText, onClick, show, hide and showProgress.
This page sends the raw initData string to your backend on load:
<!doctype html>
<html>
<head>
<script src="https://telegram.org/js/telegram-web-app.js?64"></script>
</head>
<body>
<p id="status">Loading</p>
<script>
const tg = window.Telegram.WebApp;
tg.ready();
fetch('/api/me', { headers: { Authorization: 'tma ' + tg.initData } })
.then((r) => r.json())
.then((me) => {
document.getElementById('status').textContent = 'Hello ' + me.first_name;
tg.MainButton.setText('Continue');
tg.MainButton.show();
});
</script>
</body>
</html>
The Authorization: tma header is a convention some libraries use, not a Telegram rule. Any header or body field works, as long as you send initData exactly as Telegram produced it.
The page also has initDataUnsafe, the same data already parsed into an object. Telegram’s warning is short: “Data from this field should not be trusted.” Use it to draw the interface, never to decide who the user is. version reports the Bot API version the user’s client supports, and isVersionAtLeast("8.0") tells you whether a feature exists before you call it.
What initData contains
initData is a URL-encoded query string. Complex fields such as user are JSON objects inside it.
| Field | What it holds |
|---|---|
query_id |
Session ID for answerWebAppQuery |
user |
The current user: id, first_name, username, language_code, is_premium, allows_write_to_pm |
receiver, chat |
Chat partner and chat, for attachment menu and join request launches |
chat_type, chat_instance |
Chat type and global chat ID, for direct link launches |
start_param |
The startapp or startattach value |
auth_date |
Unix time when the app was opened |
hash |
HMAC for validation by your bot’s server |
signature |
Ed25519 signature for validation by a third party |
The Mini Apps page says this object is empty for keyboard button and inline mode launches. user.id can use up to 52 significant bits, so store it as a 64-bit integer. The start_param value and its limits are explained in Telegram bot deep links.
Validate initData with HMAC-SHA256
Telegram publishes the check as pseudocode:
secret_key = HMAC_SHA256(<bot_token>, "WebAppData")
if (hex(HMAC_SHA256(data_check_string, secret_key)) == hash) {
// data is from Telegram
}
The data-check-string is “a chain of all received fields, sorted alphabetically, in the format key=\n). In HMAC_SHA256(<bot_token>, "WebAppData"), the bot token is the message and WebAppData is the key. Our implementation, standard library only:
import hashlib
import hmac
import json
import time
from urllib.parse import parse_qsl
def validate_init_data(init_data: str, bot_token: str, max_age_seconds: int = 3600) -> dict:
"""Validate Telegram.WebApp.initData on your server. Returns the parsed fields."""
fields = dict(parse_qsl(init_data, keep_blank_values=True, strict_parsing=True))
received_hash = fields.pop("hash", None)
if not received_hash:
raise ValueError("initData has no hash")
data_check_string = "\n".join(f"{k}={v}" for k, v in sorted(fields.items()))
secret_key = hmac.new(b"WebAppData", bot_token.encode(), hashlib.sha256).digest()
computed = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(computed, received_hash):
raise ValueError("initData hash mismatch")
auth_date = int(fields.get("auth_date", "0"))
if max_age_seconds and time.time() - auth_date > max_age_seconds:
raise ValueError("initData is too old")
for key in ("user", "receiver", "chat"):
if key in fields:
fields[key] = json.loads(fields[key])
return fields
parse_qsl decodes the URL encoding, and the data-check-string uses the decoded values. The code removes only hash, because that’s the value under comparison. It keeps signature when present, following the “all received fields” wording. Telegram’s bot-side section doesn’t mention signature either way, so test the function against real initData from your own bot before you rely on it.
The one-hour limit is our choice. Telegram says only that you “can additionally check the auth_date field” to reject outdated data, and it publishes no window. Pick one that fits how long your users keep the app open. Without any limit, a captured initData string stays valid forever.
Third-party check with Ed25519
A Mini App builder that processes data for someone else’s bot doesn’t hold the bot token. For that case Telegram added third-party validation, announced in the Bot API 8.0 changelog of November 17, 2024 (changelog). The signature field is “the base64url-encoded representation of the Ed25519 signature”, and the check needs only initData and the bot’s numeric ID.
The data-check-string starts with <bot_id>:WebAppData and a line feed. Then come all fields “except hash and signature”, sorted, one key=value per line. Telegram’s published production key is e7bf03a2fa4602af4580703d88dda5bb59f32ed8b02a56c187fe7d34caed242d. The test environment uses 40055058a4ee38156a06562e52eece92a771bcd8346a8c4615cb7376eddf72ec. Our version needs the third-party cryptography package (pip install cryptography):
import base64
from urllib.parse import parse_qsl
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
TELEGRAM_PROD_KEY = "e7bf03a2fa4602af4580703d88dda5bb59f32ed8b02a56c187fe7d34caed242d"
def verify_third_party(init_data: str, bot_id: int, public_key_hex: str = TELEGRAM_PROD_KEY) -> dict:
fields = dict(parse_qsl(init_data, keep_blank_values=True, strict_parsing=True))
signature = fields.pop("signature")
fields.pop("hash", None)
data_check_string = f"{bot_id}:WebAppData\n" + "\n".join(
f"{k}={v}" for k, v in sorted(fields.items())
)
sig = base64.urlsafe_b64decode(signature + "=" * (-len(signature) % 4))
Ed25519PublicKey.from_public_bytes(bytes.fromhex(public_key_hex)).verify(
sig, data_check_string.encode()
) # raises InvalidSignature on failure
return fields
Check auth_date here too, because a valid signature never expires.
Send results back to the chat
An app opened from an inline button, the menu button or the attachment menu can finish with answerWebAppQuery. Your server calls it with web_app_query_id, the query_id from validated initData, and result, an InlineQueryResult describing the message. Telegram sends that message “on behalf of the user” and closes the Mini App. Read can_send_after from initData if it’s present: it gives the seconds to wait before the call.
An app opened from a keyboard button uses Telegram.WebApp.sendData(data) instead. It sends up to 4096 bytes to the bot as a service message and closes the app. Your bot reads it from message.web_app_data.data. The Bot API reference warns that “a bad client can send arbitrary data in this field”. Check it like any other user input.
Origin hardening in Bot API 10.2
Bot API 10.2 of July 14, 2026 blocked “the usage of Mini App methods from origins different from the original” (changelog). Telegram turned it on for all Mini Apps on July 20, 2026, and BotFather has an opt-out. If your app loads its front end from one domain and embeds pages or iframes from another, Mini App method calls from the second origin are now refused. Serve the parts that call Telegram.WebApp from the domain in your WebAppInfo.url.
Z-API Omni team