A-chat for developers

Mini apps and Hub

A mini app is a web page that opens full screen inside A-chat. It looks like part of the app: it gets the theme colours, the safe areas and the size of the window, and it learns who opened it through a signed initData, never through the person’s own login.

Hub is the place where people find mini apps and games. On the phone it is a tab; in the web version and the desktop app it is in the main menu. A mini app can also be opened by a bot it is linked to.

You build the page and its server anywhere you like. A-chat gives the window, the SDK and the signed identity.

The developer’s way

  1. Make the app on the developer portal or in My mini apps.
  2. Add the SDK to your page.
  3. Check initData on your server, yourself or with the check API.
  4. Open the app yourself to try it while it waits for review.
  5. Optionally, verify your domain.
  6. The A-chat team reviews it. When it is approved, it appears in Hub.
  7. Optionally, link a bot of yours to it.

Make an app

Open developer.a-chat.app, sign in with your A-chat account and choose Mini apps → New mini app; or open Settings → For developers → My mini apps on the phone, the web version or the desktop app, and tap New mini app. The portal also shows the app’s launches, its rating and every review. You can also send /newapp to @achatbot: it asks for the id, the title and the address, and uses the address’s host as the app’s only host.

Field Rules
Id 3 to 32 of a-z, 0-9 and _, starting with a letter. It cannot be changed. Some words are kept for the team.
Title 1 to 40 characters.
Short line Up to 120 characters. Shown in Hub under the title.
Address The first page, https, on one of the app’s hosts, on the usual port.
Hosts 1 to 10 host names the app may load from: example.com or *.example.com. Put here every host the page needs (its API, a CDN, fonts, pictures).
Outside sites Up to 5 hosts that may open in the system browser after the person agrees, for example your terms page or a shop.
Kind app or game.
Category One short word: up to 32 of a-z, 0-9, _ and -, starting with a letter. For example tools, education, shopping. The A-chat team keeps the list of categories Hub shows, with their names in each language. An app whose category is not on the list is still shown under All.
Icon and cover Pictures you upload. The cover is the wide picture of a featured card.
Privacy policy, terms of use https links. Shown on the app’s page in Hub.
May ask for Camera, microphone, location. Declare only what the app needs. See Camera, microphone and location.
Full screen Opens with no bar of A-chat over the page. Two small floating buttons stay at the top right: keep contentSafeAreaInset.top clear. See requestFullscreen.

A person may have up to 20 mini apps (50 with A-chat Plus) and make up to 5 a day. Over that a new one is refused; nothing is removed when Plus ends.

Review

A new app is pending. The team approves it (live) or rejects it with a reason, which you see in My mini apps. The team can also freeze an app: it stops opening.

Any change you make to the app sends it back to pending. A frozen app stays frozen.

While an app is pending, its owner can open it to check it (Open to check). Nobody else sees it.

The key

Each app has its own key, shaped like a bot token: <number>:<secret>. Your server uses it to check initData.

Keep the key on your server only. Never put it in the page.

An app and a bot are separate things. You may link one of your bots to one of your apps, and unlink it at any time. A bot can be linked to one app.

When an app is linked to a bot:

Deleting the bot unlinks it. The app stays.

Add the SDK

Put the SDK in the <head> of every page, before your own scripts:

<script src="https://a-chat.app/sdk/webapp.js"></script>

It makes window.AChat.WebApp:

<script>
  const app = window.AChat.WebApp;
  app.ready();
  document.body.style.background = app.themeParams.bg_color || '#ffffff';
  app.MainButton.setText('Order').show().onClick(() => {
    app.showConfirm('Place the order?', (ok) => {
      if (ok) app.sendData(JSON.stringify({ item: 'coffee', size: 'M' }));
    });
  });
</script>

On the phone, A-chat puts the same bridge into the page before it loads, and the file then does nothing. In the web version and the desktop app, the file connects the page to the window. Either way, your code is the same.

The full list of fields, methods and events is in the SDK reference.

The rules of the window

Link What happens
On the app’s hosts Opens inside the window.
An A-chat link (a-chat://... or https://a-chat.app/...) The window closes and the app opens that place.
tel: or mailto: The system asks the person, then calls or writes.
On one of the app’s outside sites The person sees the host and is asked; then it opens in the system browser.
Anything else Refused, with a short note.

In the web version and the desktop app the page runs in a sandboxed frame. It cannot open popups, navigate the top window, download files or use alert(), confirm() and prompt(). Use WebApp.showAlert, showConfirm and showPopup. A browser cannot limit the requests your page makes from inside the frame, but the window still keeps the page itself on your hosts.

Who opened the app: initData

On every launch, A-chat signs a short string for the person and the app. The page gets it as WebApp.initData:

app_id=food_tracker&auth_date=1795449683&bot=foodbot&platform=ios&query_id=AAQ...&user=%7B%22id%22%3A7000000042%2C...%7D&hash=a86a...
Field Description
query_id A random id of this launch.
user JSON: id, first_name, username (when set), language_code (when known), is_plus (only when true), allows_write_to_pm.
auth_date Unix time of the launch.
app_id Your app’s id.
platform ios, android, web, macos, windows, linux or unknown.
bot When linked. The linked bot’s @name.
start_param When given. What a link started the app with: https://a-chat.app/a/<app id>?startapp=<param> (1-64 of A-Z a-z 0-9 _ -).
chat_type Opened from a chat (a web_app button under a message, the bot’s menu button), when the person is in it: sender (their chat with the app’s linked bot), private, group or channel.
chat_instance With chat_type. A string that is the same for this app and chat on every launch (a group’s topics share it) and different for another app: keep per-chat state by it.
hash The signature.

user.id is the same number your linked bot sees for that person.

The page must send initData to your server, and your server must check it before it trusts anything in it. WebApp.initDataUnsafe is for drawing only: it is not signed, and its fields may differ between platforms.

How to check it

  1. Parse initData as a URL query string. Decode each value.
  2. Take out hash.
  3. Sort the remaining fields by name. Join them as name=value, one per line (\n). This is the data-check string.
  4. secret_key = HMAC_SHA256(key = "WebAppData", message = <the app's key>).
  5. expected = hex(HMAC_SHA256(key = secret_key, message = <data-check string>)).
  6. Compare expected with hash in constant time. Different: reject.
  7. Check auth_date. Reject data older than you allow; one hour is a good limit.
  8. Parse user as JSON. Use user.id as the person’s id in your app.

The app’s key is the whole key: the number, the colon and the secret.

Node.js

import crypto from 'node:crypto';

export function checkInitData(initData, appKey, maxAgeSeconds = 3600) {
  const params = new URLSearchParams(initData);
  const hash = params.get('hash');
  if (!hash) return null;
  params.delete('hash');
  const dataCheckString = [...params.entries()]
    .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
    .map(([key, value]) => `${key}=${value}`)
    .join('\n');
  const secretKey = crypto.createHmac('sha256', 'WebAppData').update(appKey).digest();
  const expected = crypto.createHmac('sha256', secretKey).update(dataCheckString).digest();
  const given = Buffer.from(hash, 'hex');
  if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return null;
  const authDate = Number(params.get('auth_date'));
  if (!authDate || Date.now() / 1000 - authDate > maxAgeSeconds) return null;
  const data = Object.fromEntries(params);
  if (data.user) data.user = JSON.parse(data.user);
  return data;
}

// const data = checkInitData(req.body.initData, process.env.ACHAT_APP_KEY);
// if (!data) return res.status(401).end();
// const personId = data.user.id;

Python

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


def check_init_data(init_data: str, app_key: str, max_age: int = 3600):
    fields = dict(parse_qsl(init_data, keep_blank_values=True))
    received = fields.pop("hash", "")
    if not received:
        return None
    data_check_string = "\n".join(f"{k}={fields[k]}" for k in sorted(fields))
    secret_key = hmac.new(b"WebAppData", app_key.encode(), hashlib.sha256).digest()
    expected = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, received):
        return None
    if time.time() - int(fields.get("auth_date", "0")) > max_age:
        return None
    if "user" in fields:
        fields["user"] = json.loads(fields["user"])
    return fields


# data = check_init_data(request.form["initData"], os.environ["ACHAT_APP_KEY"])
# if data is None: abort(401)
# person_id = data["user"]["id"]

When the launch could not be signed (for example while the app’s key is revoked), the phone opens the page with an empty initData. Show a message instead of the app’s content in that case.

You can also let A-chat do the check: see checkInitData.

The check API for your server

Your server can call A-chat with the app’s key, in the same way a bot calls the Bot API:

https://api.a-chat.app/miniapp<app key>/<method>

Keep the key on your server. The page itself never calls this API.

checkInitData

Checks that initData was signed by A-chat for this app, and is younger than a day.

Parameter Type Required Description
init_data String Yes WebApp.initData, exactly as the page got it.

Returns { "valid": false } for data that is wrong, too old or of another app. Otherwise valid: true and the fields of initData: user as an object, the other fields as strings.

curl "https://api.a-chat.app/miniapp123456:ABC.../checkInitData" \
  --data-urlencode "init_data=app_id=food_tracker&auth_date=1795449683&..."
{
  "ok": true,
  "result": {
    "valid": true,
    "user": { "id": 7000000042, "first_name": "Anna", "username": "anna", "language_code": "en", "allows_write_to_pm": true },
    "auth_date": "1795449683",
    "query_id": "AAQ...",
    "app_id": "food_tracker",
    "platform": "ios",
    "bot": "foodbot"
  }
}

A day is the longest the check accepts. Check auth_date yourself when you want a shorter limit.

sendMessage

Writes to a person through the bot linked to the app.

Parameter Type Required Description
user_id Integer Yes The person’s number: user.id of their initData.
text String Yes 1 to 4,096 characters.
parse_mode String No HTML, MarkdownV2 or Markdown. See Formatting.
entities Array No The marks of text, instead of parse_mode.
start_param String No 1-64 of A-Z a-z 0-9 _ -: what the app is opened with from this message’s notification (start_param of initData).

Returns { "message_id": ..., "date": ... }.

getStats

No parameters. Returns the app’s numbers, never a name:

{
  "ok": true,
  "result": {
    "launches": { "day": 120, "month": 3400 },
    "people": { "day": 80, "month": 1500, "total": 4200 },
    "rating": { "average": 4.6, "count": 57 }
  }
}

day is today (UTC). month is the last 30 days.

Node.js

const KEY = process.env.ACHAT_APP_KEY; // 123456:ABC...
const API = `https://api.a-chat.app/miniapp${KEY}/`;

async function call(method, params = {}) {
  const response = await fetch(API + method, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
  const data = await response.json();
  if (!data.ok) throw new Error(`${data.error_code}: ${data.description}`);
  return data.result;
}

// In your route that gets initData from the page:
const checked = await call('checkInitData', { init_data: req.body.initData });
if (!checked.valid) return res.status(401).end();

if (checked.user.allows_write_to_pm) {
  await call('sendMessage', {
    user_id: checked.user.id,
    text: '<b>Thanks!</b> Your order is on its way.',
    parse_mode: 'HTML',
  });
}

const stats = await call('getStats');
console.log('people today', stats.people.day);

Launching from a bot

web_app buttons

Send an inline button with web_app:

{
  "chat_id": 7000000042,
  "text": "Open the menu",
  "reply_markup": {
    "inline_keyboard": [[{ "text": "Menu", "web_app": { "url": "https://example.com/menu" } }]]
  }
}

The button opens the mini-app window when its address is on the hosts of the app linked to the bot. Otherwise the phone asks the person whether to open it as a link, and the web version and the desktop app say it cannot open there.

The bot’s menu button can open the app too. Set it with setChatMenuButton and {"type": "web_app", "text": "Order", "web_app": {"url": "https://example.com/menu"}}: the button stands left of the field in the bot’s chat, on the same rule of hosts. See setChatMenuButton.

answerWebAppQuery

initData has a query_id. The linked bot can answer the launch with one result:

curl "https://api.a-chat.app/bot123456:ABC.../answerWebAppQuery" \
  -H "Content-Type: application/json" \
  -d '{
    "web_app_query_id": "AAQ...",
    "result": {
      "type": "article",
      "id": "order-42",
      "title": "Order 42",
      "input_message_content": { "message_text": "Order 42: 1 coffee, size M" }
    }
  }'

The page gets the query_id from initData, sends it to your server, and your server calls the bot. See answerWebAppQuery.

sendData and web_app_data

WebApp.sendData(data) sends up to 4,096 bytes to the linked bot and closes the window. The bot gets an update:

{
  "update_id": 120,
  "message": {
    "message_id": 0,
    "from": { "id": 7000000042, "is_bot": false, "first_name": "Anna", "username": "anna", "language_code": "en" },
    "chat": { "id": 7000000042, "type": "private", "first_name": "Anna", "username": "anna" },
    "date": 1795449700,
    "web_app_data": { "data": "{\"item\":\"coffee\",\"size\":\"M\"}", "button_text": "" }
  }
}

It works only when the app has a linked bot and the person has started that bot. Otherwise nothing reaches the bot. sendData works from any launch of the app, from Hub too.

For anything bigger or more private, send the data from the page to your own server with initData, and let your server answer the person through the bot, with the Bot API or the check API’s sendMessage.

The web version and the desktop app

In the web version and the desktop app, Hub opens an app in a panel. The page is loaded in a sandboxed frame inside a page of A-chat, never at the top level.

Use the SDK rather than these messages: they may change.

Let A-chat show your page in its frame

Because the page sits in a frame there, your server must allow A-chat to frame it. Many hosts and frameworks forbid framing by default. Then the window stays empty in the web version and the desktop app, while the phone shows the page as usual.

Your page cannot be framed when it answers with:

Send this instead, on every page of the app, and drop X-Frame-Options:

Content-Security-Policy: frame-ancestors https://web.a-chat.app

If your site already sends a Content-Security-Policy, add the frame-ancestors directive to it rather than sending a second header. Keep 'self' in the list if your own pages frame each other: frame-ancestors 'self' https://web.a-chat.app. The desktop app shows your page under the same address, https://web.a-chat.app, so this one line covers both.

Caddy

header {
	-X-Frame-Options
	Content-Security-Policy "frame-ancestors https://web.a-chat.app"
}

nginx

proxy_hide_header X-Frame-Options;
add_header Content-Security-Policy "frame-ancestors https://web.a-chat.app" always;

Apache

Header always unset X-Frame-Options
Header always set Content-Security-Policy "frame-ancestors https://web.a-chat.app"

Cloudflare. In the dashboard, open Rules → Transform Rules → Modify Response Header and create a rule for your app’s host:

If your origin server already sends a Content-Security-Policy, change it there instead, so the two do not clash.

Express (helmet)

app.use(helmet({
  frameguard: false,
  contentSecurityPolicy: { directives: { frameAncestors: ["https://web.a-chat.app"] } },
}));

Next.js (next.config.js)

module.exports = {
  async headers() {
    return [{ source: "/(.*)", headers: [{ key: "Content-Security-Policy", value: "frame-ancestors https://web.a-chat.app" }] }];
  },
};

To check it, run curl -sI https://<your host>/ and look for these two headers. Then open the app from Hub at web.a-chat.app. If the window stays empty, the browser’s console names the header that stopped it.

Also list in the app’s hosts every host the page needs: a CDN, your API on another subdomain, a fonts host. On the phone, requests to a host that is not listed are refused.

Verify your domain

Show that the app’s site is yours. The domain is the host of the app’s Address. Verifying it is not required: an app works without it, and the team sees it when it reviews the app.

The A-chat team may make it required, for every app or for one app. Then, until the domain is verified, the app opens only for you and is not shown in Hub. Your app’s screen and the developer portal say whether it is required now.

  1. Open the app on the developer portal (tab Domain) or in My mini apps. Its domain section shows a token, and two ways to prove the domain.
  2. Do one of them:
    • A file. Serve https://<host>/.well-known/achat-app.json with exactly what the screen shows:

      { "app": "food_tracker", "token": "<the token from the screen>" }

      It must answer 200 over HTTPS, without a redirect.

    • A DNS record. Add a TXT record achat-app=<the token> on _achat-app.<host>, or on the host itself.

  3. Tap Check. The screen shows the domain as verified, and how.

The token stays the same for the app. A DNS record may take some time to be seen: check again later if it fails at first.

Let the portal add the record

On the developer portal the domain tab finds who hosts your DNS. If it is Cloudflare, the portal opens Cloudflare’s token form already filled in (Zone → DNS → Edit and Zone → Zone → Read; choose only your domain’s zone), you paste the token, and the portal adds the TXT record, and if you want, the CNAME, A or AAAA record that points the host at your server, then checks the domain. The token is used once and never stored. Hosts that support the open Domain Connect standard get a Connect button that sends you to the host to confirm the records and back, once the host has enabled our template. Every other host: add the record by hand as above.

Keeping data

Where What for Limits
DeviceStorage Values on this device only; gone when A-chat is deleted. Phone: 1,024 keys, 4,096 characters a value. Web version and desktop app: 5 MB per app.
CloudStorage Values kept by A-chat for this person and this app, on every device, also after A-chat is installed again. 1,024 keys, 4,096 characters a value. Keys of A-Za-z0-9_-.
Your own server Anything bigger, or shared between people. Yours. Check initData first.

localStorage and cookies are on this device only, and on the phone they are one for all the A-chat accounts on it. How to keep everything through a new phone and a second account: Saving without losing anything.

What people see in Settings

Every person has Settings → Mini apps on the phone, in the web version and in the desktop app. It lists the apps they opened, the newest first, and for each one:

After Remove, your app sees an empty CloudStorage for that person. Their rating stays. A bot they started can still write to them until they block it.

Camera, microphone and location

An app gets the camera, the microphone or the location only if it declared them, and only when the person agrees. Each time the page asks, A-chat shows its own question with the app’s name (“Allow Food Tracker to use the camera?”), then the phone’s or the browser’s own question when A-chat does not have that permission yet.

Keeping a secret on the phone

WebApp.SecureStorage keeps up to 10 small values (2,048 characters each) in the phone’s Keychain or Keystore, apart for each app and A-chat account, on this device only. Use it for a session token or a key of your service. The web version and the desktop app answer unsupported: keep another way to sign the person in there.

What works where

Feature iPhone, Android Web version, desktop app
Open from Hub Yes Yes
Open from a bot’s web_app button or menu button Yes, for the linked app’s hosts Yes, for the linked app’s hosts
Signed initData Yes Yes
Theme, viewport, CSS variables Yes Yes (safe areas are 0)
Main, secondary, back and settings buttons Yes Yes
Alerts, confirms, popups Yes Yes
openLink, openAChatLink Yes Yes (allowed links open in a new tab after a question)
Full screen The window’s full screen The browser’s full screen
Header colour Yes Yes
Background colour Yes No
Haptic feedback Yes Ignored
DeviceStorage Yes Yes
sendData Yes Yes
Read the clipboard Yes Yes, as the browser allows
Location Yes, when declared and allowed Yes, when declared and allowed (requestLocation)
Camera, microphone Yes, when declared and allowed No
QR scanner (showScanQrPopup) Yes Yes, with a camera
SecureStorage Yes No
CloudStorage Yes Yes
shareToChat Yes Yes
requestContact, switchInlineQuery Yes Yes
Asking from the page for the right to write (requestWriteAccess) Yes Yes

Every app has its own link: https://a-chat.app/a/<app id> (https://a-chat.app/app/<app id> is the same link). Add ?startapp=<param> (1-64 of A-Z a-z 0-9 _ -) to start the app at a place of yours: the page gets it as start_param in initData. Get the link from the page with WebApp.getShareLink().

Hub has links too: https://a-chat.app/hub, a section https://a-chat.app/hub/games (or /hub/apps), a category https://a-chat.app/hub/tools or https://a-chat.app/hub?category=tools.

Ratings and the place in Hub

A person who opened an app at least twice may rate it with 1 to 5 stars and a short review. The owner cannot rate their own app. Hub orders apps by their rating (weighted toward the middle while there are few votes), the number of people who opened the app in the last 7 days, and a short lift for new apps in their first two weeks. The team chooses the featured apps at the top.

Next