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
Create an isolated test connection in the dashboard.
Create a test API key
Grant access to the sandbox connection and required permissions. The secret is shown once.
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 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 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,
"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 }
}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"
}
}Sandbox API
Sandbox mirrors the main contract and persists commands, payment intents, events, and webhooks, but never calls 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 |
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 |
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
Create endpoints with a user JWT. URLs must use HTTPS. The whsec_* signing secret is returned once.
/webhook-endpointsJWT · Список endpoint-ов
/webhook-endpointsJWT · Создать: { name, url }; secret возвращается один раз
/webhook-endpoints/{endpointId}/disableJWT · Отключить; body {}
/webhook-deliveries?status=…JWT · pending | processing | delivered | dead_letter
/webhook-deliveries/{deliveryId}/replayJWT · Повторить 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": { "providerStatus": "SandboxProcessed", "environment": "sandbox" }
}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.
В контракте v1 состав data зависит от типа события и не гарантирует paymentIntentId. Не придумывайте это поле в интеграции: webhook используйте как сигнал, а итоговое состояние сверяйте по сохранённым 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 и исправить переход или сумму. |
| 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 и обратиться в поддержку. |