openapi: 3.0.3
info:
  title: unio — API для партнёров
  version: 1.0.0
  description: |
    unio подтверждает студенческий статус и выдаёт скидки партнёров. Партнёру — только факт: студент или нет, вуз, срок статуса, псевдоним студента. Ни ИИН, ни ФИО, ни фото; почта — только со scope email и согласия студента.

    Три способа: (1) «Касса» — заведение проверяет QR со студенческой карты unio (или 9 цифр под ним, как код в приложении-аутентификаторе) и отмечает, что скидка дана (телефон кассы /cashier или своя кассовая система через этот API); (2) «Промокоды» — онлайн: студент берёт в unio личный промокод на час и вводит его у вас на сайте, в приложении или в доставке, а ваш сервер проверяет код и сообщает unio о погашении — так считаются конверсии. Коды могут быть и ваши: загрузите выгрузку из своей промо-системы в кабинете unio — unio раздаст их по одному, а о погашениях вы сообщите по API или отчётом; (3) «Войти через unio» — OAuth 2.0 Authorization Code + PKCE, кнопка «Я студент» на сайте. Пошаговая инструкция по промокодам — https://unio.asia/developers/promo.md.

    QR и 9 цифр живут 90 секунд и гасятся один раз, поэтому снимок экрана не пройдёт. Постоянный код скидки UNIO-XXXX-XXXX — запасной путь, когда у студента нет связи.

    Ключ API кассовой системы и client_id/secret для «Войти через unio» выдаёт unio в кабинете партнёра (раздел «Касса») / при подключении.

    Ошибки API кассы: JSON `{"error": "<код>", "message": "<текст для человека>"}`. Ошибки OAuth — по RFC 6749: `{"error", "error_description"}`.

    Время — миллисекунды Unix, если не сказано иное. Суммы — в тенге (число, до двух знаков после запятой).
servers:
  - url: https://unio.asia
tags:
  - name: Касса
    description: Проверка QR и погашение скидок
  - name: Промокоды
    description: Личные промокоды для онлайна — проверка и сообщение о погашении (конверсии)
  - name: Войти через unio
    description: OAuth 2.0 + PKCE
paths:
  /v1/pos/check:
    post:
      tags: [Касса]
      operationId: posCheck
      summary: Проверить QR или код с карты студента
      description: Ничего не гасит, можно звать сколько угодно.
      security:
        - posKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/CheckRequest'
            example:
              qr: "https://unio.asia/k#Wm3fQ0bX7cLr2Ys9KdNa1v"
      responses:
        '200':
          description: Результат проверки.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CheckResult'
              example:
                result: ok
                ok: true
                message: Студент — можно давать скидку
                method: qr
                offer:
                  slug: zerno-coffee
                  brand: "Кофейня «Зерно»"
                  title: Любой кофе дешевле
                  discount: "−20%"
                  terms: Одна скидка на чек.
                student:
                  sub: 9f2c41d0a7b3e5c18d6f2a90
                  university: КБТУ
                  valid_until: "2027-06-30"
                uses_today: 0
                expires_in: 74
        '400':
          description: Ошибка запроса.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: "bad_key — ключ API неверный."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: rate_limited — больше 300 проверок за 10 минут на ключ или больше 30 ответов unknown за 10 минут.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
  /v1/pos/uses:
    post:
      tags: [Касса]
      operationId: posUse
      summary: Отметить, что скидка дана
      description: Проверяет так же, как /v1/pos/check, и записывает погашение. QR гасится один раз.
      security:
        - posKey: []
      parameters:
        - name: Idempotency-Key
          in: header
          required: false
          description: >-
            Необязательный, рекомендуется. 1–100 видимых ASCII-символов, без пробелов.
            Повтор запроса с тем же ключом (например, после обрыва связи) не создаёт второе
            погашение и возвращает первое с replayed=true и кодом 200.
          schema:
            type: string
            minLength: 1
            maxLength: 100
            pattern: '^[!-~]+$'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UseRequest'
            example:
              qr: "https://unio.asia/k#Wm3fQ0bX7cLr2Ys9KdNa1v"
              amount: 1500.00
              receipt: "2026-11-02-0451"
      responses:
        '201':
          description: Погашение создано.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UseResult'
              example:
                use:
                  id: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
                  created_at: 1793577600000
                  updated_at: 1793577600000
                  cancelled_at: null
                  cancellable_until: 1793664000000
                  method: qr
                  source: api
                  till: null
                  api_key: "Касса №1"
                  amount: 1500.00
                  receipt: "2026-11-02-0451"
                  offer:
                    slug: zerno-coffee
                    brand: "Кофейня «Зерно»"
                    title: Любой кофе дешевле
                    discount: "−20%"
                  student:
                    sub: 9f2c41d0a7b3e5c18d6f2a90
                offer:
                  slug: zerno-coffee
                  brand: "Кофейня «Зерно»"
                  title: Любой кофе дешевле
                  discount: "−20%"
                  terms: Одна скидка на чек.
                student:
                  sub: 9f2c41d0a7b3e5c18d6f2a90
                  university: КБТУ
                  valid_until: "2027-06-30"
                uses_today: 1
                expires_in: 40
        '200':
          description: Повтор запроса с тем же Idempotency-Key — возвращается первое погашение.
          content:
            application/json:
              schema:
                type: object
                required: [use, replayed]
                properties:
                  use:
                    $ref: '#/components/schemas/Use'
                  replayed:
                    type: boolean
                    example: true
              example:
                use:
                  id: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
                  created_at: 1793577600000
                  updated_at: 1793577600000
                  cancelled_at: null
                  cancellable_until: 1793664000000
                  method: qr
                  source: api
                  till: null
                  api_key: "Касса №1"
                  amount: 1500.00
                  receipt: "2026-11-02-0451"
                  offer:
                    slug: zerno-coffee
                    brand: "Кофейня «Зерно»"
                    title: Любой кофе дешевле
                    discount: "−20%"
                  student:
                    sub: 9f2c41d0a7b3e5c18d6f2a90
                replayed: true
        '400':
          description: "error: bad_request, bad_amount или bad_idempotency_key."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: "bad_key — ключ API неверный."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: >-
            Проверка не пройдена. error равен одному из result проверки
            (expired, used, not_student, other_company, offer_ended, unknown),
            message — что сказать кассиру.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: rate_limited.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    get:
      tags: [Касса]
      operationId: posUses
      summary: Сверка погашений
      description: Погашения компании, изменённые после курсора (since, after) — создание или отмена, по возрастанию updated_at и id. Первая страница — since=0.
      security:
        - posKey: []
      parameters:
        - name: since
          in: query
          required: false
          description: Мс Unix.
          schema:
            type: integer
            format: int64
            default: 0
        - name: after
          in: query
          required: false
          description: >-
            id последней записи прошлой страницы (next_after). Вместе с since — курсор: у записей
            с одинаковым updated_at на границе страницы ни одна не потеряется.
          schema:
            type: string
            pattern: '^[0-9a-f]{32}$'
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 500
            default: 100
      responses:
        '200':
          description: Список погашений.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UseList'
              example:
                items:
                  - id: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
                    created_at: 1793577600000
                    updated_at: 1793577600000
                    cancelled_at: null
                    cancellable_until: 1793664000000
                    method: qr
                    source: api
                    till: null
                    api_key: "Касса №1"
                    amount: 1500.00
                    receipt: "2026-11-02-0451"
                    offer:
                      slug: zerno-coffee
                      brand: "Кофейня «Зерно»"
                      title: Любой кофе дешевле
                      discount: "−20%"
                    student:
                      sub: 9f2c41d0a7b3e5c18d6f2a90
                next_since: 1793577600000
                next_after: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
                has_more: false
        '401':
          description: "bad_key — ключ API неверный."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
  /v1/pos/uses/{id}/cancel:
    post:
      tags: [Касса]
      operationId: posCancel
      summary: Отменить погашение
      description: Например, возврат чека. Можно в течение 24 часов после погашения. Повторная отмена ничего не меняет и возвращает ту же запись. Тела нет.
      security:
        - posKey: []
      parameters:
        - name: id
          in: path
          required: true
          description: 32 hex.
          schema:
            type: string
            pattern: '^[0-9a-f]{32}$'
      responses:
        '200':
          description: Погашение отменено.
          content:
            application/json:
              schema:
                type: object
                required: [use]
                properties:
                  use:
                    $ref: '#/components/schemas/Use'
              example:
                use:
                  id: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
                  created_at: 1793577600000
                  updated_at: 1793578200000
                  cancelled_at: 1793578200000
                  cancellable_until: null
                  method: qr
                  source: api
                  till: null
                  api_key: "Касса №1"
                  amount: 1500.00
                  receipt: "2026-11-02-0451"
                  offer:
                    slug: zerno-coffee
                    brand: "Кофейня «Зерно»"
                    title: Любой кофе дешевле
                    discount: "−20%"
                  student:
                    sub: 9f2c41d0a7b3e5c18d6f2a90
        '401':
          description: "bad_key — ключ API неверный."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: not_found — такого погашения нет.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: too_late — прошло больше 24 часов.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
  /v1/promo/check:
    post:
      tags: [Промокоды]
      operationId: promoCheck
      summary: Проверить промокод покупателя
      description: >-
        Ничего не гасит — зовите, когда покупатель ввёл код в поле «Промокод» на сайте или в приложении.
        result=ok — давайте скидку и покажите покупателю customer_message. Успешная проверка видна в отчёте
        unio как «ввели у партнёра». Если код — ваш (из выгрузки, загруженной в кабинете unio), проверять
        его не обязательно: ваша промо-система его и так знает — просто сообщите о погашении.
      security:
        - posKey: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/PromoCheckRequest'
            example:
              code: UN7K3QX9PM
      responses:
        '200':
          description: Результат проверки.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/PromoCheckResult'
              example:
                result: ok
                ok: true
                message: Студент — можно давать скидку
                customer_message: Промокод принят — скидка твоя
                method: personal
                code:
                  code: UN7K3QX9PM
                  source: unio
                  issued_at: 1793710000000
                  expires_at: 1793713600000
                  expires_in: 2741
                  redeemed_at: null
                offer:
                  slug: vzhuh-scooters
                  brand: "Самокаты «Вжух»"
                  title: Первые три поездки
                  discount: "−30%"
                  terms: Один код — один заказ.
                student:
                  sub: 9f2c41d0a7b3e5c18d6f2a90
                  university: КБТУ
                  valid_until: "2027-06-30"
        '400':
          description: bad_request — нет code.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: "bad_key — ключ API неверный."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: rate_limited — больше 3000 запросов за 10 минут на ключ или больше 300 ответов unknown за 10 минут.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
  /v1/promo/redemptions:
    post:
      tags: [Промокоды]
      operationId: promoRedeem
      summary: Сообщить о погашении промокода
      description: >-
        Главный вызов: заказ с кодом оформлен — сообщите unio, так считается конверсия. Один код — одно
        погашение. Повтор с тем же кодом и тем же order_id (или с тем же Idempotency-Key) возвращает первую
        запись с replayed=true и кодом 200 — после обрыва связи смело повторяйте. О погашении можно сообщить
        и после срока кода (пачкой раз в час или в день): скидку вы уже дали — погашение засчитывается с
        on_time=false. Отказ «код истёк» даёт только /v1/promo/check, до того как вы дали скидку.
      security:
        - posKey: []
      parameters:
        - name: Idempotency-Key
          in: header
          required: false
          description: >-
            Необязательный: повторы и так распознаются по коду и order_id. 1–100 видимых ASCII-символов,
            без пробелов; свой для каждого заказа.
          schema:
            type: string
            minLength: 1
            maxLength: 100
            pattern: '^[!-~]+$'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/RedemptionRequest'
            example:
              code: UN7K3QX9PM
              order_id: "YA-2026-11-03-0042"
              amount: 4500
              redeemed_at: 1793711259000
      responses:
        '201':
          description: Погашение записано.
          content:
            application/json:
              schema:
                type: object
                required: [redemption]
                properties:
                  redemption:
                    $ref: '#/components/schemas/Redemption'
              example:
                redemption:
                  id: c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8
                  code: UN7K3QX9PM
                  order_id: "YA-2026-11-03-0042"
                  receipt: "YA-2026-11-03-0042"
                  amount: 4500
                  redeemed_at: 1793711259000
                  on_time: true
                  issued_at: 1793710000000
                  expires_at: 1793713600000
                  created_at: 1793711260000
                  updated_at: 1793711260000
                  cancelled_at: null
                  cancellable_until: 1796303260000
                  method: personal
                  source: api
                  till: null
                  api_key: "Сайт, прод"
                  offer:
                    slug: vzhuh-scooters
                    brand: "Самокаты «Вжух»"
                    title: Первые три поездки
                    discount: "−30%"
                  student:
                    sub: 9f2c41d0a7b3e5c18d6f2a90
        '200':
          description: Повтор — возвращается первое погашение этого кода.
          content:
            application/json:
              schema:
                type: object
                required: [redemption, replayed]
                properties:
                  redemption:
                    $ref: '#/components/schemas/Redemption'
                  replayed:
                    type: boolean
                    example: true
        '400':
          description: "error: bad_request (нет code), bad_amount, bad_redeemed_at (в будущем или раньше выдачи кода), bad_idempotency_key."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '401':
          description: "bad_key — ключ API неверный."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: >-
            unknown — такого кода unio не выдавал (или это код из вашей выгрузки, который ещё никому не выдан);
            other_company — код выдан на скидку другой компании; used — код уже засчитан с другим order_id
            (в ответе есть redemption — первая запись); idempotency_key_reused — этот Idempotency-Key занят
            другим погашением.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '429':
          description: rate_limited.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
    get:
      tags: [Промокоды]
      operationId: promoRedemptions
      summary: Сверка погашений промокодов
      description: >-
        Погашения промокодов вашей компании, изменённые после курсора (since, after) — новые и отменённые,
        по возрастанию updated_at и id. Первая страница — since=0, дальше — next_since и next_after, пока
        has_more=true.
      security:
        - posKey: []
      parameters:
        - name: since
          in: query
          required: false
          description: Мс Unix.
          schema:
            type: integer
            format: int64
            default: 0
        - name: after
          in: query
          required: false
          description: id последней записи прошлой страницы (next_after).
          schema:
            type: string
            pattern: '^[0-9a-f]{32}$'
        - name: limit
          in: query
          required: false
          schema:
            type: integer
            minimum: 1
            maximum: 500
            default: 100
      responses:
        '200':
          description: Список погашений.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RedemptionList'
        '401':
          description: "bad_key — ключ API неверный."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
  /v1/promo/redemptions/{id}/cancel:
    post:
      tags: [Промокоды]
      operationId: promoCancel
      summary: Отменить погашение
      description: >-
        Заказ отменили или вернули — погашение перестаёт считаться конверсией. В течение 30 дней после
        сообщения о погашении. Повторная отмена ничего не меняет и возвращает ту же запись. Тела нет.
        Код второй раз не оживает: студент берёт в unio новый.
      security:
        - posKey: []
      parameters:
        - name: id
          in: path
          required: true
          description: id погашения, 32 hex.
          schema:
            type: string
            pattern: '^[0-9a-f]{32}$'
      responses:
        '200':
          description: Погашение отменено.
          content:
            application/json:
              schema:
                type: object
                required: [redemption]
                properties:
                  redemption:
                    $ref: '#/components/schemas/Redemption'
        '401':
          description: "bad_key — ключ API неверный."
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '404':
          description: not_found — такого погашения у вашей компании нет.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
        '409':
          description: too_late — прошло больше 30 дней.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Error'
  /.well-known/openid-configuration:
    get:
      tags: [Войти через unio]
      operationId: oidcDiscovery
      summary: OpenID Discovery
      description: Метаданные провайдера.
      security: []
      responses:
        '200':
          description: Метаданные.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Discovery'
              example:
                issuer: https://unio.asia
                authorization_endpoint: https://unio.asia/oauth/authorize
                token_endpoint: https://unio.asia/oauth/token
                userinfo_endpoint: https://unio.asia/oauth/userinfo
                response_types_supported: [code]
                grant_types_supported: [authorization_code]
                code_challenge_methods_supported: [S256]
                scopes_supported: [student, email]
                token_endpoint_auth_methods_supported: [client_secret_basic, client_secret_post]
                id_token_signing_alg_values_supported: [HS256]
                subject_types_supported: [pairwise]
                display_values_supported: [page, popup, embed]
                claims_supported: [sub, student, email, email_verified]
  /oauth/authorize:
    get:
      tags: [Войти через unio]
      operationId: oauthAuthorize
      summary: Экран согласия
      description: Браузер студента.
      security: []
      parameters:
        - name: response_type
          in: query
          required: true
          schema:
            type: string
            enum: [code]
        - name: client_id
          in: query
          required: true
          schema:
            type: string
        - name: redirect_uri
          in: query
          required: true
          description: Строго как в настройках партнёра.
          schema:
            type: string
        - name: state
          in: query
          required: false
          description: Рекомендуется.
          schema:
            type: string
            maxLength: 512
        - name: scope
          in: query
          required: false
          description: "Через пробел — student, email."
          schema:
            type: string
            default: student
        - name: code_challenge
          in: query
          required: false
          description: 43–128 символов base64url. PKCE.
          schema:
            type: string
            minLength: 43
            maxLength: 128
        - name: code_challenge_method
          in: query
          required: false
          schema:
            type: string
            enum: [S256]
        - name: nonce
          in: query
          required: false
          description: Вернётся в id_token.
          schema:
            type: string
            maxLength: 256
        - name: display
          in: query
          required: false
          description: >-
            embed — окно unio во фрейме на странице партнёра, результат через postMessage,
            так работает SDK /sdk/unio.js.
          schema:
            type: string
            enum: [page, popup, embed]
            default: page
      responses:
        '302':
          description: >-
            Переход на экран согласия unio; после решения студента — на redirect_uri
            с ?code=…&state=… или ?error=…&error_description=…&state=…
            (error: access_denied, invalid_scope, invalid_request, unsupported_response_type).
        '400':
          description: "HTML-страница ошибки — неизвестный client_id или redirect_uri не совпал. На чужой адрес не перенаправляем."
          content:
            text/html:
              schema:
                type: string
              example: "<!doctype html><html><body><h1>Ошибка</h1><p>redirect_uri не совпадает с настройками партнёра.</p></body></html>"
  /oauth/token:
    post:
      tags: [Войти через unio]
      operationId: oauthToken
      summary: Выдача токенов
      security:
        - clientBasic: []
        - {}
      requestBody:
        required: true
        description: Данные аутентификации — заголовком Basic (client_secret_basic) или полями в теле (client_secret_post).
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              required: [grant_type, code]
              properties:
                grant_type:
                  type: string
                  enum: [authorization_code]
                code:
                  type: string
                  description: Одноразовый; живёт 5 минут.
                redirect_uri:
                  type: string
                code_verifier:
                  type: string
                  description: Обязателен, если в /oauth/authorize был code_challenge.
                client_id:
                  type: string
                client_secret:
                  type: string
          application/json:
            schema:
              type: object
              required: [grant_type, code]
              properties:
                grant_type:
                  type: string
                  enum: [authorization_code]
                code:
                  type: string
                  description: Одноразовый; живёт 5 минут.
                redirect_uri:
                  type: string
                code_verifier:
                  type: string
                  description: Обязателен, если в /oauth/authorize был code_challenge.
                client_id:
                  type: string
                client_secret:
                  type: string
      responses:
        '200':
          description: Токены выданы.
          headers:
            Cache-Control:
              description: no-store
              schema:
                type: string
                example: no-store
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TokenResponse'
              example:
                access_token: q7XKc2m9Vd0nR4tYb8LzWp1sH6uFj3Ae5GiNo0kTyQw
                token_type: Bearer
                expires_in: 3600
                scope: student email
                id_token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1YmU4YzBkMWYzYTI0ZTZiOWM3ZDFlMmYzYTRiNWM2ZCIsInN0dWRlbnQiOnsidmVyaWZpZWQiOnRydWUsInVuaXZlcnNpdHkiOiLQmtCR0KLQoyIsInZhbGlkX3VudGlsIjoiMjAyNy0wNi0zMCJ9LCJpc3MiOiJodHRwczovL3VuaW8uYXNpYSIsImF1ZCI6ImFjbWUiLCJpYXQiOjE3OTM1Nzc2MDAsImV4cCI6MTc5MzU3ODIwMCwibm9uY2UiOiJuLTdmM2EifQ.X5UuU03HekZJLk6iPe-fjkwXh4CAcXYYrkrtqqgDB68
        '400':
          description: >-
            invalid_request; invalid_grant — код неизвестен, истёк, выдан другому партнёру,
            уже использован (тогда выданные по нему токены отзываются), не совпал redirect_uri
            или code_verifier; unsupported_grant_type.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OAuthError'
        '401':
          description: invalid_client — неверные учётные данные клиента.
          headers:
            WWW-Authenticate:
              description: Basic realm="unio"
              schema:
                type: string
                example: 'Basic realm="unio"'
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/OAuthError'
  /oauth/userinfo:
    get:
      tags: [Войти через unio]
      operationId: oauthUserinfo
      summary: Данные студента
      description: >-
        Перепроверить статус позже: работает, пока студент не отключил партнёра в кабинете
        и токен не истёк (1 час).
      security:
        - accessToken: []
      responses:
        '200':
          description: Данные студента.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Claims'
              example:
                sub: a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6
                student:
                  verified: true
                  university: КБТУ
                  valid_until: "2027-06-30"
                email: student@example.com
                email_verified: true
        '401':
          description: invalid_token — токен неверный или истёк.
          headers:
            WWW-Authenticate:
              description: Bearer realm="unio"
              schema:
                type: string
                example: 'Bearer realm="unio"'
          content:
            application/json:
              schema:
                type: object
                required: [error]
                properties:
                  error:
                    type: string
              example:
                error: invalid_token
components:
  securitySchemes:
    posKey:
      type: http
      scheme: bearer
      bearerFormat: "unio_sk_…"
      description: >-
        Ключ API кассовой системы. Создаётся в кабинете unio → «Касса» → «Ключ API»,
        показывается один раз.
    clientBasic:
      type: http
      scheme: basic
      description: >-
        client_id:client_secret (client_secret_basic). Также можно передать client_id и
        client_secret в теле запроса (client_secret_post).
    accessToken:
      type: http
      scheme: bearer
      description: access_token из /oauth/token.
  schemas:
    Error:
      type: object
      required: [error, message]
      properties:
        error:
          type: string
          description: Код ошибки.
        message:
          type: string
          description: Текст для человека.
    OAuthError:
      type: object
      required: [error]
      properties:
        error:
          type: string
          description: Код ошибки по RFC 6749.
        error_description:
          type: string
          description: Текст для человека.
    OfferBrief:
      type: object
      required: [slug, brand, title, discount]
      properties:
        slug:
          type: string
        brand:
          type: string
        title:
          type: string
        discount:
          type: string
          description: Строка вида «−20%».
        terms:
          type: string
          nullable: true
    Student:
      type: object
      required: [sub, university, valid_until]
      properties:
        sub:
          type: string
          description: >-
            Псевдоним студента, 24 hex. Один и тот же на всех кассах и в API одной компании,
            у разных компаний разный.
        university:
          type: string
          nullable: true
        valid_until:
          type: string
          format: date
          nullable: true
          description: До какого дня действует статус.
    Use:
      type: object
      required: [id, created_at, updated_at, method, source]
      properties:
        id:
          type: string
          description: 32 hex.
        created_at:
          type: integer
          format: int64
          description: Мс Unix.
        updated_at:
          type: integer
          format: int64
          description: Мс Unix.
        cancelled_at:
          type: integer
          format: int64
          nullable: true
          description: Мс Unix.
        cancellable_until:
          type: integer
          format: int64
          nullable: true
          description: До какого момента (мс Unix) можно отменить; null, если уже отменено.
        method:
          type: string
          enum: [qr, code, promo, personal]
          description: >-
            Как студент показал скидку: qr — QR с карты, code — 9 цифр под QR,
            promo — постоянный код скидки UNIO-XXXX-XXXX (у студента не было связи),
            personal — личный промокод онлайн-скидки (раздел «Промокоды»).
        source:
          type: string
          enum: [till, api]
          description: Касса-телефон или кассовая система.
        till:
          type: string
          nullable: true
          description: Название кассы.
        api_key:
          type: string
          nullable: true
          description: Название ключа.
        amount:
          type: number
          nullable: true
          description: Сумма чека в тенге.
        receipt:
          type: string
          nullable: true
        redeemed_at:
          type: integer
          format: int64
          nullable: true
          description: Только для personal — когда погасили промокод, мс Unix.
        on_time:
          type: boolean
          nullable: true
          description: Только для personal — погасили ли до конца срока кода.
        offer:
          type: object
          properties:
            slug:
              type: string
            brand:
              type: string
            title:
              type: string
            discount:
              type: string
        student:
          type: object
          properties:
            sub:
              type: string
              description: Псевдоним студента.
    CheckRequest:
      type: object
      description: "Нужно одно из двух — qr или code; если пришли оба, проверяется qr."
      anyOf:
        - required: [qr]
        - required: [code]
      properties:
        qr:
          type: string
          description: >-
            Содержимое QR с карты студента как есть — ссылка вида https://unio.asia/k#AbC…
            или только токен после #.
        code:
          type: string
          description: >-
            9 цифр под QR на карте студента («123 456 789», меняются вместе с QR, живут 90 секунд
            и гасятся один раз), личный промокод онлайн-скидки (UN и 8 знаков или ваш код из выгрузки) —
            или постоянный код скидки UNIO-XXXX-XXXX, если у студента нет связи. Пробелы, дефисы,
            регистр и кириллица вместо похожих латинских букв не важны.
          example: 477 508 348
    UseRequest:
      allOf:
        - $ref: '#/components/schemas/CheckRequest'
        - type: object
          properties:
            amount:
              type: number
              minimum: 0
              exclusiveMinimum: true
              maximum: 100000000
              description: Сумма чека в тенге.
            receipt:
              type: string
              maxLength: 64
              description: Номер чека.
    CheckResult:
      type: object
      required: [result, ok, message, method]
      description: offer, student, uses_today, expires_in есть только при result=ok.
      properties:
        result:
          type: string
          enum: [ok, expired, used, not_student, other_company, offer_ended, unknown]
          description: |
            ok — студент, скидку можно дать;
            expired — QR старше 90 секунд, попросить открыть карту заново (у личного промокода — вышел его срок);
            used — этот QR уже погашен;
            not_student — статус студента не подтверждён или истёк;
            other_company — скидка другого заведения (больше ничего не сообщаем);
            offer_ended — скидка выключена;
            unknown — такого QR или кода нет.
        ok:
          type: boolean
        message:
          type: string
          description: Текст для кассира.
        method:
          type: string
          enum: [qr, code, promo, personal]
          nullable: true
          description: qr — QR, code — 9 цифр под QR, promo — постоянный код скидки, personal — личный промокод.
        offer:
          $ref: '#/components/schemas/OfferBrief'
        student:
          $ref: '#/components/schemas/Student'
        uses_today:
          type: integer
          description: Сколько раз сегодня этому студенту уже дали эту скидку в вашей компании.
        expires_in:
          type: integer
          description: Сек до конца жизни QR или личного промокода (qr, code, personal).
    UseResult:
      type: object
      required: [use, offer, student, uses_today]
      properties:
        use:
          $ref: '#/components/schemas/Use'
        offer:
          $ref: '#/components/schemas/OfferBrief'
        student:
          $ref: '#/components/schemas/Student'
        uses_today:
          type: integer
          description: Сколько раз сегодня этому студенту уже дали эту скидку в вашей компании.
        expires_in:
          type: integer
          description: Сек до конца жизни QR, только для qr.
    UseList:
      type: object
      required: [items, next_since, next_after, has_more]
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/Use'
        next_since:
          type: integer
          format: int64
          description: Передайте в since следующего запроса.
        next_after:
          type: string
          nullable: true
          description: Передайте в after следующего запроса.
        has_more:
          type: boolean
    PromoCheckRequest:
      type: object
      required: [code]
      properties:
        code:
          type: string
          description: >-
            Промокод, который ввёл покупатель, как есть. Пробелы, дефисы, регистр и кириллица вместо похожих
            латинских букв не важны.
          example: UN7K3QX9PM
    PromoCode:
      type: object
      required: [code, source, issued_at, expires_at, expires_in]
      properties:
        code:
          type: string
          description: Код так, как его показали студенту.
          example: UN7K3QX9PM
        source:
          type: string
          enum: [unio, partner]
          description: >-
            unio — код сгенерировал unio («UN» и 8 знаков без 0, 1, I, O); partner — ваш код из выгрузки,
            загруженной в кабинете unio.
        issued_at:
          type: integer
          format: int64
          description: Когда unio выдал код студенту, мс Unix.
        expires_at:
          type: integer
          format: int64
          description: До какого момента код действует, мс Unix. Срок задаётся у скидки, по умолчанию — час.
        expires_in:
          type: integer
          description: Сек до конца срока; 0 — срок вышел.
        redeemed_at:
          type: integer
          format: int64
          nullable: true
          description: Когда код погасили, если о погашении уже сообщили.
    PromoCheckResult:
      type: object
      required: [result, ok, message, customer_message]
      description: code есть, если код найден у вашей компании; offer и student — только при result=ok.
      properties:
        result:
          type: string
          enum: [ok, expired, used, not_student, other_company, offer_ended, unknown]
          description: |
            ok — студент, скидку можно дать;
            expired — срок кода вышел: студент берёт в unio новый;
            used — о погашении этого кода уже сообщили;
            not_student — статус студента не подтверждён или истёк;
            other_company — код выдан на скидку другой компании (больше ничего не сообщаем);
            offer_ended — скидка выключена;
            unknown — такого кода unio не выдавал.
        ok:
          type: boolean
        message:
          type: string
          description: Текст для сотрудника и логов.
        customer_message:
          type: string
          description: Текст для покупателя — покажите его рядом с полем «Промокод» как есть.
        method:
          type: string
          enum: [personal]
          nullable: true
          description: personal — личный промокод; null, если код у вашей компании не найден.
        code:
          $ref: '#/components/schemas/PromoCode'
        offer:
          $ref: '#/components/schemas/OfferBrief'
        student:
          $ref: '#/components/schemas/Student'
    RedemptionRequest:
      type: object
      required: [code]
      properties:
        code:
          type: string
          description: >-
            Промокод из заказа как есть. Пробелы, дефисы, регистр и кириллица вместо похожих латинских букв
            не важны.
          example: UN7K3QX9PM
        order_id:
          type: string
          maxLength: 64
          description: Номер заказа. Рекомендуется — по нему видна сверка и узнаётся повтор.
        amount:
          type: number
          minimum: 0
          exclusiveMinimum: true
          maximum: 100000000
          description: Сумма заказа в тенге.
        redeemed_at:
          type: integer
          format: int64
          description: >-
            Когда код погасили, мс Unix по вашим часам: не позже «сейчас + 5 минут» и не раньше выдачи кода
            студенту. Не передали — «сейчас». Сообщаете пачкой позже — передайте время заказа: по нему
            считается «в срок».
    Redemption:
      type: object
      required: [id, code, created_at, updated_at, method, source, issued_at, expires_at]
      properties:
        id:
          type: string
          description: 32 hex.
        code:
          type: string
          description: Промокод — как его показали студенту.
        order_id:
          type: string
          nullable: true
          description: Номер заказа.
        receipt:
          type: string
          nullable: true
          description: То же, что order_id (поле журнала погашений кассы).
        amount:
          type: number
          nullable: true
          description: Сумма заказа в тенге.
        redeemed_at:
          type: integer
          format: int64
          nullable: true
          description: Когда код погасили, мс Unix (из вашего сообщения; null — в отчёте не было даты).
        on_time:
          type: boolean
          nullable: true
          description: >-
            true — погасили до конца срока кода; false — позже (конверсия засчитана с пометкой «после срока»);
            null — время погашения неизвестно.
        issued_at:
          type: integer
          format: int64
          description: Когда unio выдал код студенту, мс Unix.
        expires_at:
          type: integer
          format: int64
          description: Когда кончился срок кода, мс Unix.
        created_at:
          type: integer
          format: int64
          description: Когда unio получил сообщение о погашении, мс Unix.
        updated_at:
          type: integer
          format: int64
          description: Мс Unix; меняется и при отмене.
        cancelled_at:
          type: integer
          format: int64
          nullable: true
          description: Мс Unix.
        cancellable_until:
          type: integer
          format: int64
          nullable: true
          description: До какого момента можно отменить (мс Unix); null, если уже отменено.
        method:
          type: string
          enum: [personal]
        source:
          type: string
          enum: [api, till, import]
          description: >-
            api — сообщил ваш сервер; till — отметила касса unio (/cashier); import — ваш отчёт, загруженный
            в кабинете unio.
        till:
          type: string
          nullable: true
          description: Название кассы.
        api_key:
          type: string
          nullable: true
          description: Название ключа.
        offer:
          type: object
          properties:
            slug:
              type: string
            brand:
              type: string
            title:
              type: string
            discount:
              type: string
        student:
          type: object
          properties:
            sub:
              type: string
              description: Псевдоним студента — тот же, что в /v1/promo/check и на кассе.
    RedemptionList:
      type: object
      required: [items, next_since, next_after, has_more]
      properties:
        items:
          type: array
          items:
            $ref: '#/components/schemas/Redemption'
        next_since:
          type: integer
          format: int64
          description: Передайте в since следующего запроса.
        next_after:
          type: string
          nullable: true
          description: Передайте в after следующего запроса.
        has_more:
          type: boolean
    Discovery:
      type: object
      required:
        - issuer
        - authorization_endpoint
        - token_endpoint
        - userinfo_endpoint
        - response_types_supported
        - grant_types_supported
        - code_challenge_methods_supported
        - scopes_supported
        - token_endpoint_auth_methods_supported
        - id_token_signing_alg_values_supported
        - subject_types_supported
        - display_values_supported
        - claims_supported
      properties:
        issuer:
          type: string
          description: URL.
        authorization_endpoint:
          type: string
          description: URL.
        token_endpoint:
          type: string
          description: URL.
        userinfo_endpoint:
          type: string
          description: URL.
        response_types_supported:
          type: array
          items:
            type: string
        grant_types_supported:
          type: array
          items:
            type: string
        code_challenge_methods_supported:
          type: array
          items:
            type: string
        scopes_supported:
          type: array
          items:
            type: string
        token_endpoint_auth_methods_supported:
          type: array
          items:
            type: string
        id_token_signing_alg_values_supported:
          type: array
          items:
            type: string
        subject_types_supported:
          type: array
          items:
            type: string
        display_values_supported:
          type: array
          items:
            type: string
        claims_supported:
          type: array
          items:
            type: string
    TokenResponse:
      type: object
      required: [access_token, token_type, expires_in, scope, id_token]
      properties:
        access_token:
          type: string
          description: Случайная строка, не JWT. Живёт 1 час — для /oauth/userinfo.
        token_type:
          type: string
          example: Bearer
        expires_in:
          type: integer
          description: Секунды.
          example: 3600
        scope:
          type: string
        id_token:
          type: string
          description: >-
            JWT HS256, подписан client_secret партнёра. Payload — IdTokenClaims. Проверяй подпись, aud, iss и exp
            на своём сервере. Пример в ответе подписан секретом «example-secret».
    Claims:
      type: object
      required: [sub, student]
      properties:
        sub:
          type: string
          description: Псевдоним для этого партнёра, 32 hex.
        student:
          type: object
          required: [verified, university, valid_until]
          properties:
            verified:
              type: boolean
            university:
              type: string
              nullable: true
              description: Null, если verified=false.
            valid_until:
              type: string
              format: date
              nullable: true
              description: До какого дня действует статус; null, если verified=false.
        email:
          type: string
          description: Только со scope email.
        email_verified:
          type: boolean
    IdTokenClaims:
      allOf:
        - $ref: '#/components/schemas/Claims'
        - type: object
          required: [iss, aud, iat, exp]
          properties:
            iss:
              type: string
              description: URL issuer.
            aud:
              type: string
              description: client_id.
            iat:
              type: integer
              description: Секунды Unix.
            exp:
              type: integer
              description: Секунды Unix; id_token живёт 10 минут.
            nonce:
              type: string
              description: Как было передано в /oauth/authorize.
