A-chat for developers

Mini app SDK reference

The SDK is the object window.AChat.WebApp. Add it to every page of your mini app:

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

Version of this reference: 1.0 (WebApp.version).

How to make an app and check initData is in Mini apps and Hub.

How calls work

Most methods send a message to the A-chat window and return at once. Methods that wait for an answer take a callback and also return a Promise, or call the callback only.

When a platform does not have a feature yet, the call fails with the error unsupported: the Promise rejects with an Error whose message is "unsupported", and the callback gets the failure as described for each method. Calls that do not wait for an answer (switchInlineQuery, the buttons, the colours…) fail silently.

const app = window.AChat.WebApp;

app.shareToChat('Try this app').then(
  () => console.log('shared'),
  (error) => console.log(error.message), // "unsupported" today
);

Fields

All fields are read-only. They change when the window tells the page something new, and an event fires.

Field Type Description
version String The bridge’s version, "1.3". Check what a version brings with isVersionAtLeast.
platform String ios, android, web, macos, windows, linux; unknown outside A-chat.
initData String The signed launch data. Send it to your server and check it there. Empty when the launch was not signed.
initDataUnsafe Object The same data, unsigned, for drawing only. Never trust it. Its fields may differ between platforms.
colorScheme String light or dark.
themeParams Object The theme’s colours, as #rrggbb. See Theme.
safeAreaInset Object {top, bottom, left, right} in CSS pixels: the device’s notch and home bar. 0 in the web version.
contentSafeAreaInset Object {top, bottom, left, right}: what A-chat’s own controls cover over the page (for example the floating buttons in full screen).
viewportHeight Number The page’s visible height in CSS pixels.
viewportStableHeight Number The same as viewportHeight today.
isExpanded Boolean Always true: the window is always full height.
isFullscreen Boolean The page is in full screen.
isActive Boolean The window is active.
isOrientationLocked Boolean true while the page holds the window’s orientation with lockOrientation(). orientationLockChanged fires when it changes.
isClosingConfirmationEnabled Boolean Set by enableClosingConfirmation().
isVerticalSwipesEnabled Boolean Set by enableVerticalSwipes() / disableVerticalSwipes().
headerColor String or null The last colour passed to setHeaderColor.
backgroundColor String or null The last colour passed to setBackgroundColor.
bottomBarColor String or null The last colour passed to setBottomBarColor.

Methods

ready()

Tells A-chat the page is ready to show. A-chat keeps its loader over the page until then, so the person sees the loader and then the finished first screen, never an empty frame or a screen being built. Call it once the first screen is drawn: after your styles, fonts and saved state (the level, the draft) are in, not at the first line of your script. A page that never calls it is shown 1.2 s after it has loaded.

WebApp.ready();

expand()

Accepted. The window is always full height.

close()

Closes the window. When closing confirmation is on, the person is asked first.

requestFullscreen(), exitFullscreen()

The bar of A-chat goes and the page takes its place; A-chat’s controls become two small floating buttons at the top right, and contentSafeAreaInset.top says how much they cover. On the phone the page covers the whole screen and the status bar is hidden. In the web version and the desktop app the page fills the window, and after a press of the person the browser’s own full screen comes too; the person may leave that with Esc, and isFullscreen follows. fullscreenChanged fires on every change.

To open with no bar from the first frame, turn on Full screen in the app’s declaration: isFullscreen is then true at the start. In the web version the browser’s own full screen still needs requestFullscreen().

lockOrientation(mode), unlockOrientation()

On the phone, the window turns with the phone while the app is open (portrait and landscape, whatever the person’s setting for the rest of A-chat says). The page decides whether it wants that: nothing is fixed in the app.

Laying a page out for landscape

On its side the phone’s window is wide and short: its bar is lower (44 px, the name only), and the page’s own buttons (MainButton, SecondaryButton) sit side by side in a bar that keeps clear of the notch and the home bar. The page must do the same:

hideKeyboard()

Puts the keyboard away: the page’s field being typed in lets go of the focus. Works everywhere.

form.addEventListener('submit', () => WebApp.hideKeyboard());

Coming back to where the person was

The cross puts the window down; it does not end it. On the phone the page stays loaded out of sight, and opening the same app again (from Hub, from a link or a button of a bot) brings the same window up exactly where it was: the board, the form, the scroll. deactivated fires when it is put down and activated when it comes back (isActive says which). While it is put down the page is also told it is hidden, as a browser’s hidden tab is (document.hidden, visibilityState: 'hidden', the visibilitychange event), and its requestAnimationFrame callbacks wait until it comes back, so a game’s drawing loop stops by itself; timers (setInterval) do not stop: stop them on deactivated or visibilitychange.

enableClosingConfirmation(), disableClosingConfirmation()

With it on, closing the window asks the person first. Use it while the person has unsaved work.

enableVerticalSwipes(), disableVerticalSwipes()

Accepted. They set isVerticalSwipesEnabled; the window has no swipe to close today.

setHeaderColor(color), setBackgroundColor(color), setBottomBarColor(color)

color is #rrggbb.

showAlert(message, callback?)

Shows a message with an OK button. callback() is called when it closes.

WebApp.showAlert('Saved', () => console.log('closed'));

showConfirm(message, callback?)

Shows a message with Cancel and OK. callback(ok) gets true for OK.

WebApp.showConfirm('Delete this item?', (ok) => {
  if (ok) deleteItem();
});

showPopup(params, callback?)

Param Type Description
title String Optional. Up to 64 characters.
message String 1 to 256 characters.
buttons Array Optional. Up to 3. Default: one OK button.

A button is {id, type, text}:

type Label
default text
destructive text, drawn as a dangerous action
ok “OK”
close “Close” in the person’s language
cancel “Cancel” in the person’s language

callback(buttonId) gets the id of the pressed button. Then the popupClosed event fires with {button_id}.

WebApp.showPopup(
  {
    title: 'Leave the game?',
    message: 'Your progress will be lost.',
    buttons: [
      { id: 'leave', type: 'destructive', text: 'Leave' },
      { id: 'stay', type: 'cancel' },
    ],
  },
  (id) => {
    if (id === 'leave') WebApp.close();
  },
);

openLink(url, options?)

Opens a link by the window’s rules: the app’s hosts inside the window, A-chat links in the app, tel: and mailto: after the system asks, the app’s outside sites after the person agrees, anything else refused with a short note. See The rules of the window. options is ignored.

openAChatLink(url)

Opens an A-chat link (a-chat://... or https://a-chat.app/...). The same rules as openLink.

sendData(data)

Sends a string (up to 4,096 bytes; longer is cut) to the bot linked to the app, as web_app_data, and closes the window. Nothing reaches a bot when the app has no linked bot or the person has not started it. See sendData and web_app_data.

WebApp.sendData(JSON.stringify({ order: 42 }));

requestLocation(callback?)

Asks the person for the location once, for an app that declared location. On the phone A-chat asks, then the phone. Since 1.3 also in the web version and the desktop app: A-chat asks first, then the browser (or, in the desktop app, Windows or macOS, whose location service must be on). Your page itself never gets the browser’s location: A-chat reads it and passes only {latitude, longitude, accuracy}.

callback(ok, location): ok is true and location is {latitude, longitude, accuracy} when allowed and found; ok is false when refused, not found or unsupported.

WebApp.requestLocation((ok, place) => {
  if (ok) showNearby(place.latitude, place.longitude);
});

On the phone navigator.geolocation works too, with the same questions. In the web version and the desktop app it is not available to your page: use requestLocation.

readTextFromClipboard(callback?)

callback(text) gets the clipboard’s text, or null when it fails. On the phone the app reads it while the person is in the window. In the web version and the desktop app the browser reads it, and may ask the person first.

showScanQrPopup(params, callback?)

Since 1.3. Opens A-chat’s QR scanner over the window: the back camera on the phone, the computer’s camera in the web version and the desktop app. The camera is asked for the first time it is used. Your page gets only the text of each code read, never the picture; on the computer the code is read inside A-chat’s page, nothing is sent anywhere.

Param Type Description
text String Optional. Up to 64 characters shown under the frame. Default: “Point the camera at a QR code” in the person’s language.

callback(text) is called for every code read. Return true to close the scanner; return anything else to keep it open for the next code. The same code is passed again only after 2 s. Every code also fires qrTextReceived with {data}.

WebApp.showScanQrPopup({ text: 'Scan the table code' }, (text) => {
  if (!text.startsWith('table:')) return false; // not ours: keep scanning
  openTable(text.slice(6));
  return true; // close
});

When the person closes the scanner, scanQrPopupClosed fires.

closeScanQrPopup()

Since 1.3. Closes the scanner. scanQrPopupClosed does not fire for it.

requestContact(callback?)

Asks the person to share their contact with the bot linked to the app. After their yes, their contact card goes to that bot as their own message in their chat with it. The bot gets a message with contact: user_id, first_name and username. A phone number is never shared.

callback(ok, result): ok is true and result is {status: "sent"} when the card was sent. ok is false when the person said no, when the app has no linked bot that may write to them (they have not started it and have not allowed the app to write), or after 5 requests in a minute.

WebApp.requestContact((ok) => {
  if (ok) showNote('Thanks! We will write to you in A-chat.');
});

requestWriteAccess(callback?)

Asks the person whether the bot linked to the app may write to them. Their answer is kept: the bot may then send them messages, and the check API’s sendMessage reaches them. They can take it back in Settings → Mini apps.

callback(ok): true when they allowed it.

Opens a picker of the person’s chats. The text and the link (on a line of its own) go as their message to the chats they pick. Up to 4,096 characters.

Returns a Promise: true once the picker opened (the phone app) or a chat was picked (the web version and the desktop app), false when the person closed it without a chat.

await WebApp.shareToChat('My score: 420', 'https://a-chat.app/a/yourgame');

getShareLink(startParam?)

Since 1.2. The app’s own link, to share anywhere: https://a-chat.app/a/<app id>, and with a startParam (1-64 of A-Z a-z 0-9 _ -) https://a-chat.app/a/<app id>?startapp=<startParam>. The app opened from it gets the parameter as start_param in initData. An empty string when the app has no link (a game of a bot). A startParam of other characters throws.

const link = WebApp.getShareLink('room_42');
await WebApp.shareToChat('Join my room', link);

switchInlineQuery(query, types?)

Puts @yourbot query in the field of a chat, which asks the bot linked to the app in inline mode there. The bot needs inline mode on. The window closes.

Nothing happens when the app has no linked bot.

isVersionAtLeast(version)

true when WebApp.version is the same or newer.

if (WebApp.isVersionAtLeast('1.0')) {
  // ...
}

onEvent(name, handler), offEvent(name, handler)

Add and remove an event handler. Inside the handler, this is WebApp.

Buttons

MainButton and SecondaryButton

Buttons at the bottom of the window, drawn by A-chat. MainButton defaults to the text “Continue”, SecondaryButton to “Cancel”. Both start hidden.

Field Type Description
text String Up to 64 characters.
color String #rrggbb.
textColor String #rrggbb.
isVisible Boolean
isActive Boolean
isProgressVisible Boolean
position String MainButton: top; SecondaryButton: bottom.
Method Description
setText(text) Set the text.
show(), hide() Show or hide.
enable(), disable() Make it pressable or not.
showProgress(), hideProgress() Show or hide a spinner.
setParams({text, color, text_color, is_visible, is_active, position}) Set several at once.
onClick(handler), offClick(handler) Listen to presses (mainButtonClicked / secondaryButtonClicked).

Every method returns the button, so calls can be chained:

WebApp.MainButton.setText('Pay 4.99').show().onClick(pay);

BackButton

A back arrow in place of the window’s close button.

Member Description
isVisible Boolean.
show(), hide()
onClick(handler), offClick(handler) backButtonClicked.

While it is shown, the window’s back control (and Android’s Back) sends backButtonClicked instead of closing.

SettingsButton

Adds “Settings” to the window’s menu.

Member Description
isVisible Boolean.
show(), hide()
onClick(handler), offClick(handler) settingsButtonClicked.

HapticFeedback

Phone only; ignored elsewhere. Each method returns HapticFeedback.

Method Values
impactOccurred(style) light, medium, heavy, rigid, soft
notificationOccurred(type) success, warning, error
selectionChanged()

Haptics follow the person’s own setting in A-chat.

Storage

DeviceStorage

Values kept on this device, for this app. In the web version and the desktop app they are kept per account and app. To keep values on every device of the person, use CloudStorage.

Method Promise result
setItem(key, value, callback?) true
getItem(key, callback?) The value, or null.
getItems(keys, callback?) {key: value or null}
removeItem(key, callback?) true
removeItems(keys, callback?) true
getKeys(callback?) Array of keys.
clear(callback?) true

callback(error, result): error is null on success.

Limits: keys 1 to 128 characters; values are strings. On the phone, up to 1,024 keys and 4,096 characters a value. In the web version and the desktop app, up to 5 MB per app in all.

await WebApp.DeviceStorage.setItem('level', '3');
const level = await WebApp.DeviceStorage.getItem('level');

“Clear cookies and data” in the window’s menu removes it. On the phone it goes with A-chat when the person deletes it, and it is one for all the A-chat accounts of the phone: put the person’s id (initDataUnsafe.user.id) in the key.

CloudStorage

Values kept by A-chat for this person and this app. They follow the person to every device: the phone, the web version and the desktop app.

Method Promise result
setItem(key, value, callback?) true
getItem(key, callback?) The value, or "" when the key is not there.
getItems(keys, callback?) {key: value}, with "" for keys that are not there.
removeItem(key, callback?) true
removeItems(keys, callback?) true
getKeys(callback?) Array of keys, sorted.
clear(callback?) true

callback(error, result): error is null on success.

Limit
Key 1 to 128 of A-Z, a-z, 0-9, _ and -. Other keys fail with bad_key.
Value A string of up to 4,096 characters. Longer fails with bad_value.
Keys per person and app 1,024. A setItem over that fails.
Keys in one getItems or removeItems 100.
const store = WebApp.CloudStorage;

await store.setItem('level', '3');
const level = await store.getItem('level'); // "3"
const all = await store.getItems(['level', 'coins']); // { level: "3", coins: "" }

Values are kept on A-chat’s server, encrypted at rest (AES-256-GCM, each value sealed for its app and person). That protects a copy of the database, not more: A-chat’s server reads them to give them back, and they are not end-to-end encrypted. Do not keep secrets there (passwords, keys, tokens, payment details). Keys are not encrypted: do not put anything private in a key. When the person removes the app in Settings → Mini apps, its CloudStorage for them is deleted. See What people see in Settings.

A game opened by Play in a chat has no CloudStorage: the calls fail there. Keep its scores with setGameScore.

Saving without losing anything

A person deletes A-chat and installs it again, signs in on a new phone, or has two accounts on one phone. What lives through it:

Kept in New phone, A-chat installed again Another account on the same phone
CloudStorage, your own server Is there Has its own
localStorage, cookies, IndexedDB Gone The same one
DeviceStorage Gone The same one on the phone; its own in the web version and the desktop app
SecureStorage Gone Has its own

So a page that should lose nothing:

const me = WebApp.initDataUnsafe.user.id;
const local = `${me}/game_best`;
let best = Number(localStorage.getItem(local)) || 0;
let cloudRead = false;

async function load() {
  const cloud = Number(await WebApp.CloudStorage.getItem('game_best')) || 0;
  cloudRead = true;
  if (best > cloud) await WebApp.CloudStorage.setItem('game_best', String(best));
  else best = cloud;
}

async function save(score) {
  if (score <= best) return;
  best = score;
  localStorage.setItem(local, String(best));
  if (cloudRead) await WebApp.CloudStorage.setItem('game_best', String(best));
}

SecureStorage

Since 1.3. A few small values kept in the phone’s own protected store: the Keychain on iPhone, the Keystore on Android. Use it for what must not leave the device unprotected: a session token of your service, a key. Kept apart for each app and each A-chat account on the phone, on this device only (never in a backup, never moved to another phone), and read only while the phone is unlocked.

Method Promise result
setItem(key, value, callback?) true
getItem(key, callback?) The value, or null.
removeItem(key, callback?) true
getKeys(callback?) Array of keys, sorted.
clear(callback?) true

callback(error, result): error is null on success.

Limit
Key 1 to 64 of A-Z, a-z, 0-9, _ and -. Other keys fail with invalid.
Value A string of up to 2,048 characters. Longer fails with invalid.
Keys per account and app 10. A new key over that fails with too_many_keys.
try {
  await WebApp.SecureStorage.setItem('session', token);
} catch (error) {
  // "unsupported": the web version or the desktop app. Sign the person in again there.
}

Phone only: in the web version and the desktop app every call fails with unsupported, so keep a way to work without it. “Clear cookies and data” in the window’s menu, and removing the app in Settings → Mini apps, remove it.

Events

Event Data When
themeChanged colorScheme or themeParams changed.
viewportChanged {isStateStable} viewportHeight or isExpanded changed.
safeAreaChanged safeAreaInset changed.
contentSafeAreaChanged contentSafeAreaInset changed.
fullscreenChanged isFullscreen changed.
orientationLockChanged isOrientationLocked changed.
activated, deactivated isActive changed.
mainButtonClicked The main button was pressed.
secondaryButtonClicked The secondary button was pressed.
backButtonClicked The back button was pressed.
settingsButtonClicked “Settings” was chosen in the menu.
popupClosed {button_id} A showPopup popup closed.
qrTextReceived {data} The QR scanner read a code: data is its text.
scanQrPopupClosed The person closed the QR scanner.
WebApp.onEvent('themeChanged', function () {
  document.body.style.background = this.themeParams.bg_color;
});

Theme

themeParams

Key Use
bg_color The page’s background.
secondary_bg_color A second background (grouped lists).
section_bg_color A section’s background.
header_bg_color The bar’s background.
text_color Text.
hint_color Quiet text.
link_color Links.
button_color A button’s background.
button_text_color A button’s text.
accent_color The accent.
destructive_color Dangerous actions.
separator_color Lines between rows.

CSS variables

The SDK sets these on <html> and keeps them up to date:

Variable From
--achat-bg bg_color
--achat-secondary-bg secondary_bg_color
--achat-section-bg section_bg_color
--achat-header-bg header_bg_color
--achat-text text_color
--achat-hint hint_color
--achat-link link_color
--achat-button button_color
--achat-button-text button_text_color
--achat-accent accent_color
--achat-destructive destructive_color
--achat-separator separator_color
--achat-viewport-height viewportHeight
--achat-viewport-stable-height viewportStableHeight
--achat-safe-area-inset-top, -bottom, -left, -right safeAreaInset
--achat-content-safe-area-inset-top, -bottom, -left, -right contentSafeAreaInset

It also sets data-achat-color-scheme="light" or "dark" and data-achat-fullscreen="true" or "false" on <html>.

body {
  background: var(--achat-bg, #fff);
  color: var(--achat-text, #000);
  padding-top: var(--achat-content-safe-area-inset-top, 0px);
  padding-bottom: var(--achat-safe-area-inset-bottom, 0px);
}

a {
  color: var(--achat-link);
}

[data-achat-color-scheme='dark'] img.logo {
  filter: invert(1);
}

Your server

The SDK runs in the page. What needs the app’s key runs on your server:

What How
Check initData By hand with the app’s key, or the check API’s checkInitData. See Who opened the app.
Write to a person The check API’s sendMessage, through the linked bot, to people who started it.
The app’s numbers The check API’s getStats: launches, people, rating.
Answer a launch in the bot’s chat The linked bot’s answerWebAppQuery with query_id of initData.

The check API is https://api.a-chat.app/miniapp<app key>/<method>. Its methods and examples are in The check API for your server.

// In the page: send initData to your server, never the key to the page.
await fetch('/api/start', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ initData: WebApp.initData }),
});

What answers unsupported today

Call Phone Web version, desktop app
CloudStorage.* works works
shareToChat works works
getShareLink works works
requestContact works works
requestWriteAccess works works
switchInlineQuery works works
requestLocation works when declared works when declared (since 1.3)
showScanQrPopup, closeScanQrPopup works works where the computer has a camera (since 1.3)
SecureStorage.* works unsupported
readTextFromClipboard works works where the browser allows it (it may ask the person)
Camera, microphone, navigator.geolocation in your page work when declared not available (the place: requestLocation)
HapticFeedback works ignored
lockOrientation, unlockOrientation works a phone’s browser in full screen; elsewhere accepted, no effect
hideKeyboard works works
The window kept loaded when put down; activated / deactivated works not kept
enableVerticalSwipes, setBottomBarColor accepted, no effect accepted, no effect

Outside A-chat (a page opened in a normal browser) the SDK has platform: "unknown", an empty initData, and its calls go nowhere.