Quickstart
Base URL: https://api.tolepay.kz/v1. Start with a test key and /sandbox, which never sends requests to Kaspi.
Create a sandbox connection
Open API keys → Create test key in the dashboard. The connection is prepared automatically; no Kaspi connection or paid subscription is required.
Create a test API key
Choose a permission preset or customize it. Save the key, connection ID and ready-to-use requests. No JWT needed; GET /api-key describes permissions and connections.
Create an invoice or QR
Send the Bearer key, X-Tole-Connection-Id, and a unique Idempotency-Key.
Simulate payment
Call simulate with paid and verify your webhook handler.
Switch to live
Replace test credentials and /sandbox routes with live equivalents. Test IDs never cross environments.
Authentication and common headers
Call payment endpoints from your backend only. Never expose tole_sk_* in a browser, mobile app, public repository, or frontend logs.
Authorization
Required. Bearer tole_sk_live_v1… for live or Bearer tole_sk_test_v1… for sandbox.
Content-Type
application/json for requests with a body.
X-Tole-Connection-Id
Connection UUID. Optional in live when a default exists; always required in sandbox.
Idempotency-Key
Required for create/cancel/refund. One business request must keep one key.
Permissions are checked for the selected connection. A grant for another connection gives no access. Wildcards are unsupported.
120 / min
GET и provider reads
60 / min
client-info
30 / min
create, cancel, refund
Live payment API
Append every path to https://api.tolepay.kz/v1. operationId and paymentIntentId are owner-scoped Tole UUIDs, never private Kaspi identifiers.
POST/invoices/client-infoValidate an invoice recipient
Checks whether Kaspi can invoice the number. Customer name and full phone are never returned.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
phoneNumber | body | string | Yes | Kazakhstan phone: +7 followed by 10 digits. |
Safe fields may include available, canCreateInvoice, eligible, exists, isAvailable, and status.
curl https://api.tolepay.kz/v1/invoices/client-info \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"phoneNumber":"+77001234567"}'{
"ok": true,
"data": { "eligible": true }
}POST/invoicesCreate a phone-number invoice
Creates a live Kaspi invoice. data.id is the local Tole UUID for follow-up requests.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
Idempotency-Key | header | string | Yes | Unique mutation key. Retry the same request with the same key. |
phoneNumber | body | string | Yes | +7 followed by 10 digits. |
amount | body | integer | Yes | Amount in KZT: 1–100,000,000. |
comment | body | string | No | Optional, up to 200 characters. |
receiptUrl and orderNumber are optional and appear only when Kaspi returned valid values.
curl https://api.tolepay.kz/v1/invoices \
-X POST \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1024-invoice-v1" \
-d '{"phoneNumber":"+77001234567","amount":5000,"comment":"Order 1024"}'{
"ok": true,
"data": {
"id": "d7dfb407-0e4c-4cc2-9d31-26d9f696cb27",
"kind": "invoice",
"status": "created",
"amount": 5000,
"clientPhoneLast4": "4567",
"receiptUrl": "https://…",
"orderNumber": "…"
},
"commandId": "d7dfb407-0e4c-4cc2-9d31-26d9f696cb27",
"replayed": false
}GET/invoices/historyList invoice history
Returns sanitized invoice history for the selected connection.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
Provider fields are filtered; private Kaspi IDs become local operationId values.
curl https://api.tolepay.kz/v1/invoices/history \
-H "Authorization: Bearer $TOLE_API_KEY"{
"ok": true,
"data": { "items": [{ "operationId": "uuid", "amount": 5000, "status": "Processed", "date": "…" }] }
}GET/invoices/{operationId}Get invoice details
Reads current provider details and updates observed payment-intent status.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
operationId | path | uuid | Yes | Owner-scoped local Tole operation UUID. |
curl https://api.tolepay.kz/v1/invoices/$OPERATION_ID \
-H "Authorization: Bearer $TOLE_API_KEY"{
"ok": true,
"data": { "amount": 5000, "currency": "KZT", "status": "Processed" }
}POST/invoices/{operationId}/cancelCancel an invoice
Cancels a created invoice. Body must be an empty JSON object.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
Idempotency-Key | header | string | Yes | Unique mutation key. Retry the same request with the same key. |
operationId | path | uuid | Yes | Owner-scoped local Tole operation UUID. |
curl https://api.tolepay.kz/v1/invoices/$OPERATION_ID/cancel \
-X POST \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1024-cancel-v1" \
-d '{}'{
"ok": true,
"data": { "operationId": "uuid", "status": "cancelled" },
"commandId": "uuid",
"replayed": false
}POST/qrCreate a dynamic QR
Creates a payment QR and returns paymentUrl plus the original qrToken.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
Idempotency-Key | header | string | Yes | Unique mutation key. Retry the same request with the same key. |
amount | body | integer | Yes | KZT amount: 1–100,000,000. |
latitude | body | number | No | Optional, −90…90; only with longitude. |
longitude | body | number | No | Optional, −180…180; only with latitude. |
expiresAt and receiptUrl are optional. paymentUrl and qrToken are always HTTPS.
curl https://api.tolepay.kz/v1/qr \
-X POST \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-1024-qr-v1" \
-d '{"amount":5000}'{
"ok": true,
"data": {
"id": "uuid", "kind": "qr", "status": "created", "amount": 5000,
"paymentUrl": "https://…", "qrToken": "https://qr.kaspi.kz/…",
"expiresAt": "…", "receiptUrl": "https://…"
},
"commandId": "uuid",
"replayed": false
}GET/qr/{operationId}Get QR details
Reads current QR status from the provider.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
operationId | path | uuid | Yes | Owner-scoped local Tole operation UUID. |
curl https://api.tolepay.kz/v1/qr/$OPERATION_ID \
-H "Authorization: Bearer $TOLE_API_KEY"{
"ok": true,
"data": { "amount": 5000, "currency": "KZT", "status": "Processed" }
}GET/history/operationsList payment operations
History through the specified UTC date with an optional next-page cursor.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
endDate | query | date | Yes | Required: YYYY-MM-DD, inclusive UTC. |
lastTransactionDate | query | string | No | Cursor from the previous response. |
statementPeriodCode | query | integer | No | Non-negative statement-period code. |
curl "https://api.tolepay.kz/v1/history/operations?endDate=2026-08-23" \
-H "Authorization: Bearer $TOLE_API_KEY"{
"ok": true,
"data": {
"items": [{ "operationId": "uuid", "amount": 5000, "type": "Payment", "status": "Processed" }],
"lastTransactionDate": "…", "hasMore": false
}
}GET/history/operations/{operationId}Get a payment operation
Sanitized operation details by local UUID.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
operationId | path | uuid | Yes | Owner-scoped local Tole operation UUID. |
operationMethod | query | integer | No | Optional non-negative method code. |
curl "https://api.tolepay.kz/v1/history/operations/$OPERATION_ID?operationMethod=0" \
-H "Authorization: Bearer $TOLE_API_KEY"{
"ok": true,
"data": { "operationId": "uuid", "amount": 5000, "status": "Processed" }
}POST/refundsCreate a refund
Full or partial refund of a paid remote invoice or QR on the selected connection.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
Idempotency-Key | header | string | Yes | Unique mutation key. Retry the same request with the same key. |
operationId | body | uuid | Yes | Local invoice/QR payment-intent UUID. |
returnAmount | body | integer | Yes | KZT, not above the refundable balance. |
curl https://api.tolepay.kz/v1/refunds \
-X POST \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: refund-order-1024-v1" \
-d '{"operationId":"uuid","returnAmount":1500}'{
"ok": true,
"data": { "operationId": "uuid", "status": "refund_accepted", "returnAmount": 1500 },
"commandId": "uuid", "replayed": false
}GET/payment-intents/invoices/{paymentIntentId}Get durable invoice status
Reads durable Tole ledger state for reconciliation.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
paymentIntentId | path | uuid | Yes | Tole payment intent UUID. |
curl https://api.tolepay.kz/v1/payment-intents/invoices/$PAYMENT_INTENT_ID \
-H "Authorization: Bearer $TOLE_API_KEY"{
"ok": true,
"data": {
"id": "uuid", "kind": "invoice", "status": "paid", "amount": 5000,
"refundedAmount": 0, "currency": "KZT", "revision": 3,
"source": "scheduled_invoice", "recurringInvoiceId": "uuid",
"occurrenceId": "uuid", "attemptNumber": 1,
"createdAt": "2026-08-23T10:00:00.000Z", "updatedAt": "2026-08-23T10:01:00.000Z",
"paidAt": "2026-08-23T10:01:00.000Z", "terminalAt": null, "lastReconciledAt": "…"
}
}GET/payment-intents/qr/{paymentIntentId}Get durable QR status
Durable payment-intent contract for QR.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
paymentIntentId | path | uuid | Yes | Tole payment intent UUID. |
curl https://api.tolepay.kz/v1/payment-intents/qr/$PAYMENT_INTENT_ID \
-H "Authorization: Bearer $TOLE_API_KEY"{
"ok": true,
"data": {
"id": "uuid", "kind": "qr", "status": "pending", "amount": 5000,
"currency": "KZT", "revision": 1, "source": null,
"recurringInvoiceId": null, "occurrenceId": null, "attemptNumber": null
}
}GET/commands/{commandId}Get idempotent command status
Checks create/cancel/refund after a 202, network interruption, or retry.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
commandId | path | uuid | Yes | UUID from commandId or Location. |
The command resolves connection and permission. A foreign commandId returns 404.
curl https://api.tolepay.kz/v1/commands/$COMMAND_ID \
-H "Authorization: Bearer $TOLE_API_KEY"{
"ok": true,
"data": {
"commandId": "uuid", "status": "succeeded", "responseStatus": 201,
"result": { "ok": true, "data": { "id": "uuid" }, "commandId": "uuid" },
"updatedAt": "2026-08-23T10:00:01.000Z"
}
}Auto-invoices
An auto-invoice automatically issues a regular Kaspi remote invoice from a typed schedule. It is not an automatic charge: the customer still decides whether to pay.
A rule stores a concrete connectionId, phone number, amount, comment, timezone, completion limits, and retry policy. API-key responses expose only phoneLast4 and commentPresent; the full phone and comment are available to the owner through the dashboard JWT API only.
/recurring-invoices/previewAPI key · Следующие 1–20 запусков; ничего не сохраняет
/recurring-invoicesrecurring_invoice:create + invoice:create · Создать правило · Idempotency-Key
/recurring-invoicesrecurring_invoice:read · Правила всех доступных connections
/recurring-invoices/{recurringInvoiceId}recurring_invoice:read · Безопасная проекция правила
/recurring-invoices/{recurringInvoiceId}recurring_invoice:update + invoice:create · Изменить только будущие запуски
/recurring-invoices/{recurringInvoiceId}/pauserecurring_invoice:update · Приостановить будущие запуски
/recurring-invoices/{recurringInvoiceId}/resumerecurring_invoice:update + invoice:create · Возобновить расписание и перепривязать execution key
/recurring-invoices/{recurringInvoiceId}/runrecurring_invoice:trigger + invoice:create · Поставить run-now в очередь · Idempotency-Key
/recurring-invoices/{recurringInvoiceId}?expectedRevision=Nrecurring_invoice:delete · Архивировать, сохранив историю
/recurring-invoices/{recurringInvoiceId}/occurrencesrecurring_invoice:read · Список запусков
/recurring-invoices/{recurringInvoiceId}/occurrences/{occurrenceId}recurring_invoice:read · Запуск и его attempts
A schedule without cron
Send monthly, interval, weekly, or once plus an IANA timezone. HH:mm and YYYY-MM-DDTHH:mm are wall-clock values in that zone; preview returns UTC instants for human display.
// Каждый месяц 27-го числа в 10:00
{"kind":"monthly","dayOfMonth":27,"time":"10:00","shortMonthPolicy":"last_day"}
// Каждые две недели с локальной точки отсчёта
{"kind":"interval","every":2,"unit":"week","anchorAt":"2026-09-01T09:30"}
// Каждые десять дней
{"kind":"interval","every":10,"unit":"day","anchorAt":"2026-09-01T10:00"}
// Каждый понедельник и пятницу в 09:00
{"kind":"weekly","everyWeeks":1,"weekdays":[1,5],"time":"09:00"}
// Один раз в локальном времени правила
{"kind":"once","runAt":"2026-09-01T10:00"}weekdays uses ISO numbering: Monday = 1 and Sunday = 7. A weekly response includes a stable local anchorDate in YYYY-MM-DD format; preserve it when editing an every-N-weeks cadence. For days 29–31, last_day moves the run to the short month's final day, while skip omits that month. anchorAt and runAt use strict YYYY-MM-DDTHH:mm wall-clock values without seconds or an offset.
POST/recurring-invoices/previewPreview a schedule
Calculates the next 1–20 UTC instants without saving a rule or contacting Kaspi.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
schedule | body | monthly | interval | weekly | once | Yes | Typed schedule; cron strings are not accepted. |
timezone | body | IANA timezone | Yes | For example, Asia/Almaty. |
startsAt | body | RFC 3339 date-time | No | Optional lower schedule boundary. |
endsAt | body | RFC 3339 date-time | No | Optional upper schedule boundary. |
count | body | integer 1..20 | No | Number of dates; defaults to 5. |
The response contains UTC instants. Display them in the rule's timezone.
curl https://api.tolepay.kz/v1/recurring-invoices/preview \
-X POST \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"schedule":{"kind":"monthly","dayOfMonth":27,"time":"10:00","shortMonthPolicy":"last_day"},
"timezone":"Asia/Almaty","count":5
}'{
"nextRuns": [
"2026-09-27T05:00:00.000Z",
"2026-10-27T05:00:00.000Z"
]
}POST/recurring-invoicesCreate an auto-invoice
Creates a durable rule and permanently binds it to the currently selected live connection.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | No | Live connection UUID; optional when a default connection is configured. |
Idempotency-Key | header | string | Yes | Unique mutation key. Retry the same request with the same key. |
name | body | string 1..100 | Yes | Human-readable internal name. |
phoneNumber | body | string | Yes | Kazakhstan phone: +7/7 followed by 10 digits. |
amount | body | integer 1..100000000 | Yes | Amount of each invoice in KZT. |
comment | body | string <= 200 | No | Optional comment for the regular Kaspi remote invoice. |
schedule | body | schedule union | Yes | monthly | interval | weekly | once. |
timezone | body | IANA timezone | Yes | Timezone used by schedule wall-clock fields. |
startsAt / endsAt | body | RFC 3339 date-time | No | Optional execution window. |
maxOccurrences | body | integer 1..100000 | No | Optional maximum execution count. |
retryPolicy | body | { delays: ISO duration[] } | No | Up to five delays in the exact supplied order; each PT1S..P30D. |
misfirePolicy | body | run_once | skip | No | Defaults to run_once. |
Without the header, the server resolves and stores the default UUID once. Changing the default never moves an existing rule.
curl https://api.tolepay.kz/v1/recurring-invoices \
-X POST \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Idempotency-Key: customer-42-monthly-v1" \
-H "Content-Type: application/json" \
-d '{
"name":"Ежемесячная подписка","phoneNumber":"77001234567","amount":15000,
"comment":"За сентябрь",
"schedule":{"kind":"monthly","dayOfMonth":27,"time":"10:00","shortMonthPolicy":"last_day"},
"timezone":"Asia/Almaty","retryPolicy":{"delays":["PT6H","PT1H","PT15M"]},
"misfirePolicy":"run_once"
}'{
"id": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"name": "Ежемесячная подписка",
"phoneLast4": "4567",
"amount": 15000,
"commentPresent": true,
"connectionId": "7a67d6bd-5daf-47af-b899-fdb8b7db4d63",
"schedule": {
"kind": "monthly", "dayOfMonth": 27, "time": "10:00",
"shortMonthPolicy": "last_day"
},
"timezone": "Asia/Almaty",
"startsAt": null,
"endsAt": null,
"maxOccurrences": null,
"occurrenceCount": 0,
"nextRunAt": "2026-09-27T05:00:00.000Z",
"status": "active",
"misfirePolicy": "run_once",
"retryPolicy": { "delays": ["PT6H", "PT1H", "PT15M"] },
"revision": 1,
"lastRunAt": null,
"createdAt": "2026-08-24T10:00:00.000Z",
"updatedAt": "2026-08-24T10:00:00.000Z",
"archivedAt": null
}GET/recurring-invoicesList auto-invoice rules
Returns rules across all connections where the key has a read grant. Archived rules are excluded unless status=archived is explicit.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
cursor | query | string | No | Opaque cursor from the previous page. |
limit | query | integer 1..100 | No | Page size. |
status | query | rule status | No | Optional status filter. |
curl "https://api.tolepay.kz/v1/recurring-invoices?limit=20&status=active" \
-H "Authorization: Bearer $TOLE_API_KEY"{
"recurringInvoices": [{
"id": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"name": "Ежемесячная подписка",
"phoneLast4": "4567",
"amount": 15000,
"commentPresent": true,
"connectionId": "7a67d6bd-5daf-47af-b899-fdb8b7db4d63",
"schedule": {
"kind": "monthly", "dayOfMonth": 27, "time": "10:00",
"shortMonthPolicy": "last_day"
},
"timezone": "Asia/Almaty",
"startsAt": null,
"endsAt": null,
"maxOccurrences": null,
"occurrenceCount": 0,
"nextRunAt": "2026-09-27T05:00:00.000Z",
"status": "active",
"misfirePolicy": "run_once",
"retryPolicy": { "delays": ["PT6H", "PT1H", "PT15M"] },
"revision": 1,
"lastRunAt": null,
"createdAt": "2026-08-24T10:00:00.000Z",
"updatedAt": "2026-08-24T10:00:00.000Z",
"archivedAt": null
}],
"nextCursor": null
}GET/recurring-invoices/{recurringInvoiceId}Get an auto-invoice rule
Returns a masked projection without the full phone number or comment text.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
recurringInvoiceId | path | uuid | Yes | Owner-scoped recurring-invoice rule UUID. |
curl https://api.tolepay.kz/v1/recurring-invoices/$RECURRING_INVOICE_ID \
-H "Authorization: Bearer $TOLE_API_KEY"{
"id": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"name": "Ежемесячная подписка",
"phoneLast4": "4567",
"amount": 15000,
"commentPresent": true,
"connectionId": "7a67d6bd-5daf-47af-b899-fdb8b7db4d63",
"schedule": {
"kind": "monthly", "dayOfMonth": 27, "time": "10:00",
"shortMonthPolicy": "last_day"
},
"timezone": "Asia/Almaty",
"startsAt": null,
"endsAt": null,
"maxOccurrences": null,
"occurrenceCount": 0,
"nextRunAt": "2026-09-27T05:00:00.000Z",
"status": "active",
"misfirePolicy": "run_once",
"retryPolicy": { "delays": ["PT6H", "PT1H", "PT15M"] },
"revision": 1,
"lastRunAt": null,
"createdAt": "2026-08-24T10:00:00.000Z",
"updatedAt": "2026-08-24T10:00:00.000Z",
"archivedAt": null
}PATCH/recurring-invoices/{recurringInvoiceId}Update future executions
Updates future configuration only; existing occurrences and payment intents are never rewritten.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
recurringInvoiceId | path | uuid | Yes | Owner-scoped recurring-invoice rule UUID. |
expectedRevision | body | integer >= 1 | Yes | Revision from the latest GET; prevents lost updates. |
изменяемые поля | body | partial create body | No | At least one field besides expectedRevision. null clears comment, startsAt, endsAt, maxOccurrences, or retryPolicy. |
A stale revision returns 409 RECURRING_INVOICE_CONCURRENT_MODIFICATION. Re-read the rule and reapply the decision to the fresh version.
curl https://api.tolepay.kz/v1/recurring-invoices/$RECURRING_INVOICE_ID \
-X PATCH \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"expectedRevision":1,"amount":17500,"retryPolicy":null}'{
"id": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"name": "Ежемесячная подписка",
"phoneLast4": "4567",
"amount": 15000,
"commentPresent": true,
"connectionId": "7a67d6bd-5daf-47af-b899-fdb8b7db4d63",
"schedule": {
"kind": "monthly", "dayOfMonth": 27, "time": "10:00",
"shortMonthPolicy": "last_day"
},
"timezone": "Asia/Almaty",
"startsAt": null,
"endsAt": null,
"maxOccurrences": null,
"occurrenceCount": 0,
"nextRunAt": "2026-09-27T05:00:00.000Z",
"status": "active",
"misfirePolicy": "run_once",
"retryPolicy": { "delays": ["PT6H", "PT1H", "PT15M"] },
"revision": 1,
"lastRunAt": null,
"createdAt": "2026-08-24T10:00:00.000Z",
"updatedAt": "2026-08-24T10:00:00.000Z",
"archivedAt": null
}POST/recurring-invoices/{recurringInvoiceId}/pausePause a rule
Stops future scheduled executions without deleting history.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
recurringInvoiceId | path | uuid | Yes | Owner-scoped recurring-invoice rule UUID. |
expectedRevision | body | integer >= 1 | Yes | Must match the current revision. |
curl https://api.tolepay.kz/v1/recurring-invoices/$RECURRING_INVOICE_ID/pause \
-X POST -H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" -d '{"expectedRevision":1}'{
"id": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"name": "Ежемесячная подписка",
"phoneLast4": "4567",
"amount": 15000,
"commentPresent": true,
"connectionId": "7a67d6bd-5daf-47af-b899-fdb8b7db4d63",
"schedule": {
"kind": "monthly", "dayOfMonth": 27, "time": "10:00",
"shortMonthPolicy": "last_day"
},
"timezone": "Asia/Almaty",
"startsAt": null,
"endsAt": null,
"maxOccurrences": null,
"occurrenceCount": 0,
"nextRunAt": "2026-09-27T05:00:00.000Z",
"status": "active",
"misfirePolicy": "run_once",
"retryPolicy": { "delays": ["PT6H", "PT1H", "PT15M"] },
"revision": 1,
"lastRunAt": null,
"createdAt": "2026-08-24T10:00:00.000Z",
"updatedAt": "2026-08-24T10:00:00.000Z",
"archivedAt": null
}POST/recurring-invoices/{recurringInvoiceId}/resumeResume a rule
Resumes scheduling under the selected misfire policy.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
recurringInvoiceId | path | uuid | Yes | Owner-scoped recurring-invoice rule UUID. |
expectedRevision | body | integer >= 1 | Yes | Must match the current revision. |
curl https://api.tolepay.kz/v1/recurring-invoices/$RECURRING_INVOICE_ID/resume \
-X POST -H "Authorization: Bearer $TOLE_API_KEY" \
-H "Content-Type: application/json" -d '{"expectedRevision":2}'{
"id": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"name": "Ежемесячная подписка",
"phoneLast4": "4567",
"amount": 15000,
"commentPresent": true,
"connectionId": "7a67d6bd-5daf-47af-b899-fdb8b7db4d63",
"schedule": {
"kind": "monthly", "dayOfMonth": 27, "time": "10:00",
"shortMonthPolicy": "last_day"
},
"timezone": "Asia/Almaty",
"startsAt": null,
"endsAt": null,
"maxOccurrences": null,
"occurrenceCount": 0,
"nextRunAt": "2026-09-27T05:00:00.000Z",
"status": "active",
"misfirePolicy": "run_once",
"retryPolicy": { "delays": ["PT6H", "PT1H", "PT15M"] },
"revision": 1,
"lastRunAt": null,
"createdAt": "2026-08-24T10:00:00.000Z",
"updatedAt": "2026-08-24T10:00:00.000Z",
"archivedAt": null
}POST/recurring-invoices/{recurringInvoiceId}/runQueue an immediate execution
Creates a durable occurrence and responds before contacting Kaspi. It issues an invoice now; it does not charge money.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
Idempotency-Key | header | string | Yes | Unique mutation key. Retry the same request with the same key. |
recurringInvoiceId | path | uuid | Yes | Owner-scoped recurring-invoice rule UUID. |
expectedRevision | body | integer >= 1 | No | Optional CAS: create the run only for the rule revision you read. |
Location points to the occurrence. Until a response is confirmed, retry the same run with the same key: a refreshed expectedRevision does not change the semantic request and replays the original occurrence if the first request committed.
curl https://api.tolepay.kz/v1/recurring-invoices/$RECURRING_INVOICE_ID/run \
-X POST \
-H "Authorization: Bearer $TOLE_API_KEY" \
-H "Idempotency-Key: customer-42-run-2026-09-01" \
-H "Content-Type: application/json" -d '{"expectedRevision":3}'{
"id": "b83a52dd-4578-44d9-80a0-b0a1b821fd4d",
"recurringInvoiceId": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"scheduledFor": "2026-09-27T05:00:00.000Z",
"status": "pending",
"attemptCount": 0,
"nextAttemptAt": null,
"paymentIntentId": null,
"commandId": null,
"lastFailureCode": null,
"createdAt": "2026-09-27T05:00:00.000Z",
"updatedAt": "2026-09-27T05:00:00.000Z",
"completedAt": null
}DELETE/recurring-invoices/{recurringInvoiceId}?expectedRevision=NArchive a rule
Stops new and queued runs while retaining audit, occurrences, and payments. An already-started Kaspi attempt is not cancelled and may finish after archival.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
recurringInvoiceId | path | uuid | Yes | Owner-scoped recurring-invoice rule UUID. |
expectedRevision | query | integer >= 1 | Yes | Query only; DELETE has no body. |
Check history after archival: an already-processing attempt may finish or require reconciliation under needs_attention.
curl "https://api.tolepay.kz/v1/recurring-invoices/$RECURRING_INVOICE_ID?expectedRevision=3" \
-X DELETE -H "Authorization: Bearer $TOLE_API_KEY"{
"id": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"name": "Ежемесячная подписка",
"phoneLast4": "4567",
"amount": 15000,
"commentPresent": true,
"connectionId": "7a67d6bd-5daf-47af-b899-fdb8b7db4d63",
"schedule": {
"kind": "monthly", "dayOfMonth": 27, "time": "10:00",
"shortMonthPolicy": "last_day"
},
"timezone": "Asia/Almaty",
"startsAt": null,
"endsAt": null,
"maxOccurrences": null,
"occurrenceCount": 0,
"nextRunAt": "2026-09-27T05:00:00.000Z",
"status": "active",
"misfirePolicy": "run_once",
"retryPolicy": { "delays": ["PT6H", "PT1H", "PT15M"] },
"revision": 1,
"lastRunAt": null,
"createdAt": "2026-08-24T10:00:00.000Z",
"updatedAt": "2026-08-24T10:00:00.000Z",
"archivedAt": null
}GET/recurring-invoices/{recurringInvoiceId}/occurrencesList executions
Returns scheduled, processing, retrying, and completed occurrences.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
recurringInvoiceId | path | uuid | Yes | Owner-scoped recurring-invoice rule UUID. |
cursor | query | string | No | Opaque cursor. |
limit | query | integer 1..100 | No | Page size. |
status | query | occurrence status | No | Optional filter. |
curl "https://api.tolepay.kz/v1/recurring-invoices/$RECURRING_INVOICE_ID/occurrences?limit=20" \
-H "Authorization: Bearer $TOLE_API_KEY"{
"occurrences": [{
"id": "b83a52dd-4578-44d9-80a0-b0a1b821fd4d",
"recurringInvoiceId": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"scheduledFor": "2026-09-27T05:00:00.000Z",
"status": "pending",
"attemptCount": 0,
"nextAttemptAt": null,
"paymentIntentId": null,
"commandId": null,
"lastFailureCode": null,
"createdAt": "2026-09-27T05:00:00.000Z",
"updatedAt": "2026-09-27T05:00:00.000Z",
"completedAt": null
}],
"nextCursor": null
}GET/recurring-invoices/{recurringInvoiceId}/occurrences/{occurrenceId}Get an execution and its attempts
Adds technical attempts to the occurrence projection for diagnostics and reconciliation.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
recurringInvoiceId | path | uuid | Yes | Owner-scoped recurring-invoice rule UUID. |
occurrenceId | path | uuid | Yes | UUID of one scheduled execution. |
curl https://api.tolepay.kz/v1/recurring-invoices/$RECURRING_INVOICE_ID/occurrences/$OCCURRENCE_ID \
-H "Authorization: Bearer $TOLE_API_KEY"{
"id": "b83a52dd-4578-44d9-80a0-b0a1b821fd4d",
"recurringInvoiceId": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"scheduledFor": "2026-09-27T05:00:00.000Z",
"status": "pending",
"attemptCount": 0,
"nextAttemptAt": null,
"paymentIntentId": null,
"commandId": null,
"lastFailureCode": null,
"createdAt": "2026-09-27T05:00:00.000Z",
"updatedAt": "2026-09-27T05:00:00.000Z",
"completedAt": null,
"attempts": [{
"id":"uuid","attemptNumber":1,"status":"succeeded",
"scheduledAt":"2026-09-27T05:00:00.000Z","startedAt":"2026-09-27T05:00:01.000Z",
"completedAt":"2026-09-27T05:00:02.000Z","commandId":"uuid",
"paymentIntentId":"uuid","failureCode":null
}]
}Retries only cover issuance failures
retryPolicy.delays runs in the exact order supplied and never duplicates an invoice that was issued but remains unpaid. On outcome_unknown, Tole moves to needs_attention and never blindly repeats the Kaspi mutation.
Rule statuses: active, paused, completed, needs_attention, archived. Occurrence statuses: pending, processing, retry_scheduled, succeeded, failed, needs_attention, skipped. misfirePolicy=run_once creates at most one occurrence after downtime, while skip records missed runs without catch-up.
Auto-invoices currently support live Kaspi connections only. Do not add /sandbox to these routes until OpenAPI explicitly documents a mirror.
The dashboard JWT mirror is /v1/automations/recurring-invoices with the same suffixes. Dashboard create may send connectionId in the body; when omitted, the server resolves and stores the current default connection. Its internal key receives the exact recurring permissions plus invoice:create.
Sandbox API
Sandbox runs on the same production Base URL and mirrors the main contract, persisting commands, payment intents, events, and webhooks without ever calling Kaspi.
Mirrored sandbox routes
Add /sandbox before the live path. Request schemas and mutation control envelopes match live; data contains sandbox synthetic values. X-Tole-Connection-Id is required.
/sandbox/invoices/client-infoinvoice:read
/sandbox/invoicesinvoice:create
/sandbox/invoices/historyinvoice:read
/sandbox/invoices/{operationId}invoice:read
/sandbox/invoices/{operationId}/cancelinvoice:cancel
/sandbox/qrqr:create
/sandbox/qr/{operationId}qr:read
/sandbox/history/operationshistory:read
/sandbox/history/operations/{operationId}history:read
/sandbox/refundsrefund:create
/sandbox/commands/{commandId}permission исходной команды
{
"ok": true,
"data": {
"id": "uuid", "kind": "invoice", "status": "created", "amount": 5000,
"clientPhoneLast4": "4567", "orderNumber": "SBX-1234ABCD", "environment": "sandbox"
},
"commandId": "uuid", "replayed": false
}{
"ok": true,
"data": {
"id": "uuid", "kind": "qr", "status": "created", "amount": 5000,
"paymentUrl": "https://sandbox.tole.test/pay/uuid",
"qrToken": "https://sandbox.tole.test/qr/uuid", "environment": "sandbox"
},
"commandId": "uuid", "replayed": false
}POST/sandbox/connectionsCreate a sandbox connection
Management endpoint authenticated with a user JWT, not an API key.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
displayName | body | string | Yes | Display name, 1–100 characters. |
curl https://api.tolepay.kz/v1/sandbox/connections \
-X POST -H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"displayName":"Development"}'{
"id": "uuid", "providerMode": "sandbox", "status": "active", "displayName": "Development"
}GET/sandbox/payment-intents/{paymentIntentId}Get a sandbox payment intent
Durable test state for an invoice or QR.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | Yes | Required sandbox connection UUID. |
paymentIntentId | path | uuid | Yes | Tole payment intent UUID. |
curl https://api.tolepay.kz/v1/sandbox/payment-intents/$PAYMENT_INTENT_ID \
-H "Authorization: Bearer $TOLE_TEST_API_KEY" \
-H "X-Tole-Connection-Id: $SANDBOX_CONNECTION_ID"{
"ok": true,
"data": { "id": "uuid", "kind": "invoice", "status": "pending", "amount": 5000, "currency": "KZT", "environment": "sandbox" }
}POST/sandbox/payment-intents/{paymentIntentId}/simulateSimulate payment outcome
Moves a sandbox intent to a terminal status and creates a webhook event.
| Field | In | Type | Required | Description |
|---|---|---|---|---|
X-Tole-Connection-Id | header | string | Yes | Required sandbox connection UUID. |
paymentIntentId | path | uuid | Yes | Tole payment intent UUID. |
status | body | enum | Yes | paid | cancelled | expired | failed |
curl https://api.tolepay.kz/v1/sandbox/payment-intents/$PAYMENT_INTENT_ID/simulate \
-X POST \
-H "Authorization: Bearer $TOLE_TEST_API_KEY" \
-H "X-Tole-Connection-Id: $SANDBOX_CONNECTION_ID" \
-H "Content-Type: application/json" \
-d '{"status":"paid"}'{
"ok": true,
"data": { "id": "uuid", "kind": "invoice", "status": "paid", "environment": "sandbox" }
}API keys and permissions
Create a key in the dashboard or through the JWT management API. The raw secret is returned only once.
/api-keysJWT · Список ключей; query cursor и limit 1–100
/api-keysJWT · Создать: { name, grants: [{ connectionId, permissions }] }
/api-keys/{apiKeyId}JWT · Заменить name и grants; нужен expectedRevision
/api-keys/{apiKeyId}/revokeJWT · Отозвать ключ; повторный revoke безопасен
| Permission | Разрешает |
|---|---|
invoice:create | POST /invoices; также execution binding для recurring create/update/resume/run |
invoice:read | client-info, invoice history/details, invoice payment intent |
invoice:cancel | POST /invoices/{id}/cancel |
qr:create | POST /qr |
qr:read | QR details и QR payment intent |
history:read | history endpoints и sandbox payment intent |
refund:create | POST /refunds |
recurring_invoice:create | POST /recurring-invoices; дополнительно требуется invoice:create |
recurring_invoice:read | список, detail и occurrences автосчетов |
recurring_invoice:update | PATCH, pause и resume; PATCH/resume дополнительно требуют invoice:create |
recurring_invoice:delete | DELETE-архивирование автосчёта |
recurring_invoice:trigger | POST /recurring-invoices/{id}/run; дополнительно требуется invoice:create |
sandbox:simulate | POST /sandbox/payment-intents/{id}/simulate |
{
"name": "Production backend",
"grants": [{
"connectionId": "7a67d6bd-5daf-47af-b899-fdb8b7db4d63",
"permissions": ["invoice:create", "invoice:read", "invoice:cancel"]
}]
}{
"apiKey": {
"id": "uuid", "name": "Production backend", "keyPrefix": "tole_sk_live_v1.…", "status": "active",
"revision": 1,
"grants": [{
"connectionId": "uuid", "connectionName": "main", "environment": "live",
"permissions": ["invoice:create", "invoice:read", "invoice:cancel"]
}]
},
"secret": "tole_sk_live_v1.<uuid>.<secret>"
}Webhooks
Webhook endpoints and deliveries accept a user JWT or any active tole_sk_* owned by the same account; connection grants are not required. URLs must use HTTPS. The whsec_* signing secret is returned once.
/webhook-endpointsJWT / tole_sk_* · Список endpoint-ов
/webhook-endpointsJWT / tole_sk_* · Создать: { name, url }; secret возвращается один раз
/webhook-endpoints/{endpointId}/disableJWT / tole_sk_* · Отключить; body {}
/webhook-deliveries?status=…JWT / tole_sk_* · pending | processing | delivered | dead_letter
/webhook-deliveries/{deliveryId}/replayJWT / tole_sk_* · Повторить dead-letter delivery; body {}
HTTP delivery
webhook-id
UUID события
webhook-timestamp
Unix timestamp
webhook-signature
v1=<hex HMAC-SHA256>
{
"id": "c2e94dd8-9802-44e7-a52b-14f45d5b9cdb",
"type": "payment.paid",
"createdAt": "2026-08-23T10:01:00.000Z",
"data": { "paymentIntentId": "33ec20dc-8d82-4077-a557-d59328853df9", "connectionId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "providerStatus": "Processed", "receiptUrl": "https://example.test/receipt/123", "receiptStatus": "available" }
}Payment receipts
New payment.paid events include paymentIntentId, connectionId, receiptUrl and receiptStatus. If Kaspi has not provided a receipt, receiptUrl is null and receiptStatus is unavailable; payment is still successful. Retrieve it later with GET /invoices/{id}/receipt or GET /payment-intents/invoices/{paymentIntentId}/receipt; use qr instead of invoices for QR payments. Requires invoice:read or qr:read. External URLs are returned immediately. Protected receipts are fetched server-side: receiptDocument (title, amount, currency, merchant, fields), receiptUrl: null, receiptStatus: available. Old webhook payloads remain unchanged.
Integrator API: GET /integrator/customers/{externalCustomerId}/connections/{connectionId}/invoices/{resourceId}/receipt (invoices:read), or /qr/{resourceId}/receipt (qr:read). Tole returns the provider’s link and does not generate fiscal receipts. Saving or printing depends on Kaspi’s page.
Payment event types: payment.created, payment.paid, payment.cancelled, payment.expired, payment.failed, payment.partially_refunded, payment.refunded, refund.reserved, refund.succeeded, refund.rejected, refund.outcome_unknown, operation.succeeded, operation.rejected, operation.outcome_unknown.
{
"id": "07dc5b90-f306-4f73-9d7e-6079f809825a",
"type": "recurring_invoice.occurrence.succeeded",
"createdAt": "2026-09-27T05:00:02.000Z",
"data": {
"recurringInvoiceId": "2d229044-8645-4e8b-b3fc-e0d6a9fe4184",
"occurrenceId": "b83a52dd-4578-44d9-80a0-b0a1b821fd4d",
"attemptNumber": 1,
"scheduledFor": "2026-09-27T05:00:00.000Z",
"status": "succeeded",
"paymentIntentId": "33ec20dc-8d82-4077-a557-d59328853df9",
"commandId": "a7a5d4dc-c623-456c-b176-8ec1f1000dc1"
}
}Recurring lifecycle: recurring_invoice.created, updated, paused, resumed, completed, needs_attention, archived; occurrence events: created, retry_scheduled, succeeded, failed, needs_attention, skipped. Обычные payment events созданного счёта дополнительно несут source: scheduled_invoice, recurringInvoiceId, occurrenceId и attemptNumber.
Новые payment.paid содержат paymentIntentId. Старые события могут не содержать его; итоговое состояние можно сверить по сохранённым UUID через payment-intent endpoints.
Проверяйте подпись по exact raw body до JSON.parse. Сохраняйте event id и обрабатывайте событие идемпотентно. Возвращайте 2xx только после надёжной фиксации события.
import { createHmac, timingSafeEqual } from "node:crypto";
const signed = `${webhookId}.${timestamp}.${rawBody}`;
const expected = "v1=" + createHmac("sha256", secret)
.update(signed, "utf8")
.digest("hex");
const actualBytes = Buffer.from(signature, "utf8");
const expectedBytes = Buffer.from(expected, "utf8");
if (actualBytes.length !== expectedBytes.length ||
!timingSafeEqual(actualBytes, expectedBytes)) {
throw new Error("Invalid Tole webhook signature");
}Billing management API
JWT-authenticated endpoints for plan, usage, subscription, and checkout management.
/billing/overviewJWT · Subscription, usage, invoices и текущий checkout
/billing/plansJWT · Доступные публичные планы и entitlements
/billing/invoices/{invoiceId}JWT · Получить owner-scoped billing invoice
/billing/checkoutJWT · Создать или продолжить checkout: { planCode }
/billing/checkout/{checkoutId}JWT · Получить статус checkout
/billing/subscription/cancelJWT · Отменить подписку в конце периода
/billing/webhooks/kaspiprovider callback · Служебный HMAC callback; не вызывается merchant-интеграцией
{
"planCode": "business"
}{
"id": "uuid",
"status": "pending",
"planCode": "business",
"planName": "Business",
"amountKzt": 22500,
"currency": "KZT",
"paymentUrl": "https://…",
"receiptUrl": null,
"expiresAt": "2026-08-23T11:00:00.000Z",
"paidAt": null,
"createdAt": "2026-08-23T10:00:00.000Z"
}Response formats, idempotency, and polling
Complete
Сохраните data.id/paymentIntentId и commandId. Повтор с тем же Idempotency-Key вернёт тот же результат и header Idempotent-Replayed: true.
Wait
Читайте Retry-After: 2 и Location. Poll GET /commands/:commandId. Не создавайте новую mutation.
Do not retry
Kaspi мог выполнить операцию. Проверяйте command и payment intent; новый create может дать дубль.
{
"ok": false, "kind": "in_progress", "commandId": "uuid", "replayed": true
}{
"ok": false, "kind": "outcome_unknown", "commandId": "uuid", "replayed": false
}Payment intent statuses: pending, paid, cancelled, expired, failed, partially_refunded, refunded.
REST API errors
Branch on HTTP status and code. message is diagnostic text and may change.
{
"statusCode": 409,
"code": "PUBLIC_API_IDEMPOTENCY_CONFLICT",
"message": "The Idempotency-Key was already used for a different request"
}| HTTP | code | Что делать |
|---|---|---|
| 400 | PUBLIC_API_VALIDATION_ERROR | Исправить body, query, UUID или заголовок. Не повторять без изменения запроса. |
| 401 | API_KEY_INVALID_CREDENTIAL | Проверить namespace и заменить неверный или отозванный ключ. |
| 402 | BILLING_SUBSCRIPTION_UNAVAILABLEBILLING_ENTITLEMENT_UNAVAILABLE | Активировать тариф или возможность. |
| 403 | PUBLIC_API_FORBIDDEN | Проверить grant, permission и X-Tole-Connection-Id. |
| 404 | PUBLIC_API_RESOURCE_NOT_FOUND | Проверить локальный UUID и environment; чужие ресурсы также выглядят как 404. |
| 409 | PUBLIC_API_IDEMPOTENCY_CONFLICT | Не менять body под старым ключом. Для новой операции создать новый key. |
| 409 | PUBLIC_API_DEFAULT_CONNECTION_REQUIREDPUBLIC_API_DEFAULT_CONNECTION_UNAVAILABLE | Передать connection header или исправить основное подключение. |
| 409 | PAYMENT_INVALID_STATEPAYMENT_REFUND_LIMIT_EXCEEDED | Перечитать payment intent и исправить переход или сумму. |
| 400 | RECURRING_INVOICE_VALIDATION_ERROR | Исправить расписание, timezone, окно, retry delays или лимиты полей. |
| 404 | RECURRING_INVOICE_NOT_FOUNDRECURRING_INVOICE_OCCURRENCE_NOT_FOUND | Проверить owner-scoped UUID; чужой ресурс также выглядит как 404. |
| 409 | RECURRING_INVOICE_CONCURRENT_MODIFICATIONRECURRING_INVOICE_INVALID_STATERECURRING_INVOICE_IDEMPOTENCY_CONFLICT | Перечитать revision/status; не менять semantic request под прежним idempotency key. |
| 409 | RECURRING_INVOICE_DEFAULT_CONNECTION_REQUIREDRECURRING_INVOICE_CONNECTION_UNAVAILABLE | Выбрать готовое live-подключение с нужными permissions. |
| 503 | RECURRING_INVOICE_UNAVAILABLE | Для read/preview применить backoff; после mutation сначала перечитать правило или occurrence. |
| 429 | RATE_LIMIT_EXCEEDEDBILLING_LIMIT_EXCEEDED | Соблюдать Retry-After или лимит тарифа. |
| 502 | PUBLIC_API_UPSTREAM_REJECTED | Kaspi отклонил команду. Исправить бизнес-условия перед новой командой. |
| 503 | PUBLIC_API_UNAVAILABLERATE_LIMIT_UNAVAILABLE | Для read — backoff. Для mutation сначала проверить commandId. |
| 500 | PUBLIC_API_INTERNAL_ERROR | Сохранить безопасный context и обратиться в поддержку. |