Log in with A-chat
Let people sign in to your site with their A-chat account. There are two ways, and you can use both:
- The widget: a button on your page. The person confirms in A-chat, and your page gets their signed fields.
- OAuth 2.0 / OpenID Connect: the standard authorization code flow with PKCE. Your server gets an ID token and an access token.
The person’s id is the same number your bot sees in its updates and your mini app sees in initData. You can recognise one person on your site, in your bot and in your mini app. With the extra write, your site’s bot may also write to them.
What your site gets
Always (the button says so):
| Field (widget) | Claim (OpenID) | What it is |
|---|---|---|
id |
sub |
The person’s number (a string in the JWT). |
first_name |
name |
The name of their profile. |
username |
preferred_username |
Their @name, when they have one. |
photo_url |
picture |
A link to a small copy of their picture. It works for an hour: keep your own copy. Absent when they show their picture to nobody. |
language_code |
locale |
The language of their app. |
Only when you ask for it and the person leaves it on in the consent screen:
| Field | Scope | What it is |
|---|---|---|
bio |
bio |
The “About” of their profile. |
allows_write_to_pm |
write |
true: your site’s bot may write to the person. See The bot may write. |
Never: the phone number, the e-mail, chats, contacts. Scopes asking for them are dropped.
Register your site
On the developer portal: Log in with A-chat → New site. Or in the A-chat app: Settings → For developers → Sites → New site; the web version (web.a-chat.app) and the desktop app have it too.
The portal also lets you verify each domain of the site (a TXT record _achat-login.<host> with achat-login=<token>, or the file /.well-known/achat-login.json), by hand or through Cloudflare, and shows the addresses your OAuth library needs. Sign-in does not require a verified domain, unless the A-chat team makes it required (for every site or for yours): then sign-ins from a domain that is not verified are refused with domain_unverified (localhost always works).
- Name: 1-64 characters, shown on the consent screen.
- Domains: 1-10 host names without a scheme, port or path (
example.com,www.example.com).localhostis allowed for trying it out. - Return addresses (OAuth only): up to 10
httpsaddresses on those domains (httponly onlocalhost). They are compared exactly. The widget does not need them. - Bot (optional): one of your bots, shown on the consent screen. A site needs one to ask for
write.
You get:
client_id: the site’s number.- The secret: it is shown whole when the site is made and when you replace it. After that it is masked, and Show asks for your cloud password if you have one. Keep it on your server only. Replace makes a new one, and the old one stops at once.
Up to 20 sites per account.
The widget
Put the script where the button should be:
<script async src="https://a-chat.app/login/widget.js"
data-client-id="7000000123"
data-onauth="onAChatAuth(user)"
data-request-access="bio write"></script>
<script>
function onAChatAuth(user) {
if (!user) return; // the person cancelled
fetch('/auth/a-chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(user) });
}
</script>
| Attribute | Meaning |
|---|---|
data-client-id |
Your site’s client_id. Required. |
data-onauth |
A function called with the fields, or false when the person cancelled. A bare name (onAChatAuth) also works. |
data-auth-url |
Instead of a function: the page goes to this address with the fields in the query. |
data-request-access |
The extras to ask for, separated by spaces: bio, write, or bio write. |
data-mode |
popup (default) or redirect. |
data-size, data-radius, data-lang |
The button’s size, corner radius and language (11 languages). |
From your own code: window.AChatLogin.auth({ clientId, scope, mode, authUrl }, done). scope is the same list as data-request-access.
The fields: id, first_name, username?, photo_url?, language_code?, bio?, allows_write_to_pm?, auth_date, hash. allows_write_to_pm is the string "true" when the person allowed write, and is absent otherwise. It is signed with the rest: keep it in the check.
Check the fields on your server
Never trust the fields without this check, made with your site’s secret:
data_check_string = every field except hash, as "key=value", sorted by key, joined by "\n"
secret_key = SHA256(<site secret>)
hash = hex(HMAC_SHA256(secret_key, data_check_string))
Also check that auth_date is fresh (a day at most, or less: you decide).
Node.js:
import crypto from 'node:crypto';
export function checkAChatLogin(fields, siteSecret, maxAgeSeconds = 86400) {
const { hash, ...rest } = fields;
const dataCheckString = Object.keys(rest)
.sort()
.map((key) => `${key}=${rest[key]}`)
.join('\n');
const secretKey = crypto.createHash('sha256').update(siteSecret).digest();
const expected = crypto.createHmac('sha256', secretKey).update(dataCheckString).digest('hex');
if (!hash || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(String(hash)))) return false;
return Date.now() / 1000 - Number(rest.auth_date) <= maxAgeSeconds;
}
Python:
import hashlib, hmac, time
def check_achat_login(fields: dict, site_secret: str, max_age: int = 86400) -> bool:
rest = {k: v for k, v in fields.items() if k != "hash"}
data_check_string = "\n".join(f"{k}={rest[k]}" for k in sorted(rest))
secret_key = hashlib.sha256(site_secret.encode()).digest()
expected = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, str(fields.get("hash", ""))):
return False
return time.time() - int(rest.get("auth_date", 0)) <= max_age
A working example page with both checks: a-chat.app/login/example.html.
OAuth 2.0 and OpenID Connect
Discovery: https://api.a-chat.app/api/login/.well-known/openid-configuration. The issuer is https://api.a-chat.app/api/login.
1. Send the person to the consent page
https://web.a-chat.app/oauth/authorize
?response_type=code
&client_id=7000000123
&redirect_uri=https%3A%2F%2Fexample.com%2Fauth%2Fa-chat
&scope=openid%20profile
&state=<random>
&code_challenge=<BASE64URL(SHA256(code_verifier))>
&code_challenge_method=S256
&nonce=<random>
PKCE with S256 is required. redirect_uri must be one of your return addresses exactly. Add bio and write to scope to ask for the extras.
If the request is wrong (unknown client, a return address that is not yours, no PKCE), the page says so and sends nothing to your address. A person who is not signed in can sign in on the page or scan a QR code with the A-chat app.
2. Get the answer
The person comes back to redirect_uri?code=…&state=…&iss=…, or ?error=access_denied&state=…&iss=… when they cancelled. Check state. The code lives 5 minutes and works once.
3. Exchange the code
POST https://api.a-chat.app/api/login/token, as a form or JSON. Authenticate with HTTP Basic (client_id:client_secret) or client_id and client_secret in the body.
| Field | Value |
|---|---|
grant_type |
authorization_code |
code |
The code you got. |
redirect_uri |
The same address as in step 1. |
code_verifier |
43-128 characters, the one behind your code_challenge. |
{
"access_token": "acl_…",
"token_type": "Bearer",
"expires_in": 3600,
"scope": "openid profile",
"id_token": "<JWT>"
}
scope lists what the person allowed, for example openid profile write. There are no refresh tokens: keep your own session. Errors follow RFC 6749: invalid_client (401), invalid_grant, invalid_request, unsupported_grant_type, unauthorized_client (a frozen site), temporarily_unavailable (503).
4. Check the ID token
A JWT signed with ES256. The header carries kid. The keys are at https://api.a-chat.app/api/login/jwks.
Claims: iss, sub (the person’s number), aud and azp (your client_id), iat, exp (an hour), auth_time, nonce, name, preferred_username, picture, locale, bio (when allowed), allows_write_to_pm (true, when write was allowed).
Check the signature with the key of the kid, then that iss is https://api.a-chat.app/api/login, aud is your client_id, exp has not passed, and nonce is the one you sent. Any OpenID Connect library does this from the discovery address.
userinfo and revoke
GETorPOST https://api.a-chat.app/api/login/userinfowithAuthorization: Bearer <access_token>returns{sub, name, preferred_username?, picture?, locale?, bio?, allows_write_to_pm?}. The fields are current: a changed name shows. It answers 401invalid_tokenonce the person revoked the site, the site was frozen, or the token expired.POST https://api.a-chat.app/api/login/revokewithtoken(RFC 7009) ends a token.
The bot may write
A bot never writes first. With write, a person who signs in to your site lets your site’s bot write to them.
Ask for it: data-request-access="write" in the widget, or write in the OAuth scope.
- It is offered only when the site has a bot and the bot is active. Otherwise
writeis dropped from the request. - The consent screen says “Allow @yourbot to message you”, with a switch. The person can turn it off and still sign in.
When the person allows it and has not started the bot yet, A-chat opens their chat with the bot and puts a /start from them in it, as the Start button does. So:
- your bot gets an ordinary
messageupdate with/startfrom that person; - from then on the bot may write to them, by the usual rules of the Bot API;
- the person’s
idon your site is the same number aschat.idin your bot’s updates.
A person who started the bot before gets nothing new. When it cannot be done, for example because the person blocked the bot, the sign-in goes on without write.
What your site gets: allows_write_to_pm = "true" in the widget’s fields, and allows_write_to_pm: true in the ID token and in userinfo. Without it, do not count on the bot being able to write: a send may answer 403.
// After the check of the widget's fields on your server:
if (fields.allows_write_to_pm === 'true') {
await fetch(`https://api.a-chat.app/bot${process.env.BOT_TOKEN}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: Number(fields.id), text: 'Welcome! You will get your order updates here.' }),
});
}
Revoking the site does not stop the bot. To stop it, the person blocks the bot.
When access ends
A person can see every site they signed in to and revoke it (Settings → Sites in the app). Its tokens stop at once. The same happens when you delete the site, or when the team freezes it.
Limits
Per IP address, per minute: starting a sign-in 60, polling 240, /token 300, /revoke 120. Per site: 600 requests a minute.
Not available yet: refresh tokens.