# KA BOT API — complete integration spec > Redeem PUBG Mobile UC codes onto a player ID over HTTPS, from your own bot or backend. > This one file is the whole contract, written for AI coding agents. Human docs: https://ka-bot-docs.pages.dev - API contract version: `2026-09-12` (sent in the `KA-Version` response header) - Spec updated: 2026-11-12 - Support: Telegram @Nogitsuneiii — quote the `X-Request-Id` / `request_id` ## 1. Rules — an integration MUST follow all of them 1. **Server-side only.** Read the key from an environment variable (e.g. `KA_API_KEY`). Never put it in frontend code, a mobile app, a URL or logs. 2. **`Idempotency-Key` on every `POST /v1/redeem`** = your order id. Persist it before the first call and reuse the SAME value on every retry of that order. A new value only for a genuinely new attempt. 3. **Exactly one code source** per redeem: `codes` OR `uc` OR `categories` OR `packs` (or the `denomination` + `quantity` shorthand). 4. **Decide per code, not per request.** Both `200` and `422` carry `codes[]`; act on each entry's `status`. 5. **Branch on `error_code`** (stable strings). `message` is for your logs only — never show raw API text or bodies to end customers. 6. **Retry only timeouts, `429` and `5xx`** — same `Idempotency-Key`, exponential backoff, honour `Retry-After`. Never resend a `4xx` unchanged. Exception: `job_interrupted` → new attempt with a NEW key. 7. **Store `request_id`** (and `job_id` for async) on the order. 8. **Expect new values.** Unknown `error_code` / `status` values may appear: treat them as a generic failure, log, never crash. 9. **`sk_test_` keys are NOT a sandbox** — they redeem real codes and spend real quota. 10. **Long timeouts.** Most sync redeems finish in 3 to 5 seconds. Rare cases can take up to 3 minutes. Set the client timeout to 5 minutes (300 s). Use 10 minutes (600 s) as a buffer for a bad connection or a sudden update on our side. A timeout is not a failed order — retry with the same Idempotency-Key, or send `"async": true`. ## 2. Basics | Item | Value | |---|---| | Base URL | `https://api.kabotapi.com` | | Auth header | `Authorization: Bearer ` (alternative: `X-API-Key: `) | | Live key | `pk_` + 32 hex chars (35 chars) | | Test key | `sk_test_` + 32 hex chars — not a sandbox | | Get a key | Telegram bot → `/api_system` → View token → Generate token. Shown once; generating a new one disables the old one at once | | Scopes | `redeem`: `POST /v1/redeem` · `read`: `GET /v1/me`, `GET /v1/stock`, `GET /v1/jobs/{id}`, `POST /v1/webhook` | | Request body | JSON (`Content-Type: application/json`), max 256 KB | | Every response | JSON with `"ok": true` or `false`; headers `X-Request-Id`, `KA-Version` | | Stock codes (source B) | Added in the Telegram bot with `/addcodes` (or bought there) | | Wallet top-up | Telegram bot → `/wallet` | Keys can be IP-restricted. ## 3. Endpoints | Call | Scope | Purpose | Cost | |---|---|---|---| | `GET /v1/health` | none | Liveness: `{"ok": true, "version": "2026-09-12"}` | free | | `GET /v1/me` | read | Plan, quota, wallet, subscription — use it as the smoke test | free | | `GET /v1/stock` | read | Your codes held by KA BOT, per pack | free | | `GET /v1/jobs/{job_id}` | read | Async job state and result | free | | `POST /v1/webhook` | read | Register or replace your callback URL | free | | `POST /v1/redeem` | redeem | Activate codes on a player | 1 request per billable code | ### GET /v1/me ```json { "ok": true, "customer_id": 123456789, "key_prefix": "pk_0123", "scopes": ["redeem", "read"], "mode": "live", "plan": "assigned-label", "plan_active": true, "billing": "plan", "quota": { "mode": "plan", "daily_limit": 3000, "used_today": 12, "remaining_today": 2988, "overage_today": 0 }, "free_credit": { "active": false, "limit": 300, "remaining": null, "used": null, "window_sec": 86400, "next_restore_at": null }, "per_request_usd": 0.0, "balance_usd": 25.0, "subscription": { "active": true, "required": false, "expires_at": null, "days_left": null } } ``` - `mode`: `live` | `test` (from the key prefix). - `billing`: `plan` (an assigned plan is active) | `free_credit` (no plan; rolling free credit) | `none` (redeem returns `402 no_plan`). - Free-credit accounts: `plan` is `"Free credit"`, and `quota` is `{ "mode": "free_credit", "limit", "remaining", "used", "window_sec", "next_restore_at", … }`. - `quota.daily_limit: null` means no daily cap. Daily counters reset at 00:00 UTC. - `subscription.required: false` → ignore `active` / `days_left`; `402 subscription_expired` is never returned. Only when `required` is `true` does a lapsed bot subscription block the API. ### GET /v1/stock ```json { "ok": true, "by_category": { "60": 12, "325": 4 }, "total": 16 } ``` `by_category` keys are your pack labels (UC amounts), usable in `categories` and `packs`. ### POST /v1/redeem Headers: `Authorization`, `Content-Type: application/json`, `Idempotency-Key` (required — missing → `400 idempotency_required`, nothing spent). Body: `player_id` plus exactly one code source. | Field | Type | Rule | |---|---|---| | `player_id` | string | PUBG Mobile player ID, digits only, 5–24 chars; otherwise `400 bad_player` | | `codes` | string[] | **Source A — your own codes.** Max 50. Malformed → `400 bad_codes` with up to 5 samples in `invalid` | | `uc` | integer | **Source B — KA BOT stock.** UC total; we pick packs from your stock. No combination → `400 no_combo` | | `categories` | string[] | Source B — explicit pack labels, e.g. `["60", "60"]` | | `packs` | object[] | Source B — `[{"denomination": 60, "quantity": 2}]`; quantity 1–50, max 50 codes in total; invalid → `400 bad_packs` | | `denomination` + `quantity` | integer + integer | Shorthand for a single `packs` entry | | `async` | boolean | Optional. `true` → `202` with a `job_id` (see Async jobs) | No source → `400 empty`. More than one → `400 ambiguous_source`. Not enough stock → `409 no_stock` (body carries `needed` and your current `by_category`; nothing billed). ```json { "player_id": "5123456789", "codes": ["ABCDEFGHJK12345678"] } { "player_id": "5123456789", "uc": 120 } { "player_id": "5123456789", "packs": [{ "denomination": 60, "quantity": 2 }], "async": true } ``` Response: `200` when at least one code activated, `422` when none did — same shape. Always read `codes[]`. ```json { "ok": true, "player_id": "5123456789", "player_name": "PlayerOne", "requested": 2, "activated": 1, "failed": 1, "took_ms": 4130, "source": "stock", "codes": [ { "code": "AB12C…", "category": "60", "status": "activated", "disposition": "consumed", "billed": true }, { "code": "AB12C…", "category": "60", "status": "failed", "disposition": "returned", "billed": false, "error_code": "ACTIVATION_FAILED", "message": "Temporary issue. Retry later." } ], "billed_requests": 1, "refunded_requests": 1, "request_id": "req_9f2c…" } ``` - `ok`: `true` when at least one code activated. - `source`: `external` (you sent `codes`) | `stock` (KA BOT inventory). - `player_name`: the in-game nickname (may be `null`) — show the customer who was topped up. - `category`: stock codes only. `refunded_requests`: present only when above 0. Per-code `status` — what happened to the activation: | status | error_code | Billed | Your bot should | Tell the customer | |---|---|---|---|---| | `activated` | — | yes | Mark the order delivered | "Done — UC delivered" | | `code_used` | `CODE_USED` | yes | Final. Do not retry; the code is spent | "Code already used" | | `invalid_code` | `INVALID_CODE` | yes | Final. Do not retry; drop the code | "Code invalid" | | `bad_player` | `CHARACTER_NOT_FOUND` | no (refunded) | Ask for the correct player ID, then a new request | "Player ID not found" | | `failed` | `ACTIVATION_FAILED` | no (refunded) | Temporary issue on our side. Retry later with a NEW Idempotency-Key | "Temporary issue — we'll retry" | Per-code `disposition` — what happened to the code itself: | disposition | Meaning | |---|---| | `consumed` | Spent successfully (`activated`) | | `deleted` | Proven spent or dead (`code_used` / `invalid_code`). Stock codes are removed so they are never re-issued | | `returned` | Stock code confirmed still valid and put back in your KA BOT stock (`failed` / `bad_player`) | | `unchanged` | Your own code (source A) that was not spent (`failed` / `bad_player`) — we hold no copy | Source A (`codes`): we hold no copy, so your own records are yours to update — decide refund / keep / retry from `status`. ### Async jobs `"async": true` answers in milliseconds with `202`: ```json { "ok": true, "job_id": "job_46c8…", "state": "queued", "player_id": "5123456789", "requested": 2, "poll_url": "/v1/jobs/job_46c8…", "request_id": "req_…" } ``` `GET /v1/jobs/{job_id}`: ```json { "ok": true, "job_id": "job_46c8…", "state": "done", "created_at": 1789000000, "updated_at": 1789000042, "result": { "…": "same body as a sync redeem, plus job_id" } } ``` - `state`: `queued` → `running` → `done` | `failed`. - `done`: `result` is the sync redeem body (read `result.codes[]`). - `failed`: `result` is an error body — `internal` (requests refunded) or `job_interrupted` (interrupted on our side; unused stock and quota restored → start a new attempt with a NEW Idempotency-Key). - Unknown job id → `404 not_found`. - Poll with backoff (1.5 s growing to 10 s) and give up after ~5 minutes — or take a webhook and keep polling as the fallback. ### Idempotency | Situation | You get | |---|---| | Retry after a timeout — same key, same body | The original response replayed, with header `KA-Idempotent-Replay: true`. No second activation, not billed again | | Same key while the first call is still running | `409 idempotency_in_progress` (may include `job_id`) — wait, then retry or poll | | Same key, different body | `422 idempotency_conflict` | | Our side answered `5xx` | The key is released, so a retry with the same key runs cleanly | Keys are remembered for 24 hours per account. Body comparison ignores JSON key order. ### POST /v1/webhook ```json // request { "url": "https://shop.example.com/hooks/ka-bot" } // response { "ok": true, "url": "https://shop.example.com/hooks/ka-bot", "secret": "whsec_…", "note": "Shown once. …" } ``` - `secret` is shown once. Registering again replaces the URL and rotates the secret. There is no GET. - The URL must be a public `https://` endpoint, else `400 https_required` / `400 webhook_url_blocked` (no localhost or private IPs). Deliveries are `POST` with a JSON body: ```json { "event": "redeem.completed", "created_at": 1789000042, "data": { "ok": true, "job_id": "job_46c8…", "codes": [] } } ``` | event | Fires when | `data` | |---|---|---| | `redeem.completed` | Any redeem finished, sync or async — even if every code failed | The full redeem body | | `redeem.failed` | An async job could not finish on our side; requests refunded | Error body plus `job_id` | - Headers: `KA-Event: `, `KA-Signature: t=,v1=`. - `v1` = hex `HMAC-SHA256(secret, "." + raw_body)`. Use the raw request bytes, compare in constant time, reject `|now − t| > 300 s`. - Up to 3 attempts, then dropped. Answer `2xx` quickly and do slow work after. Process each `request_id` / `job_id` once. Delivery is best-effort — keep `GET /v1/jobs/{id}` as the fallback. ```python import hashlib, hmac, time def verify(secret: str, raw_body: bytes, header: str, tolerance: int = 300) -> bool: parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p) ts, sig = parts.get("t", ""), parts.get("v1", "") if not ts.isdigit() or abs(time.time() - int(ts)) > tolerance: return False expected = hmac.new(secret.encode(), f"{ts}.".encode() + raw_body, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, sig) ``` ## 4. Errors Every error, at any status: `{"ok": false, "error_code": "bad_player", "message": "player_id must be digits."}`. Some add fields: `retry_after_sec`, `invalid`, `needed`, `by_category`, `job_id`, `subscription_expired_at`, `free_credit`, `next_restore_at`. | error_code | HTTP | Retry? | Action | |---|---|---|---| | `unauthorized`, `revoked`, `expired` | 401 | no | Fix or replace the key | | `ip_denied`, `scope_denied`, `unknown_customer` | 403 | no | Key lacks the IP allowance or scope | | `subscription_expired` | 402 | no | Only when `subscription.required` is true: renew the bot subscription | | `no_plan` | 402 | no | No API plan and no free credit — contact support | | `insufficient_funds` | 402 | no | Top up the wallet (`/wallet`), then retry | | `bad_request`, `bad_player`, `bad_codes`, `bad_packs`, `no_combo`, `empty`, `ambiguous_source`, `idempotency_required`, `https_required`, `webhook_url_blocked` | 400 | no | Fix the request | | `not_found` | 404 | no | Unknown path or job id | | `no_stock` | 409 | no | Add stock or switch to source A. Nothing billed | | `idempotency_in_progress` | 409 | wait | Identical request still running — wait, then retry the same key or poll | | `idempotency_conflict` | 422 | no | Same key, different body — a new order needs a new key | | `payload_too_large` | 413 | no | Body over 256 KB — send fewer codes | | `quota_exceeded`, `rate_limited` | 429 | yes | Wait `Retry-After` seconds, same key | | `unavailable` | 503 | yes | Retry with backoff, same key | | `internal` | 500 | yes | Retry, same key | | `job_interrupted` | 503 (async job result) | new key | Start a new attempt with a NEW Idempotency-Key | `422` means two things: a body with `error_code: "idempotency_conflict"` is a request error; a body with `codes[]` is a normal redeem where no code activated. ## 5. Billing and limits - You pay for outcomes. Requests are charged up front (1 per code), then every code that failed for a reason that is not the code's fault (`bad_player`, `failed`) is refunded automatically → `refunded_requests`. `billed_requests` is the final charge. - Not billed: requests rejected before any attempt (`4xx`, `402`, `409 no_stock`), idempotent replays, `429`s, and every read endpoint. - No plan (`billing: "free_credit"`): 300 activations. Each one comes back 24 hours after it was used — a rolling window, not a daily reset. Used up → `429 quota_exceeded` with `retry_after_sec`, `next_restore_at` and `free_credit`. - Plan (`billing: "plan"`): `quota.daily_limit` requests included per UTC day (`null` = no cap); beyond that each request is billed from the wallet at `per_request_usd`; wallet too low → `402 insufficient_funds`. Plans are assigned by the operator (contact support) — there is no self-serve catalog. - Burst limit: `POST /v1/redeem` 30 requests per 10 s per key → `429 rate_limited` + `Retry-After`. Other endpoints are not burst-limited; still, never poll faster than every 1–2 s. - Max 50 codes per redeem; body max 256 KB. Headers on responses, for reconciliation without a second call: | Header | Meaning | |---|---| | `KA-Cost` | Requests billed for this call | | `KA-Quota-Used` / `KA-Quota-Remaining` | Plan usage today, or free-credit usage in the rolling 24 h window | | `KA-Free-Credit` | `1` when the account is on free credit | | `KA-Quota-Limit` / `KA-Free-Credit-Next` | Free-credit cap / unix time the next credit returns | | `KA-Balance-Usd` | Wallet balance after the call | | `KA-Idempotent-Replay` | `true` when the answer is a replay | | `X-Request-Id` | Quote it in support tickets | | `KA-Version` | API contract version | ## 6. Reference client (Python + httpx) ```python import os, time, httpx BASE = "https://api.kabotapi.com" KEY = os.environ["KA_API_KEY"] # never hard-code or log the key def redeem(order_id: str, player_id: str, **source) -> dict: """source: codes=[...] | uc=120 | categories=[...] | packs=[...]. Returns the redeem body.""" headers = {"Authorization": f"Bearer {KEY}", "Idempotency-Key": order_id} # same key on every retry body = {"player_id": player_id, **source} delay = 2.0 for _ in range(6): try: r = httpx.post(f"{BASE}/v1/redeem", json=body, headers=headers, timeout=300) # 5 min; use 600 for extra margin except httpx.TransportError: # timeout / network: outcome unknown -> retry with the same key time.sleep(delay); delay = min(delay * 2, 30); continue try: data = r.json() except ValueError: data = {} if "codes" in data: # 200 or 422: a real outcome for every code return data if r.status_code == 429 or r.status_code >= 500 or data.get("error_code") == "idempotency_in_progress": time.sleep(float(r.headers.get("Retry-After") or delay)); delay = min(delay * 2, 30); continue raise RuntimeError(f"{r.status_code} {data.get('error_code')}") # 4xx: fix the request, do not retry raise TimeoutError("unresolved: retry later with the SAME Idempotency-Key") result = redeem("order-98213", "5123456789", uc=120) for c in result["codes"]: if c["status"] == "activated": pass # deliver elif c["status"] in ("code_used", "invalid_code"): pass # final failure (billed) else: pass # bad_player / failed / unknown: not billed — fix the ID, or retry later with a NEW key ``` ## 7. Integration checklist - [ ] Key in an env var; `GET /v1/me` returns `200` with `billing` = `plan` or `free_credit` - [ ] Order id saved first, then sent as `Idempotency-Key` on every attempt of that order - [ ] One code source per request; `player_id` checked as 5–24 digits before calling - [ ] Every `codes[i].status` mapped to an order state and a friendly customer message - [ ] Retries only on timeouts / `429` / `5xx`, same key, backoff, `Retry-After` honoured - [ ] `request_id` (and `job_id`) stored on the order - [ ] If async: webhook signature verified, deliveries deduplicated, polling fallback in place - [ ] The key, `message` text and raw API bodies never reach end customers