API Reference
The RetentionPlay /v1 HTTP API as described by the canonical OpenAPI document (backend/crates/api/openapi/playflow-v1.openapi.json).
Interactive Swagger UI
The running API also serves a live, "try it out" Swagger UI at /docs (for example http://api.localhost/docs locally), backed by the same spec at /docs/openapi.json.
RetentionPlay embed gamification / retention API: widget, progression, rewards, admin.
- Anonymous free-play — one loader script plus
project_id; no customer secret in the browser. - Session token — issued by
POST /v1/server/session-tokenwith asession:issueserver API key, then sent asAuthorization: Bearerfor play/events. - Preview — no-write previews use
GET /v1/admin/widget-previewand require an authenticated project owner with verified 2FA. - Admin JWT — from
POST /v1/admin/auth/loginfor/v1/admin/*. - Server API key —
X-PlayFlow-Server-Keyor Bearer for/v1/server/events,/v1/server/session-tokenand/v1/economy/grant.
Servers
play
Player progression & events
Operations
Dev helper: signed session token for proj_demo (disabled when ENABLE_DEMO_ENDPOINTS=0)
Issue verified player session token (API key scope session:issue)
Authorizations
Server API key scoped to the project; preferred over compatibility headers
Legacy header; Authorization Bearer or X-RetentionPlay-Server-Key also accepted
Request Body
Responses
session_token, expires_at, subject_type=verified
Ingest widget event
Server-confirmed gameplay event (e.g. streak.server_confirm)
Analytics-only business events (product_click, favorite, merchant_click, purchase)
Authorizations
Legacy header; Authorization Bearer or X-RetentionPlay-Server-Key also accepted
Parameters
Header Parameters
Request Body
Responses
Accepted (idempotent)
Current progression state
Start or resume a game run
Механика и уровень выбираются сервером; Origin должен совпадать с origin API. Повтор создавшего партию start_id разбирается до лимитов. intent=next возвращает активную партию с resumed=true. HTTP body ≤2097152байт. Ошибки JSON/Content-Type/UUID в теле: безопасный JSON validation_error с request_id (400/415/422), превышение HTTP-предела —413.
Authorizations
Platform-issued identified or anonymous player session token
Request Body
Responses
Партия начата, возвращена активная или найдена по повтору start_id
Fetch the current game run state
Чтение по механике партии, в том числе после смены механики проекта. Активная просроченная партия закрывается abandoned/expired; чтение может изменить её состояние. Origin не проверяется. Лимит 60/мин на игрока.
Authorizations
Platform-issued identified or anonymous player session token
Parameters
Path Parameters
"uuid"Responses
Актуальное состояние
Apply one game command
Origin должен совпадать с origin API. Механика берётся из партии. Match3 payload ≤512 байт под общим потолком конверта 8192 байт. Игровой отказ — HTTP 200 accepted=false. progression есть у завершающего хода уровня. Просроченная партия закрывается abandoned/expired, новая команда получает 409 run_not_active. HTTP body ≤2097152байт; сохранённый конверт command_id/sequence/action/payload ≤8192байт по Postgres jsonb::text проверяется до FraudGate. Ошибки JSON/Content-Type возвращают безопасный JSON с request_id, ошибки path UUID остаются текстовыми.
Authorizations
Platform-issued identified or anonymous player session token
Parameters
Header Parameters
Диагностическая версия клиента; не входит в payload/fingerprint и не влияет на результат. Произвольные значения не журналируются.
"^(r[0-9a-f]{12}|legacy-v1)$"Path Parameters
"uuid"Request Body
Responses
Команда обработана
Serve an uploaded project background
Lobby state for the current player
Состояние лобби одним запросом: режим показа, механика «Играть», следующий уровень, незавершённая партия и итог последней партии. Прогресс и награды не меняет; при превышении лимита сохраняется fraud flag rate_exceeded. Origin не проверяется. Лимит — 60 запросов в минуту на игрока.
Authorizations
Platform-issued identified or anonymous player session token
Responses
Состояние лобби
Player-facing reward status of a run
Статус награды за партию для показа игроку. Только владелец партии; работает и после смены механики проекта. Причины, счёт риска и срок удержания не раскрываются. Несколько заявок одной партии сводятся в один статус по приоритету pending > checking > delayed > confirmed > unavailable. Для free_play и партий без заявки — none. Прогресс и заявки не меняет; при превышении лимита сохраняется fraud flag rate_exceeded. Лимит — 30 запросов в минуту.
Authorizations
Platform-issued identified or anonymous player session token
Parameters
Path Parameters
"uuid"Responses
Статус
Обезличенная диагностика транспорта клиента
До256 байт, неизвестные поля запрещены. Origin API и действующий токен игрока. Максимум3 сообщения/мин на сессию и300 на проект. Журнал содержит только enum/status/build_version; без token/IP/player/game payload. Клиент отправляет выборку5% и не ждёт отправки. Legacy передаёт только диагностический header версии команды.
Authorizations
Platform-issued identified or anonymous player session token
Request Body
Responses
Принято
Issue origin-bound anonymous free_play session token
Widget loader script
Widget config (preview or play)
A/B exposure bucket
Play shell HTML (iframe)
Токен сессии в адресе не передаётся: окно получает его рукопожатием postMessage (retentionplay:ready -> retentionplay:bootstrap). Параметр mode обязателен.
Parameters
Query Parameters
Настоящая партия. Публичный preview запрещён (403); предпросмотр владельца — /v1/admin/widget-preview.
"play"Responses
HTML
Template UI bundle
Точка входа клиента игры
Собранный файл клиента игры
Имя файла содержит хэш содержимого, поэтому ответ кешируется на год (public, max-age=31536000, immutable). Выпуск shell/
Parameters
Path Parameters
"match3_v1"Версия старой сборки (1) или id выпуска оболочки (r + 12 hex) при game_id = shell.
"r0123456789ab""^[A-Za-z0-9_-]{1,64}$"Путь внутри сборки. Выход за её пределы запрещён.
Responses
Файл сборки
Resource balances for session user
Spend resource (booster)
Grant resource (server API key)
Authorizations
Legacy header; Authorization Bearer or X-RetentionPlay-Server-Key also accepted
Request Body
Responses
New balance
Register admin account
Admin login
Current admin profile
List own active admin sessions
Requires verified 2FA. Only own unrevoked unexpired sessions. UUID ascending pagination; refresh from the beginning to see newly created sessions. No tokens, hashes or IP addresses.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Query Parameters
15020"uuid"Responses
Active sessions page
Revoke own active admin session
Requires verified 2FA and allowed Origin for cookie callers. Revocation and safe audit commit atomically. Revoking current session clears cookies; next request requires login.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Path Parameters
"uuid"Responses
Revoked
Change password and revoke every admin session
Requires active registry session, verified 2FA and current password. Updates password and revokes all sessions in one transaction. Cookie paths are cleared; login again. Cookie callers require allowed Origin.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Request Body
Responses
Password updated; all sessions revoked
admin-projects
Projects & API keys
Operations
Предпросмотр игры владельцем проекта
Требует действующую admin-сессию, подтверждённый второй фактор и владение проектом. Браузер отправляет cookie на /v1/admin; токены в URL запрещены. CSP дополнительно разрешает ADMIN_ORIGIN только для preview. Не создаёт игровые прохождения, прогресс или награды.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Query Parameters
Обязательный режим preview.
"preview"Preview-only branding override
"#6c5ce7"Responses
HTML предпросмотра с HTTP CSP
Game template catalog with stats
List projects for account
Create project
Get project
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
Responses
project + play_settings: active_players_24h (distinct активные игроки текущей механики с активностью за 24ч, непросроченные партии), site_wheel_ready, daily_wheel_ready
Update project settings
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
Request Body
Responses
project
List API keys
Create API key (secret shown once)
Revoke API key
Embed snippet
Read published level goals of own project
Exact published level versions for Match3, Memory and Parcel Pilot; no closed run state. Legacy templates return null mechanic, empty levels and safe legacy_goals derived from the runtime defaults merged with project overrides. Wheel has no level goals.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Path Parameters
Responses
Published goals
admin-promo
Campaigns, webhooks, analytics
Operations
Event log
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
Query Parameters
"date-time""date-time"50500opaque, from a previous response's next_cursor
Responses
{events: [], next_cursor: string|null}
Export event log as CSV (streamed, unlimited rows, same filters as the list)
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
Query Parameters
"date-time""date-time"Responses
text/csv attachment, streamed; formula-injection-safe (CWE-1236)
GDPR delete player data
List campaigns
Create campaign
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
Request Body
Responses
campaign
Webhook delivery log
Retry failed webhook delivery
Resets the delivery's attempt count and backoff schedule and queues it for another attempt. Scoped to project_id: a delivery_id belonging to a different project returns 404 rather than retrying it.
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
"uuid"Responses
queued
Reveal the current webhook signing secret
The secret is never chosen by the integrator — it's derived per project from the platform's own master key and versioned. This is the only way to obtain it.
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
Responses
{ secret, version }
Rotate the webhook signing secret
Generates a new secret and increments the version. Outbound deliveries already queued re-sign with the new secret on their next attempt (they read the project's current version at send time, not a snapshot from when they were enqueued). The previous version is still accepted by the platform's own test-inbox receiver for a 24-hour grace window.
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
Responses
{ secret, version }
Send test webhook payload
Player progress per template
Dashboard metrics
A/B cohort comparison
Retention funnel start → day N → complete
Full-range daily session-start series for the dashboard chart
Authorizations
Admin JWT from signup/login
Parameters
Path Parameters
Query Parameters
7190Responses
{series: [{date, count}], delta_pct: number|null}
Start a new experiment (fresh bucket assignments going forward; past exposures kept)
Player session history
Player game runs (safe fields only, no closed engine state)
Commands (moves) recorded for one game run, scoped to the owning project
Reward claims state log
Public plan catalog
Current plan and usage
Upgrade plan
List invoices
Create Stripe Checkout session for issued invoice
Mark invoice paid (dev only, when Stripe disabled)
Stripe webhook (checkout.session.completed)
Receive a test webhook by inbox token
Локальный тестовый приёмник: секретный token принадлежит проекту. Не путь выдачи награды интегратору.
Parameters
Header Parameters
Обязателен этот заголовок или старый X-PlayFlow-Signature; HMAC по сырому телу.
Path Parameters
Responses
Successful response
Economy settings
Update economy settings
Admin grant resources to player
Fraud flags for project
admin
Admin settings and moderation
Operations
Upload the project background
Принимает multipart-поле file. Формат определяется декодированием, а не расширением: PNG, JPEG или WebP, до 5 MiB, портретное изображение от 420×760 до 2160×3840 с отношением сторон 0.50–0.65. Произвольный URL не принимается. Сервер сохраняет оригинал и непрозрачную рантайм-копию WebP 840×1520, cover по центру, q78/70/62, не более220 КиБ; слот и play_config_revision обновляются одной SQL-инструкцией. EXIF-ориентация применяется перед нормализацией; оригинальные байты сохраняются. Габариты проверяются до выделения пиксельного буфера, бюджет декодера 64 MiB. На процесс допускаются две одновременные нормализации; перегрузка возвращает 429 с Retry-After: 1.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
lobby или id механики вида run из реестра; колесо и старые шаблоны запрещены.
"lobby"Request Body
"binary"Responses
Фон сохранён
Reset the project background to the default
Снимает метаданные фона. Файл на диске остаётся; физическая уборка — отдельная задача. Слот и play_config_revision обновляются одной SQL-инструкцией.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
lobby или id механики вида run из реестра; колесо и старые шаблоны запрещены.
"lobby"Responses
Возвращён базовый фон
End the cookie admin session
Requires active registry session; atomically revokes its server record and clears both cookie paths. Cookie callers require allowed Origin.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Responses
Successful response
List current account notifications
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Query Parameters
Responses
Successful response
Search current account projects and players
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Query Parameters
Responses
Successful response
Project campaign analytics
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Responses
Successful response
Project leaderboard
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Responses
Successful response
Project fraud metrics
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Responses
Successful response
Read player fraud status
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Responses
Successful response
Set player fraud status
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Request Body
Responses
Successful response
Resolve a fraud flag
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Request Body
Responses
Successful response
Release a held or reviewed reward claim
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Responses
Successful response
Reject a held or reviewed reward claim
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Request Body
Responses
Successful response
Read project test webhook inbox
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Responses
Successful response
Clear project test webhook inbox
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Responses
Successful response
Rotate project test inbox token
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Responses
Successful response
Update a campaign
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Parameters
Path Parameters
Request Body
Responses
Successful response
Read account two-factor status
Begin TOTP enrollment
Confirm TOTP enrollment
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Request Body
Responses
Successful response
Verify TOTP or recovery code
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Request Body
Responses
Successful response
Sign in using a one-time recovery code
Authorizations
Admin JWT from signup/login
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Request Body
Responses
Successful response
wheel
Server-computed Reward Wheel R1
Operations
Read published R1 wheel
30 reads/minute/player. Anonymous sessions can use only free-play. no-store response.
Authorizations
Platform-issued identified or anonymous player session token
Parameters
Query Parameters
"daily""site""daily"Responses
JSON response; see /integration/wheel
Draw and persist one R1 spin
512-byte body ceiling. Exact durable spin_id replay before quotas; new spins 6/minute and 30/hour/player plus daily entitlements. R1 tickets/resources only, no material prizes.
Authorizations
Platform-issued identified or anonymous player session token
Parameters
Header Parameters
Admin site origin for cookie writes; API origin for public writes
Request Body
Responses
JSON response; see /integration/wheel
Read owned spin
Only this project/player can read or acknowledge the spin. 30 reads/minute/player.
Authorizations
Platform-issued identified or anonymous player session token
Parameters
Path Parameters
"uuid"Responses
JSON response; see /integration/wheel
Acknowledge result (idempotent)
Only this project/player can read or acknowledge the spin. 30 reads/minute/player.
Authorizations
Platform-issued identified or anonymous player session token
Parameters
Header Parameters
Admin site origin for cookie writes; API origin for public writes
Path Parameters
"uuid"Responses
JSON response; see /integration/wheel
Built-in wheel SVG icon
GET wheel settings
Authenticated project owner with verified 2FA. Simulation draws 10000 results and creates no award. Published weights are not in public views.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Path Parameters
Responses
JSON response; see /integration/wheel
PUT wheel settings
Authenticated project owner with verified 2FA. Simulation draws 10000 results and creates no award. Published weights are not in public views.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Header Parameters
Admin site origin for cookie writes; API origin for public writes
Path Parameters
Request Body
Responses
JSON response; see /integration/wheel
GET wheel draft
Authenticated project owner with verified 2FA. Simulation draws 10000 results and creates no award. Published weights are not in public views.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Path Parameters
"daily""site"Responses
JSON response; see /integration/wheel
PUT wheel draft
Authenticated project owner with verified 2FA. Simulation draws 10000 results and creates no award. Published weights are not in public views.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Header Parameters
Admin site origin for cookie writes; API origin for public writes
Path Parameters
"daily""site"Request Body
Responses
JSON response; see /integration/wheel
POST wheel publish
Authenticated project owner with verified 2FA. Simulation draws 10000 results and creates no award. Published weights are not in public views.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Header Parameters
Admin site origin for cookie writes; API origin for public writes
Path Parameters
"daily""site"Request Body
Responses
JSON response; see /integration/wheel
POST wheel simulate
Authenticated project owner with verified 2FA. Simulation draws 10000 results and creates no award. Published weights are not in public views.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Header Parameters
Admin site origin for cookie writes; API origin for public writes
Path Parameters
"daily""site"Responses
JSON response; see /integration/wheel
GET wheel stats
Authenticated project owner with verified 2FA. Simulation draws 10000 results and creates no award. Published weights are not in public views.
Authorizations
HttpOnly сессия админки. Изменяющие запросы с cookie требуют допустимый Origin; Bearer — альтернатива.
Admin JWT from signup/login
Parameters
Path Parameters
"daily""site"Responses
JSON response; see /integration/wheel