Tole.
Регистрация
Agent-ready · integration briefОбновлено под API v1

Дайте агенту контекст — получите рабочую интеграцию

Готовое задание фиксирует контракт, безопасность, расписания автосчетов, неизвестный результат и проверку вебхука. Агенту не придётся угадывать API.

Открыть raw MarkdownOpenAPI 3.1Открыть кабинет

Скопируйте задание целиком

Вставьте его в Codex, Claude Code, Cursor или другого агента внутри нужного репозитория. Агент сначала изучит стек, затем встроит Tole в существующую архитектуру.

Задание намеренно на английском: технические имена совпадают с OpenAPI, и меньше риск исказить поля при генерации кода.

Agent integration brief
Integrate Tole Payments API into this codebase.

Authoritative contract:
- OpenAPI 3.1: https://api.tolepay.kz/v1/openapi.json
- Human guide: https://tolepay.kz/ru/docs
- Raw agent guide: https://tolepay.kz/for-ai.md
- Base URL: https://api.tolepay.kz/v1

Before editing code:
1. Inspect the repository stack, existing HTTP client, env conventions, persistence, background jobs, and test setup.
2. Read the current OpenAPI document. Do not invent fields, SDKs, routes, statuses, or webhook events.
3. Keep all Tole credentials server-side. Add TOLE_API_KEY and optional TOLE_CONNECTION_ID to the existing secret/env system; never expose them to browser bundles or logs.

Implementation requirements:
1. Create a small typed Tole adapter around the repository's existing HTTP client. Use Authorization: Bearer <tole_sk_...>, Content-Type: application/json, and X-Tole-Connection-Id when configured.
2. Implement the requested invoice, QR, or recurring-invoice flow using the exact OpenAPI schemas. For every idempotent mutation send a stable Idempotency-Key derived from the local business operation ID, not a random key generated on each retry.
3. Persist Tole's local resource id and commandId. For recurring invoices also persist recurringInvoiceId, occurrenceId, and the generated paymentIntentId when present. Never treat a private Kaspi identifier as a public operationId.
4. Handle 200/201 as complete. On 202 in_progress, honor Retry-After and poll Location or GET /commands/{commandId}. On 202 outcome_unknown, never auto-repeat the mutation; reconcile command and payment-intent state.
5. Implement webhook verification over the exact raw request body before JSON parsing: v1=hex(HMAC-SHA256(secret, "<webhook-id>.<webhook-timestamp>.<exact_body>")). Reject invalid signatures, guard timestamp replay, deduplicate webhook-id, persist before processing, and return 2xx only after durable acceptance.
6. Use bounded timeouts. Retry safe reads with exponential backoff. Do not blindly retry payment mutations, 4xx responses, or unknown outcomes.
7. Add structured redacted logs. Never log API keys, webhook secrets, phone numbers, raw provider payloads, QR tokens, or payment URLs.
8. If recurring invoices are requested, model them as automatic invoice issuance, never as an automatic charge. Use a typed monthly, interval, weekly, or once schedule plus an IANA timezone; preview upcoming runs before create/update. Retry delays apply only when Tole could not issue the invoice. Never create a replacement merely because an issued invoice is unpaid, and never retry an outcome_unknown occurrence.
9. Add tests for success, validation error, 401/403, 409 idempotency or revision conflict, 429 Retry-After, 202 in_progress, 202 outcome_unknown, webhook valid/invalid signature, duplicate event, and timeout. Recurring flows also need timezone, short-month, pause/resume, missed-run, retry, and duplicate-occurrence tests.
10. Exercise immediate payment flows against /v1/sandbox/* with a test API key and required X-Tole-Connection-Id before enabling live mode. Recurring invoices are live-only until OpenAPI explicitly documents a sandbox mirror; do not invent one or simulate success inside production code.

Deliverables:
- production adapter and domain mapping;
- environment-variable documentation without real secrets;
- webhook endpoint and signature verification;
- automated tests and a copy-pasteable sandbox smoke command for supported immediate payment routes;
- for recurring invoices: a human-readable schedule summary, previewed next runs, lifecycle controls, and occurrence-to-payment correlation;
- a short handoff listing changed files, test results, and any remaining live-only verification.

If a required credential, connection ID, webhook URL, timezone, or business mapping is missing, finish all safe local work first and then ask for only that missing value. Never ask the user to paste a secret into chat.

Карта контракта

Эти правила должны оставаться истинными в любой реализации.

Серверная авторизация

Bearer-ключ tole_sk_* никогда не попадает в клиентский JavaScript.

Стабильная идемпотентность

Одна бизнес-операция всегда использует один Idempotency-Key, включая сетевой retry.

Автосчёт — не списание

Расписание выставляет обычный счёт; клиент сам решает, оплачивать его или нет.

202 — не успех и не отказ

in_progress опрашивается, outcome_unknown не повторяется автоматически.

Raw body вебхука

HMAC считается до JSON.parse; event id обрабатывается идемпотентно.

Сначала sandbox

Test key и sandbox connection изолированы от live Kaspi; автосчета остаются live-only до появления контракта.

Никаких provider ID

Интеграция хранит публичные UUID Tole и не угадывает внутренние поля Kaspi.

Что подготовить до запуска агента

Секреты не нужно вставлять в промпт. Положите их в локальное защищённое окружение проекта.

  • Test API key в переменной TOLE_API_KEY.
  • UUID sandbox-подключения в TOLE_CONNECTION_ID.
  • Публичный HTTPS URL будущего webhook endpoint.
  • Локальный ID заказа/платежа, из которого строится стабильный Idempotency-Key.
  • Решение, что интегрируем первым: счёт, QR или live-автосчёт.
  • Для автосчёта: IANA timezone, правило расписания и политика технических повторов.

Не передавайте агенту live-ключ через чат. Агент должен читать значение только из env/secret manager и использовать замаскированный placeholder в коде, тестах и документации.

Когда интеграция действительно готова

Попросите агента завершить работу только после этих проверок.

  • Sandbox mutation создаёт ресурс и сохраняет id + commandId.
  • Повтор с тем же business ID не создаёт второй платёж.
  • 202 in_progress соблюдает Retry-After; outcome_unknown не вызывает повторную mutation.
  • Автосчёт показывает preview дат, сохраняет recurringInvoiceId/occurrenceId и не повторяет уже выставленный неоплаченный счёт.
  • Валидный webhook принимается, невалидная подпись отклоняется, дубль event id безопасен.
  • Секреты и чувствительные payload отсутствуют в git diff, browser bundle и логах.
  • Тесты проходят; live Kaspi acceptance явно отмечен отдельным шагом, если не выполнялся.

Источники, которые агент должен читать

Написать в WhatsApp