Юзер создаёт QR в приложении X2Chat — внутри сидит одноразовый integration_token. Ваш сайт сканит QR (или копипастит token) → одним POST'ом получает bot_token + chat_id + готовый sendMessage URL. Без копирования длинных секретов руками.
User generates a QR in X2Chat app — it contains a one-time integration_token. Your site scans the QR (or pastes the token) → with one POST you get bot_token + chat_id + ready-to-use sendMessage URL. No copying long secrets by hand.
📌 Два разных QR-flow в X2Chat — не путайте:
📌 Two QR flows in X2Chat — don't mix up:
integration_token (UUIDv4, 122 бита), привязывает к (bot_id, chat_id), TTL по умолчанию 5 мин. Возвращает {token, expires_at, deep_link}.x2chat://bot/integrate?token=<UUID> или просто строку токена.POST /api/v1/integrations/redeem с {token: "<UUID>"}.bot_token (защита от перехвата) и возвращает {bot_token, chat_id, bot_username, api_base, send_message_url, example_curl}.bot_token + chat_id в свою конфигурацию. С этого момента может слать сообщения через POST bot<TOKEN>/sendMessage. Готово — без копипаста и без передачи секретов в clipboard.integration_token (UUIDv4, 122 bits), binds it to (bot_id, chat_id), default TTL 5 min. Returns {token, expires_at, deep_link}.x2chat://bot/integrate?token=<UUID> or just the token string.POST /api/v1/integrations/redeem with {token: "<UUID>"}.bot_token (defense against intercept) and returns {bot_token, chat_id, bot_username, api_base, send_message_url, example_curl}.bot_token + chat_id in its config. From this moment it can send messages via POST bot<TOKEN>/sendMessage. Done — no copy-paste, no clipboard exposure.Без auth — токен сам является авторизацией. Rate-limit: 60/час/IP.
No auth — token itself is authorization. Rate-limit: 60/hour/IP.
POST https://ix.x2chat.com/api/v1/integrations/redeem
Content-Type: application/json
{
"token": "fc6e2368-b677-430d-9f2f-295ce705c9d0"
}
{
"bot_id": "d03bff3b-f789-414c-9f75-097c4ce0495f",
"bot_username": "info_bot",
"bot_token": "52829374815:Ju1X4yonUDb5MAFtgv8hfUoGNXJMo6CNhJb_wGSIa88",
"chat_id": 92,
"api_base": "https://ix.x2chat.com/api/v1",
"send_message_url": "https://ix.x2chat.com/api/v1/bot52829374815:Ju1X4yonUDb5MAFtgv8hfUoGNXJMo6CNhJb_wGSIa88/sendMessage",
"getUpdates_url": "https://ix.x2chat.com/api/v1/bot52829374815:...<skip>/getUpdates",
"example_curl": "curl -X POST '...' -H 'Content-Type: application/json' -d '{\"chat_id\": 92, \"text\": \"Hello\"}'"
}
| Status | Причина | Reason |
|---|---|---|
400 | Невалидный UUID или пустой tokenInvalid UUID or empty token | |
410 | Token уже использован, истёк или отозванToken already redeemed, expired or revoked | |
429 | Rate-limit (60 redeem/hour/IP)Rate-limit (60 redeem/hour/IP) |
<!-- В админке вашего сайта -->
<div id="reader" style="width:300px"></div>
<input id="bot_token" placeholder="bot_token">
<input id="chat_id" placeholder="chat_id">
<script src="https://cdn.jsdelivr.net/npm/html5-qrcode"></script>
<script>
const qr = new Html5Qrcode("reader");
qr.start(
{ facingMode: "environment" },
{ fps: 10, qrbox: { width: 250, height: 250 } },
async (decodedText) => {
qr.stop();
// QR содержит либо UUID, либо deep link x2chat://bot/integrate?token=UUID
let token = decodedText.trim();
const m = token.match(/[?&]token=([0-9a-f-]+)/i);
if (m) token = m[1];
// Redeem
const r = await fetch("https://ix.x2chat.com/api/v1/integrations/redeem", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
});
if (!r.ok) {
alert("Ошибка redeem: " + r.status);
return;
}
const data = await r.json();
document.getElementById("bot_token").value = data.bot_token;
document.getElementById("chat_id").value = data.chat_id;
// Можно автоматически сохранить в БД своего сервиса:
await fetch("/admin/save-bot-credentials", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
bot_id: data.bot_id,
bot_token: data.bot_token,
chat_id: data.chat_id,
}),
});
alert("Бот подключён ✓");
}
);
</script>
// Если у вас нет браузерного scanner'а — юзер вставляет token руками
// в форму, ваш бэкенд делает redeem на server-side:
const resp = await fetch("https://ix.x2chat.com/api/v1/integrations/redeem", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: req.body.token }),
});
const { bot_token, chat_id, send_message_url } = await resp.json();
// Сохранить в DB сайта, привязав к user_id админа
await db.botCredentials.upsert({ user_id, bot_token, chat_id });
# Python equivalent
import requests
token = request.json['token'] # из формы
r = requests.post('https://ix.x2chat.com/api/v1/integrations/redeem',
json={'token': token}, timeout=10)
data = r.json()
db.upsert_bot(user_id, bot_token=data['bot_token'], chat_id=data['chat_id'])
⚠ Auto-rotate важный момент: каждый redeem генерит НОВЫЙ bot_token. Если у вас уже есть другая интеграция этого бота (например, n8n) — она перестанет работать. Это by design: redeem означает «теперь этот сервис — единственный/главный интегратор». Чтобы подключить второй сервис без сброса первого — используйте Webhook QR (обратное направление, secret отдельный на каждое подключение).
Ручной flow: юзер открывает «Мои боты», копирует bot_token (длинная строка), идёт в админку сайта, вставляет, потом запоминает chat_id, идёт обратно в чат, ищет chat_id где-то, вставляет. 5 переключений контекста.
Manual flow: user opens "My Bots", copies bot_token (long string), goes to site admin, pastes, then needs chat_id, goes back to chat, hunts for chat_id, pastes. 5 context switches.
QR flow: один скан → форма заполнена. 1 действие.
QR flow: one scan → form filled. 1 action.
В диалоге QR в X2Chat есть кнопка «Скопировать токен». Юзер копирует UUID и вставляет в форму на сайте — ваш бэкенд делает тот же redeem.
The QR dialog in X2Chat has a "Copy token" button. User copies UUID and pastes into a form on your site — your backend does the same redeem.
Owner-rate-limit: 10 issue/час. Хватает на нормальный onboarding (даже если несколько раз ошибся — обновляешь и сканишь снова).
Owner-rate-limit: 10 issues/hour. Enough for normal onboarding (even if you mis-scanned a couple of times — refresh and scan again).
© X2Chat · Bot API docs · Webhook QR · bots@x2chat.com
© X2Chat · Bot API docs · Webhook QR · bots@x2chat.com