Bot API: Mini Apps

SENSEVER

The official Sensever channel: guides and API documentation for Chat, Requests, Flow, Studio, bots and messaging channels.

4 мин чтения

Bot API: Mini Apps

A Mini App is a bot's web page that a person opens with a button in a bot message. It can be a catalog, an order form, appointment booking — any interface that is awkward to build out of messages. The page receives signed data about who opened it, and your server can trust that data after verifying the signature.

Button

A Mini App opens from an inline button with a web_app field:

{
  "client_message_id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
  "kind": "text",
  "text": "Choose a pizza in the catalog",
  "payload": {"buttons": [[{"text": "Open catalog", "web_app": {"url": "https://shop.example/app"}}]]},
  "send_as": "self"
}

The URL must be https:// only, up to 2048 characters. The button works in the Sensever web app and in the website widget. There are no other ways to open a Mini App (menu button, keyboard below the input field, inline mode, direct link).

Launch

When a person taps the button, Sensever checks that the message really has such a button, signs the launch data and opens the page in a new browser tab:

https://shop.example/app#tgWebAppData=auth_date%3D1790283600%26chat_instance%3D901%26…%26hash%3D…

The data is passed in the URL fragment (after #), so it does not end up in web server logs. If the button URL already contains #, the parameter is appended with &.

Launch data

The tgWebAppData value is a query string in application/x-www-form-urlencoded format:

Field

Description

auth_date

Launch time, Unix time in seconds

chat_instance

thread_id of the conversation where the button was tapped

chat_type

private (direct chat or project request), supergroup (group) or channel

query_id

Random launch UUID

user

JSON: id (number), first_name, language_code (the person's interface language)

hash

Signature, see below

user.id is the person's number in Sensever (the same as in p.<number>). A website visitor in a project request gets a permanent number greater than 2^51 that reveals nothing about their account.

How to read the data on the page

const launch = new URLSearchParams(location.hash.slice(1)).get("tgWebAppData");
// Send the string to your server as is and verify it there, for example in a header:
const res = await fetch("/api/session", { method: "POST", headers: { "X-Launch-Data": launch ?? "" } });

Do not trust the data until your server has verified it: anyone can open the page with any fragment.

Signature verification

The signature works as in Telegram, but with a different key: the bot's webhook_secret instead of the bot token.

  1. Parse the string and remove the hash field.

  2. Sort the remaining key=value pairs (values after URL decoding) by key and join them with a newline \n — this is data_check_string.

  3. secret_key = HMAC_SHA256(key = "WebAppData", message = webhook_secret).

  4. The signature is valid if hex(HMAC_SHA256(key = secret_key, message = data_check_string)) equals hash.

  5. Check auth_date: for example, reject data older than an hour.

Python

import hashlib
import hmac
import json
import time
from urllib.parse import parse_qsl


def check_launch(tg_web_app_data: str, webhook_secret: str, max_age: int = 3600):
    data = dict(parse_qsl(tg_web_app_data, keep_blank_values=True))
    received = data.pop("hash", "")
    check = "\n".join(f"{k}={v}" for k, v in sorted(data.items()))
    key = hmac.new(b"WebAppData", webhook_secret.encode(), hashlib.sha256).digest()
    expected = hmac.new(key, check.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, received):
        return None
    if time.time() - int(data.get("auth_date", "0")) > max_age:
        return None
    return json.loads(data["user"])

JavaScript

import { createHmac, timingSafeEqual } from "node:crypto";

function checkLaunch(tgWebAppData, webhookSecret, maxAge = 3600) {
  const data = new URLSearchParams(tgWebAppData);
  const received = Buffer.from(data.get("hash") ?? "");
  data.delete("hash");
  const check = [...data.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => `${k}=${v}`).join("\n");
  const key = createHmac("sha256", "WebAppData").update(webhookSecret).digest();
  const expected = Buffer.from(createHmac("sha256", key).update(check).digest("hex"));
  if (received.length !== expected.length || !timingSafeEqual(received, expected)) return null;
  if (Date.now() / 1000 - Number(data.get("auth_date")) > maxAge) return null;
  return JSON.parse(data.get("user"));
}

When the bot gets a new token, its webhook_secret changes too: data signed with the old secret no longer passes verification.

Differences from Telegram

  • The page opens in a regular browser tab, not inside the messenger. There is no window.Telegram.WebApp object with its methods (MainButton, sendData, close, color theme).

  • The signature uses the webhook secret, not the bot token. There is no signature field (verification without the token).

  • query_id is present, but there is no answerWebAppQuery method: to send something to the chat after actions on the page, your server sends a message with the regular method.

  • A Mini App opens only from a button in a message.

Комментарии

Авторы