# PayGate integration guide For engineers and AI agents integrating payments into a website, a React Native app, a native iOS or Android app, or a backend. Plain text on purpose: copy it, feed it to a model, or read it yourself. Base URL: https://api.paygate.example OpenAPI 3.1: https://paygate.example/openapi.json (also served by the API at https://api.paygate.example/v1/openapi.json) Human-readable reference: https://paygate.example/api/ (the same document rendered as HTML) Machine index: https://paygate.example/llms.txt ## 1. What PayGate does - Accepts payments: mobile money (the buyer approves a prompt on their phone) and cards (the buyer finishes on a hosted page, so card numbers never reach your server). - Reports one status per payment, decided after asking the provider. A redirect or deep link is never treated as proof of payment. - Pays recipients out: you onboard recipients, release a payment when work is delivered, then settle or let the recipient withdraw. - Sends events to your server and retries when it is down. Amounts: the REST API uses integer minor units (`250000` is KES 2,500). The SDKs accept major units (`1500` is KES 1,500) and convert for you. Never send a float. ## 2. Environments Every app has two credentials from day one: - `sandbox`: runs on the simulator. No real money moves, and in production a sandbox collection is recorded as simulated without touching the tenant's books. - `live`: real providers. Reads are scoped: a live credential cannot read a sandbox payment and vice versa. Use sandbox for development and CI, live for production. They are different credentials, not a header. ## 3. Authentication Two credential types. ### Server client (all money operations) A registered Ed25519 key pair. Exchange a signed client assertion for a short-lived access token, then prove possession on every request with DPoP. 1. `POST /v1/auth/token` with your client assertion and a DPoP proof. The response contains `access_token` and `token_type: "DPoP"`. 2. Send `authorization: DPoP ` and a fresh `dpop: ` header on every request. The proof is bound to the token and to the request URL and method. Reusing a proof is rejected. You do not need to implement this by hand. `@paygate/server` does the key handling, token exchange and proofs for you. Use the raw flow only if you are writing a client in another language. ### Publishable key (browser and mobile bundles) `pk_sandbox_...` or `pk_live_...`. Read-only and origin-bound: - Allowed: `GET /v1/payment_methods`. - Refused: anything that moves money (`403 publishable_key_forbidden`). It is safe to ship in a bundle because it can only read methods, and only from the origins registered when the key was created. ## 4. The payment flow ### 4.1 Create the payment ``` POST /v1/payments authorization: DPoP dpop: idempotency-key: order-9f2c-01 content-type: application/json { "reference": "order-9f2c", "amount": 250000, "currency": "KES", "recipient_id": "rcp_...", // optional: who gets paid "metadata": { "order_id": "9f2c" }, // optional, returned to you "return_url": "https://your.app/thanks" } ``` Response `201`: ```json { "id": "pay_...", "status": "requires_action", "amount_minor": 250000, "currency": "KES", "reference": "order-9f2c", "checkout_url": "https://api.paygate.example/c/..." } ``` `reference` is your order id and is unique per app. Sending the same reference again returns the same payment, never a second charge. ### 4.2 Let the buyer pay Send the buyer to `checkout_url`, or complete the payment in your own UI. Optional: start the attempt yourself. ``` POST /v1/payments/{id}/confirm { "method": "mobile_money", "phone": "254712345678" } ``` `method` is `mobile_money` or `card`. For mobile money, `phone` receives the prompt. For card, omit `phone` and open the returned `redirect_url`. Other payment routes: | Route | Purpose | |---|---| | `GET /v1/payments/{id}` | current status and attempts | | `GET /v1/payments?reference=...` | find one by your reference | | `GET /v1/payments?status=&limit=` | list (scoped to your environment) | | `POST /v1/payments/{id}/refresh` | ask the provider again and apply the result | | `POST /v1/payments/{id}/cancel` | abandon an unpaid intent; never reverses a settled payment | ### 4.3 Know when it is paid Read `GET /v1/payments/{id}` until `status` is terminal, or wait for the `payment.succeeded` webhook. Terminal states: `succeeded`, `failed`, `cancelled`, `expired`. Show success only when the server says `succeeded`. Do not trust a query string, a deep link or a browser return URL. ## 5. Webhooks ### The event Register one HTTPS URL when the app is onboarded. PayGate POSTs JSON: ```json { "id": "evt_...", "type": "payment.succeeded", "occurred_at": "2026-11-02T12:00:00.000Z", "data": { "payment_id": "pay_...", "reference": "order-9f2c", "amount": 250000, "currency": "KES" } } ``` ### Headers ``` x-paygate-signature: t=1793641837,v1= x-paygate-event-id: evt_... ``` ### Verifying the signature Verify before parsing: 1. Split `t` and `v1`. 2. Reject if `abs(now - t) > 300` seconds. 3. Compute `HMAC-SHA256(secret, t + "." + rawBody)` and compare in constant time. 4. Deduplicate on `x-paygate-event-id`. Verify the raw body, never a re-serialised object: whitespace and key order change the digest. ### Retries Respond `2xx` quickly. Any other status is retried with backoff: 10s, 60s, 5m, 30m, 1h, 6h, 12h, 24h, then the event is marked dead and waits for a human in the console. Delivery is at least once, so make your handler idempotent. ### Event types Event types: `payment.succeeded`, `payment.failed`, `settlement.approved`, `settlement.failed`, `settlement.settled`. ## 6. Payouts ### The payout sequence 1. Create a recipient: `POST /v1/recipients` with `app_ref`, `display_name`, `kind`, `category`. 2. Add a destination (the phone number money goes to): `POST /v1/recipients/{id}/destinations`. 3. Read balances: `GET /v1/recipients/{id}/balances` returns `pending`, `unreleased`, `available`, `reserved`, `paid`. Only `available` can be paid. 4. Release a delivered payment: `POST /v1/releases`. 5. Pay: - `POST /v1/settlements` creates an instruction; `POST /v1/settlements/{id}/executed` records that the app executed it (for `app_escrow`). - `POST /v1/withdrawals` records a recipient's own request; it does not execute anything itself. 6. Read state: `GET /v1/settlements`, `GET /v1/settlements/{id}`, `GET /v1/withdrawals/{id}`. ### Balances Amounts draw on `available` minus `reserved`. An instruction above the balance is refused. ## 7. Idempotency ### The three outcomes Every write accepts `Idempotency-Key`. - Same key and same body: the first response is replayed, including the resource id. - Same key, different body: `409 idempotency_conflict`. - Same key while the first request is still running: `409 request_in_progress`, retry shortly. Use a key derived from your own operation (order id plus attempt), not a random value per retry. ## 8. Errors ### The envelope Every failure uses one envelope: ```json { "error": { "code": "validation_failed", "message": "amount must be a positive integer", "details": {}, "request_id": "req_..." } } ``` `request_id` matches the `x-request-id` response header and the server log line. Branch on `code`, never on `message`. ### Common codes The codes you will branch on most often: `validation_failed`, `unauthorized`, `forbidden`, `not_found`, `conflict`, `idempotency_conflict`, `request_in_progress`, `provider_unavailable`, `provider_error`, `rate_limited`, `insufficient_funds`, `recipient_unverified`, `currency_unsupported`, `payload_too_large`. ### Rate limits Rate limiting answers `429` with `retry-after` and `error.details.retry_after_seconds`. ## 9. SDKs ### Server (`@paygate/server`, Node and Bun) ```ts import Paygate from "@paygate/server"; const paygate = new Paygate(); // PAYGATE_URL, PAYGATE_CLIENT_ID, PAYGATE_PRIVATE_KEY, PAYGATE_WEBHOOK_SECRET const { checkout_url } = await paygate.pay({ amount: 1500, reference: "order_8123" }); ``` `PAYGATE_PRIVATE_KEY` is a JSON Ed25519 JWK, not PEM. Useful calls: `pay`, `get`, `byReference`, `refresh`, `cancel`, `methods`, `createPaymentLink`, `paymentLinks`, `setPaymentLinkActive`, `createRecipient`, `addDestination`, `balances`, `setPayoutMode`, `release`, `settle`, `withdraw`, `instructions`, `instruction`, `webhook`, `mandate`. `webhook(handler)(request)` verifies the signature over the raw body and returns a non-2xx when your handler throws, so PayGate retries. ### Web (`@paygate/web`) ```ts import { PaygateWeb } from "@paygate/web"; const pg = new PaygateWeb({ publishableKey: "pk_sandbox_..." }); const methods = await pg.paymentMethods("KES"); pg.go(payment.checkout_token); // hosted checkout pg.mount("#pay", { token, label: "Pay KES 1,500" }); // or a ready button ``` ### Mobile (`@paygate/mobile` + `@paygate/mobile/relay`) The app never holds the tenant credential. Your backend mounts the relay; the app talks to it. ```ts // backend — app/paygate/[[...path]]/route.ts for Next.js, or any fetch handler import { createRelayHandler } from "@paygate/mobile/relay"; const relay = createRelayHandler({ paygate, basePath: "/paygate", authorize: requireSession }); // app const paygate = createPaygateMobile({ baseUrl: "https://api.yours.app/paygate", headers }); const { payment } = await paygate.pay({ reference: "order_8123", amount: 1500, phone: "254712345678" }); ``` `pay()` resolves only when the server reports `succeeded`; otherwise it throws `PaygateMobileError` with `code`, `status`, `retryable`, `userMessage`. The relay exposes exactly five routes: `GET /methods`, `POST /payments`, `GET /payments/:id`, `POST /payments/:id/confirm`, `POST /payments/:id/cancel`. No payouts, releases or withdrawals. Express and Node's `http` module need a small adapter; `app.use` cannot take the Fetch handler directly. Read the raw body into a `Request`, call the relay with it, and write its `Response` back. Mount the adapter before `express.json()`, which would otherwise consume the body. The complete adapter is in the [framework guide](/docs/frameworks/#express-and-node-http). For cards, call `pay()` without `phone` (or with `method: "card"`); it returns `checkoutUrl` and charges nothing until the hosted page is completed. ### Native iOS and Android No native SDK. Use the REST API from Swift or Kotlin through your own backend, or mount the same relay used by the React Native SDK and call it from the app. Keep the Ed25519 key on the server. ## 10. Rules that keep the integration correct ### The rules that keep an integration correct 1. Never mark a payment paid from a redirect, a deep link or a client-side claim. Read the server. 2. Send an `Idempotency-Key` on every write, and reuse it for retries of the same operation. 3. Verify webhook signatures over the raw body, and deduplicate on the event id. 4. Treat a failed payout as unknown until you read it; do not retry a non-idempotent payout blindly. 5. Keep the private key on the server. A publishable key is the only credential a bundle may hold. ## 11. Operator tools are internal ### Operator tools are internal The operator console and the API behind it are not part of an app integration, are not published in this reference, and are not reachable from the public API host. Do not call them from an app. ## 12. Support ### Support Include `request_id` from the response or error in any support message. It identifies the exact request in the server logs.