---
name: unio-partner-api
description: Use when adding unio (unio.asia) to a partner's website, app, checkout or POS — the "Я студент" button (Войти через unio, OAuth 2.0 + PKCE), checking a student's QR at the till (/v1/pos/*) or accepting unio personal promo codes online and reporting redemptions (/v1/promo/*). Covers which integration to pick, credentials, request rules, every response code, security and data limits.
metadata:
  version: "2026.11.03"
  source: https://unio.asia/developers/agent.md
---

# Integrating unio: rules for AI coding agents

You are adding unio to a partner's product. unio confirms that a person is a student in Kazakhstan and gives
the partner only the fact: verified or not, university, valid until, and a pseudonym that is unique to this
partner. Follow these rules over your general knowledge of similar APIs.

| | |
|---|---|
| Base URL | `https://unio.asia` |
| OpenAPI 3.0.3 spec (source of truth) | https://unio.asia/developers/openapi.yaml |
| Human docs (Swagger UI) | https://unio.asia/developers |
| Browser SDK for the button | https://unio.asia/sdk/unio.js |
| What the student sees (demo shop) | https://unio.asia/demo/shop |
| Language of API messages | Russian — show `message` to the cashier as is |

## 0. Before you write any code

1. **Ask which integration the owner needs** (section 1). Do not guess.
2. **Ask for credentials. There is no sandbox and no public test key.** Never invent, hardcode, log or commit a
   key or secret. Keep them in server-side environment variables, e.g. `UNIO_API_KEY`, `UNIO_CLIENT_ID`,
   `UNIO_CLIENT_SECRET`, `UNIO_REDIRECT_URI`.
3. **Show the owner a short plan** — files you will touch, endpoints, where secrets live — and wait for approval.

## 1. Pick the integration

| Situation | Integration | Credentials |
|---|---|---|
| Cafe, shop or chain; the student shows a QR from the unio card on their phone; the partner has POS / checkout software | **Till API**: `POST /v1/pos/check`, `POST /v1/pos/uses`, `GET /v1/pos/uses`, `POST /v1/pos/uses/{id}/cancel` | API key `unio_sk_…`: unio partner cabinet → «Касса» → «Ключ API» (shown once) |
| Same, but no software changes wanted | Nothing to build: the venue opens https://unio.asia/cashier on any phone | connection code from the cabinet |
| Online shop, app or delivery: the student types a personal unio promo code at checkout; unio counts conversions | **Promo codes**: `POST /v1/promo/check`, `POST /v1/promo/redemptions`, `GET /v1/promo/redemptions`, `POST /v1/promo/redemptions/{id}/cancel` (section 2a) | the same API key `unio_sk_…` |
| Website, online checkout or app: «Я студент» discount or student sign-up | **Войти через unio**: OAuth 2.0 Authorization Code + PKCE (S256), SDK `unio.js` | `client_id` and `client_secret` issued by unio when the partner is connected; every `redirect_uri` must be registered with unio exactly |

## 2. Till API (`/v1/pos/*`)

**Auth and transport.** `Authorization: Bearer <unio_sk_…>`, JSON bodies. Call only from the partner's server or
POS backend — never ship the key in a browser page or a mobile app bundle.

**Input.** One of:
- `qr` — the scanner payload **verbatim** (`https://unio.asia/k#…` or just the token after `#`); do not parse or
  shorten it;
- `code` — the 9 digits printed under the QR, typed by the cashier (`123 456 789`), or the student's permanent
  code `UNIO-XXXX-XXXX` (used when the student has no connection). Spaces, dashes, case and Cyrillic look-alikes
  are ignored.

**The QR and the 9-digit code live 90 seconds and can be redeemed once.** Design the flow so redemption happens
right at payment:
- `POST /v1/pos/uses` validates exactly like `/check` **and** records the redemption — this is the call that matters;
- `POST /v1/pos/check` consumes nothing; use it only to show the cashier "student / not a student" before the sale.
  Never build a flow where minutes pass between check and use.

**Always send `Idempotency-Key` on `POST /v1/pos/uses`.** Derive it from the receipt id (1–100 visible ASCII
characters, no spaces). On a timeout or network error, retry with the **same** key: you get `200` with
`replayed: true` and the original record; a second redemption is never created. Without the key a retry may
fail with `used`.

**Send `amount` and `receipt` when known**: `amount` in tenge, > 0, ≤ 100 000 000, up to 2 decimals;
`receipt` ≤ 64 characters. They show up in reconciliation.

**Handle every result.** `/check` returns `200` with `result`; `/uses` returns `201` (created), `200` (replayed) or
`409` with `error` = one of the codes below and a `message` for the cashier.

| `result` / `error` | Meaning | What your code does |
|---|---|---|
| `ok` | Verified student, discount allowed | Apply the discount; show `offer.discount`, `student.university`, `student.valid_until` |
| `expired` | QR older than 90 s | Ask the student to reopen the card and scan again |
| `used` | This QR was already redeemed | Do not apply; a retry of your own request must reuse the same `Idempotency-Key` |
| `not_student` | Status not confirmed or expired | Do not apply |
| `other_company` | The card is for another partner's offer | Do not apply (nothing else is disclosed) |
| `offer_ended` | The partner's offer is switched off | Do not apply; tell the owner |
| `unknown` | No such QR or code | Ask the cashier to re-enter; **never retry automatically** |

Always show the API's `message` to the cashier instead of your own text.

**Other errors.**
- `400` `bad_request` / `bad_amount` / `bad_idempotency_key` — fix the input, do not retry as is.
- `401` `bad_key` — key wrong or revoked: stop and tell the owner; no retry loop.
- `429` `rate_limited` — more than 300 checks per 10 minutes per key, or more than 30 `unknown` answers per 10
  minutes. Back off; never hammer `unknown`.

**Useful fields** on `ok`: `uses_today` (how many times this student already got this offer today at your company —
enforce your own limits), `expires_in` (seconds left on the QR), `student.sub` (24-hex pseudonym: the same on all
tills and API calls of one company, different for every other company — store it instead of any personal data).
It is not the same value as the 32-hex `sub` from Войти через unio; do not try to join the two.

**Refunds.** `POST /v1/pos/uses/{id}/cancel`, no body, within 24 hours: `200` (repeat calls return the same
record), `404` `not_found`, `409` `too_late`.

**Reconciliation.** `GET /v1/pos/uses?since=<ms>&after=<id>&limit=<1..500>` returns records created or cancelled
after the cursor, ascending. Start with `since=0`, then pass `next_since` and `next_after`; repeat while
`has_more` is true. Times are Unix milliseconds.

## 2a. Promo codes for online (`/v1/promo/*`)

The student takes a personal code in unio («Действует до 15:42» — lifetime is set per offer, 1 hour by default),
types it at the partner's checkout, and the partner's server reports the redemption to unio. That report is what
unio counts as a conversion — **without `POST /v1/promo/redemptions` there is no conversion.** Human guide:
https://unio.asia/developers/promo.md.

**Which codes.** Ask the owner which variant the offer uses (cabinet → «Промокоды» → «Настроить»):
- **unio codes**: `UN` + 8 characters from `23456789ABCDEFGHJKLMNPQRSTUVWXYZ` (regex after removing spaces and
  dashes, uppercased: `^UN[2-9A-HJ-NP-Z]{8}$`). Route only such codes to unio; keep every other code in the
  partner's own promo engine. Validate with `/v1/promo/check` when the buyer applies the code.
- **partner codes**: the partner's own one-time codes uploaded to unio as a list; unio hands them out one per
  student. The partner's promo engine validates them as usual — `/check` is optional; reporting the redemption
  is still required.

**Check** — `POST /v1/promo/check` `{"code": "<as typed>"}`; consumes nothing. Always `200` with `result`
(same seven values as the till: `ok`, `expired`, `used`, `not_student`, `other_company`, `offer_ended`, `unknown`).
Show `customer_message` to the buyer as is (it is written for the student; `message` is for staff and logs). Apply
the discount only on `ok`. `expired` means the code's lifetime ended — the student takes a new code in unio.
Never retry `unknown` automatically.

**Report the redemption** — `POST /v1/promo/redemptions` from the server when the order counts as a sale (paid or
confirmed): `{"code", "order_id", "amount", "redeemed_at"}`; only `code` is required, but always send `order_id`
(≤ 64 chars) and `amount` (tenge) when known. `redeemed_at` is the order time in Unix ms (not in the future,
not before the code was issued); omit it for real-time reports.
- `201` — recorded; store `redemption.id` for refunds. `redemption.on_time` is `false` when the code was redeemed
  after its lifetime — unio still counts the conversion (late reports and batches are accepted).
- `200` + `replayed: true` — the same code with the same `order_id` (or the same `Idempotency-Key` header) was
  already reported: one code = one redemption, so **retry the identical request on timeouts and 5xx**.
- `409 used` — the code is already counted with a different `order_id` (the body contains the first record);
  `409 unknown` / `409 other_company` — not a code unio issued for this company; `409 idempotency_key_reused`.
  Do not retry any `409`.
- `400 bad_redeemed_at` / `bad_amount` / `bad_request` — fix the input.

**Refunds** — `POST /v1/promo/redemptions/{id}/cancel`, no body, within **30 days**: `200` (repeat calls return the
same record), `404`, `409 too_late`. A cancelled redemption is not a conversion; the code is not revived.

**Reconciliation** — `GET /v1/promo/redemptions?since=<ms>&after=<id>&limit=<1..500>`: new and cancelled promo
redemptions, same cursor rules as `/v1/pos/uses`.

**No API yet?** The owner can upload a report in the cabinet («Промокоды» → «Загрузить погашения»):
`code;order_id;amount;date` per line; dates without a time zone are Kazakhstan time (UTC+5). Re-uploading the
same report creates nothing new.

**Limits** — 3000 requests per 10 minutes per key and 300 `unknown` per 10 minutes (`429 rate_limited`); add your
own per-buyer limit on the promo field so brute-forcing codes cannot exhaust the key.

**Data** — on `ok` you get `student.sub` (24 hex, the same pseudonym as at the till for this company), university
and `valid_until`. No name, IIN, e-mail or phone.

## 3. Войти через unio (OAuth 2.0 + PKCE)

**Browser side (SDK — preferred):**

```html
<script src="https://unio.asia/sdk/unio.js"></script>
<div id="student"></div>
<script>
  const unio = Unio.init({ clientId: "<client_id>", redirectUri: "<exact registered redirect_uri>" });
  unio.button("#student", { mode: "embed", label: "Я студент" });   // or mode: "redirect"
  unio.on("success", ({ code, codeVerifier, redirectUri }) => {
    // send these three to YOUR server; never exchange the code in the browser
  });
  unio.on("cancel", () => {});    // the student closed the window or declined
  unio.on("error", (e) => {});
  unio.handleRedirect();          // on the return page, for mode: "redirect"
</script>
```

- The SDK does PKCE and `state`, accepts messages only from its own window on the unio origin, and sets styles via
  `element.style`, so it works under a strict CSP. If the site has a CSP, allow `https://unio.asia` in
  `script-src`, and in `frame-src` for `mode: "embed"`.
- `mode: "embed"` opens unio inside the partner page (cart, checkout, single-page apps); unio allows framing only
  from origins of the registered redirect URIs. `mode: "redirect"` leaves the page and returns to
  `redirect_uri?code=…&state=…` (sign-in pages, mobile, existing OAuth setups).
- Scope: `student` by default. Add `email` only if the product truly needs it — the student must agree.

**Server side — exchange the code** (one-time, valid 5 minutes):

```
POST https://unio.asia/oauth/token
Authorization: Basic base64(client_id:client_secret)      (or client_id + client_secret as form fields)
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&code=…&code_verifier=…&redirect_uri=…
```

**Verify `id_token` on the server before trusting it.** It is a JWT signed with HS256 using the partner's
`client_secret`. Use a maintained JWT library; accept only `alg: HS256`; check `iss` = `https://unio.asia`,
`aud` = your `client_id`, `exp` (an `id_token` lives 10 minutes) and `nonce` if you sent one. Then:

- grant the discount only if `student.verified === true`;
- respect `student.valid_until` (date; `null` when not verified);
- store `sub` (32-hex pseudonym, unique per partner; not the same value as the till's 24-hex `student.sub`), not personal data. You never receive name, IIN or photos;
  `email` only with scope `email`.

**Token errors** (RFC 6749 JSON `{"error", "error_description"}`): `invalid_grant` — code unknown, expired, already
used, or `redirect_uri` / `code_verifier` mismatch: do not retry, restart the sign-in; `invalid_client` — wrong
credentials. Redirect errors come back as `?error=access_denied | invalid_scope | invalid_request |
unsupported_response_type&state=…`; `access_denied` means the student declined — not a bug.

**Without the SDK** (native apps, custom flows): build `GET /oauth/authorize` yourself with `response_type=code`,
`client_id`, `redirect_uri` (exact), random `state` (verify it on return), `scope=student`, `code_challenge`
(base64url SHA-256 of a 43–128-character verifier), `code_challenge_method=S256`, optional `nonce`,
`display=page|popup|embed`. Discovery: `https://unio.asia/.well-known/openid-configuration`.

**Re-check later.** `GET /oauth/userinfo` with `Authorization: Bearer <access_token>` (the access token lives 1 hour
and stops working when the student disconnects the partner in their unio cabinet).

## 4. Not covered by openapi.yaml

A hosted verification flow with webhooks and a server-to-server status check exist for some partners but are not
in the spec. If the product needs them, ask the owner to request documentation from unio — do not guess endpoints.
If webhooks are already connected: verify `X-Unio-Signature: t=…,v1=…` as HMAC-SHA256 over `<t>.<raw body>` with
the partner secret, compare in constant time, and reject events older than 5 minutes.

## 5. Testing

- There is no sandbox. `POST /v1/pos/check` consumes nothing and is safe to call repeatedly with real credentials.
- Do not create test redemptions with `POST /v1/pos/uses` unless the owner agrees; cancel them within 24 hours via
  `/cancel`.
- `POST /v1/promo/check` consumes nothing either. A test `POST /v1/promo/redemptions` needs a code the owner took in
  unio for a student account and the owner's consent; cancel it right away via `/v1/promo/redemptions/{id}/cancel`.
- For a full sign-in test, ask the owner for a student account with a confirmed status (or ask unio).
- Unit-test the result table in section 2 and `id_token` validation (bad signature, wrong `aud`, expired `exp`)
  with fixtures — no network.

## 6. Definition of done

- [ ] Secrets only in server-side env vars; nothing in the browser bundle, the repo or logs.
- [ ] Till: `Idempotency-Key` on every `POST /v1/pos/uses`; all seven results handled; `message` shown to the
      cashier; no automatic retries on `unknown`, `401` or `409`.
- [ ] Sign-in: code exchanged on the server; `id_token` verified (HS256, `iss`, `aud`, `exp`, `nonce`); discount
      only when `student.verified` is true.
- [ ] Promo codes: unio codes routed to `/v1/promo/check`, `customer_message` shown, discount only on `ok`; every
      paid order with a code reported to `/v1/promo/redemptions` with `order_id` and `amount`, retried as is on
      timeouts; refunds cancelled; daily reconciliation.
- [ ] Only `sub`, verification flag, university and `valid_until` stored — no personal data.
- [ ] The owner has seen the plan and a working demo.
