Originally published at keston.dev — Telegram Bot & Mini App development cost guide. KESTON builds Telegram Mini Apps end to end — bot, backend, payments and admin — with USDT/USDC milestone settlement and full source handover.

Telegram Mini Apps have a security property that catches almost every team on their first build: the client can send you any initData string it likes. There is no cookie, no session token issued by Telegram, no server-side handshake. The whole trust model rests on one HMAC you compute yourself, and if that check is wrong in the silent way (returns true for garbage), your app is a public API where anyone can claim to be anyone.

I have reviewed enough Mini App backends to say this plainly: roughly half of the ones I have seen either skip verification in "dev mode" that reached production, or implement the HMAC with the two arguments swapped, which produces a hash that never matches — so someone wrapped it in a try/catch and shipped it as a warning.

Here is the check, the six ways it goes wrong, and the payment side, which has its own separate secret.

What initData actually is

When your Mini App loads inside Telegram, the client hands you Telegram.WebApp.initData: a URL-encoded query string.

query_id=AAHdF6IQAAAAAN0XohDhrOrc&user=%7B%22id%22%3A279058397%2C%22first_name%22%3A%22Vladislav%22%7D&auth_date=1662771648&hash=c501b72ae2af52a594f9c03f3244fb72baed9f20 

Four things matter:

  • user is JSON, then URL-encoded. You must decode before parsing.
  • auth_date is a Unix timestamp in seconds.
  • hash is the signature over everything else.
  • The order of keys in the string is not the order you sign in. You sort.

The algorithm, without hand-waving

Telegram's spec is two HMACs, and the nesting is where people get it backwards.

import crypto from "node:crypto"; const MAX_AGE_SECONDS = 3600; // tune to your session length export function verifyInitData(initData, botToken, nowSec = Math.floor(Date.now() / 1000)) { if (typeof initData !== "string" || initData.length === 0) return null; const params = new URLSearchParams(initData); const hash = params.get("hash"); if (!hash) return null; // 1) secret_key = HMAC_SHA256(key="WebAppData", message=bot_token) const secretKey = crypto.createHmac("sha256", "WebAppData").update(botToken).digest(); // 2) data_check_string: every field except hash, sorted by key, joined with \n const pairs = []; for (const [k, v] of params.entries()) { if (k === "hash") continue; pairs.push(`${k}=${v}`); } pairs.sort(); const dataCheckString = pairs.join("\n"); // 3) expected = HMAC_SHA256(key=secret_key, message=data_check_string) const expected = crypto.createHmac("sha256", secretKey).update(dataCheckString).digest("hex"); // 4) constant-time compare const a = Buffer.from(expected, "hex"); const b = Buffer.from(hash, "hex"); if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) return null; // 5) freshness — the signature never expires on its own const authDate = Number(params.get("auth_date") || 0); if (!authDate || nowSec - authDate > MAX_AGE_SECONDS) return null; let user = null; try { user = JSON.parse(params.get("user") || "null"); } catch { return null; } if (!user || typeof user.id !== "number") return null; return { user, authDate, startParam: params.get("start_param") || null }; } 

That is the whole thing. Twenty lines. The failures are all in the details around it.

Six ways this goes silently wrong

1. Swapping the HMAC arguments. The spec is HMAC(key = "WebAppData", message = bot_token) for the secret, then HMAC(key = secret, message = data_check_string). If you write HMAC(key = botToken, message = "WebAppData"), you get a stable but wrong secret. Every signature fails, the happy path in staging used initDataUnsafe, and the check gets demoted to a log line. If your verification function has never returned false in production, it is not verifying anything — add a test that feeds it a tampered string and asserts rejection.

2. Forgetting the second decode. URLSearchParams decodes once. The user field's value is URL-encoded JSON, so after params.get("user") you have the JSON string and JSON.parse works. But if you read initData from a JSON body where the client already decoded it once, %22 becomes " and the signature no longer matches — because you signed the decoded form while Telegram signed the encoded form. Always sign exactly the bytes Telegram sent.

3. No freshness check. A valid initData is valid forever. It is a bearer credential with no expiry, and it circulates: support tickets, screenshots, crash reports, a shared QA link. Enforce auth_date — an hour is generous for a shopping session. This one line is the difference between "session hijack requires the victim's phone" and "session hijack requires a log file".

4. Verifying on the client. I have seen if (!verify(initData)) in Mini App front-end code. The client is the attacker's machine. Verification happens on your server, on every request that needs identity, with the bot_token that never leaves the server.

5. Trusting initDataUnsafe. The name is the documentation. initDataUnsafe.user is what the Telegram client says; initData is what you can prove. Use the unsafe copy for rendering a greeting, never for authorisation.

6. String comparison. === on hex strings leaks timing. Use timingSafeEqual on buffers of equal length, and compare lengths first.

The payment side has a different secret

Mini App payments go through your bot, not your front end:

  1. Server calls createInvoiceLink with your provider token — this stays server-side, always.
  2. Telegram shows the payment sheet inside the Mini App.
  3. Telegram calls your webhook with a pre_checkout_query; you have 10 seconds to answer answerPreCheckoutQuery with ok: true or a reason.
  4. After payment, successful_payment arrives in a message update.

Two things people miss. First, the webhook itself is unauthenticated by default — set secret_token when calling setWebhook and reject any request whose X-Telegram-Bot-Api-Secret-Token header does not match, otherwise anyone can POST you fake successful_payment updates and mint orders. Second, pre_checkout_query is your last chance to reject (out of stock, price changed, banned user) — after ok: true, refunds are manual.

And the amount in successful_payment.total_amount is in the currency's smallest unit, as an integer. If you store money as floats anywhere in this flow, you will eventually ship a rounding bug that pays out one cent too many on a thousand orders, and reconciling that against Telegram's ledger is a genuinely miserable afternoon.

What this means for scope and cost

The signature check is 20 lines. The Mini App around it is not, and the estimate people get wrong is always the same: they budget for the front end and forget that a Mini App is a full-stack product with a bot attached.

A realistic first-release scope:

  • Mini App front end (React/Vue, Telegram theme variables, back-button handling, safe areas on iOS)
  • Bot: commands, MenuButton, deep-link start_param routing
  • Backend: session, initData verification, order state machine
  • Payments: invoice links, pre_checkout_query, successful_payment, idempotent fulfilment
  • Admin: orders, refunds, broadcast, and a ledger you can reconcile
  • Ops: webhook secret, rate limits, error alerting

That lands at 2–4 weeks for a focused build, not the "5 days" that a front-end-only quote implies. The cost guide linked above breaks the range down by scope; the Telegram Bot & Mini App service page covers what is in each tier, and pricing lists the milestone structure.

The test that matters

Before you ship, write this test:

test("tampered initData is rejected", () => { const good = buildSignedInitData({ id: 42 }, "123:ABC"); const bad = good.replace(/%22id%22%3A42/, "%22id%22%3A43"); assert.equal(verifyInitData(bad, "123:ABC"), null); }); test("expired initData is rejected", () => { const old = buildSignedInitData({ id: 42 }, "123:ABC", Math.floor(Date.now() / 1000) - 7200); assert.equal(verifyInitData(old, "123:ABC"), null); }); 

If both pass, your check is real. If the first one throws instead of returning null, you are one try/catch away from the silent no-op that half the Mini Apps in production are running right now.

Leon builds Telegram Mini Apps and bots at KESTON — an independent full-stack studio working with USDT/USDC 50/50 milestones and 100% unencrypted Git handover. Reach out on Telegram or hello@keston.dev. Not affiliated with Keston Boilers (UK).