Add BNPL to your
site in 30 minutes
Drop in the KiasiPay script, pass your product details, and your customers can book now and pay in instalments — by M-PESA, Airtel Money, or bank transfer.
Building an integration? Join the developer Discord ↗
How it works
onApprove callback with the booking ref and your order reference — a hint for your page; your server confirms from the webhook.Integration options
There is more than one way to put KiasiPay in front of a customer. They differ in how much of the screen is ours and how much is yours.
POST /api/checkout/session with your API token and decides the
amount; the customer's browser only ever receives an opaque token pointing at it. There
is no browser-side way to create a session, deliberately — an API token in a
browser is an API token the customer has.
Full walkthrough →
| Option | Status | What it is |
|---|---|---|
| Popup window | Available | The SDK button opens the checkout in a separate, top-level browser window. Nothing to configure, and nothing you can configure wrongly. |
| Direct link / redirect | Available |
No SDK at all. Create the session server-side and send the customer to the
checkout_url you get back — a redirect, an email link, a QR code, a
WhatsApp message. Useful for invoices, back-office staff and anywhere there is no
JavaScript to run. See below.
For bookings created in the dashboard you do not need to render the QR yourself: the Payment link dialog on the bookings list already shows the link as a scannable code and offers it as a PNG to save. That code is generated for the dashboard only — there is no API that returns one, because the link it encodes is a bearer credential and we do not hand those out over a token integration. A /pay/… link that is expired, revoked, tampered with or simply
never existed all answer the same 404. Do not branch on the status to
tell those apart — the responses are deliberately identical so that holding a dead
link tells you nothing about whether the booking behind it is real. Issue a fresh
link from the dashboard instead.
|
| Embedded iframe / modal | Not available | Drawing the checkout inside your own page. Offered once and removed — see below. |
| Fully merchant-rendered UI (headless) | Not available | Building the plan picker, payment-method screen and consent copy yourself against raw API calls, with no KiasiPay screen anywhere. Not offered, and not currently planned — see below. |
Why the checkout is never embedded in your page
The checkout opens in a popup — a separate, top-level browser window — and the hosted page refuses to be framed anywhere. An embedded-modal integration existed for a while and was removed. Two reasons matter more than the rest:
Your customer needs to see who they are paying.
An iframe has no address bar. On a screen where someone types an M-PESA PIN, being able
to read kiasipay.com in a real browser window is the check that matters
most, and embedding removes it — for you as much as for them, because a page that
can convincingly imitate a payment form is a liability you would be carrying.
Everything else on your page could read the checkout. Framed, the checkout session token sits in your own DOM, where every analytics tag, ad script and chat widget you load can read it. Most sites run several and think of none of them as part of their payment stack. In a popup the checkout lives in its own window and none of that can reach it.
If the concern is that a popup takes the customer away from your page, the direct link is the other supported shape — a full-page redirect you control, with the same property: the customer can see where they are.
Why there is no headless option
A fully merchant-rendered checkout would mean you draw every screen and call our API for each step. We do not offer that today, and the blocker is not effort — it is consent.
Kenya's Data Protection Act 2019 requires a record of what a person agreed to, not merely that they agreed. When our checkout takes a payment it records the customer's IP address, their browser's user-agent, the session token, and the version of the consent wording they were shown — that last one being the part a regulator actually asks about. We can stand behind that record because we rendered the screen. If you rendered it, the evidence would be yours to keep and yours to produce, the wording could differ from the version we recorded, and neither of us could prove what the customer saw. Moving that liability to you without saying so would be the worst possible outcome, so the option does not exist. If you need it, talk to us first — it is a contract question before it is an API one.
Server-side sessions
A checkout session is a short-lived object holding one line item and its price. Your server creates it; the customer's browser only ever sees the opaque token that points at it.
-
1
Issue an API token in the dashboard, while the right Organization is active. The token is permanently bound to that Organization and can only act on projects its holder is currently authorized to access — see API tokens. Store it as an environment variable on your server.
-
2
Call
POST /api/checkout/sessionfrom your backend with that token in anAuthorization: Bearerheader, and the price your own system holds for that product. Never take the price from the incoming browser request — look it up. -
3
Send the customer to the session. Either return the
tokento your page for the SDK button to open, or redirect straight to thecheckout_url. Both are fine; the session does not care how it is opened. - 4
// The browser tells you WHICH product. It never tells you the price. $product = Product::findOrFail($request->input('product_id')); $response = Http::withToken(env('KIASIPAY_API_TOKEN')) ->acceptJson() ->post('https://staging.kiasipay.com/api/checkout/session', [ 'project_code' => env('KIASIPAY_PROJECT_CODE'), 'product' => [ 'id' => $product->sku, 'name' => $product->title, 'price' => $product->price, // from YOUR database 'quantity' => 1, ], 'origin_url' => 'https://shop.example.com', 'reference' => (string) $order->id, // YOUR order id — comes back in every webhook ]); // Keep both on the order: webhooks carry session_id (never the token). $order->update([ 'kiasipay_token' => $response->json('token'), 'kiasipay_session_id' => $response->json('session_id'), ]); return ['token' => $response->json('token')];
const product = await db.products.find(req.body.productId); const res = await fetch('https://staging.kiasipay.com/api/checkout/session', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.KIASIPAY_API_TOKEN}`, 'Content-Type': 'application/json', 'Accept': 'application/json', }, body: JSON.stringify({ project_code: process.env.KIASIPAY_PROJECT_CODE, product: { id: product.sku, name: product.title, price: product.price, quantity: 1 }, }), }); const { token, checkout_url } = await res.json();
Direct link / redirect
If you have no JavaScript to run — a server-rendered checkout page, an emailed
invoice, a link your staff send over WhatsApp — skip the SDK entirely and send the
customer to the checkout_url from the response. It is an ordinary URL and the
checkout is a full page. The customer pays, and your
payment.succeeded webhook lands exactly as it would from the popup.
return redirect()->away($response->json('checkout_url'));
Things that will bite you
| Symptom | Cause |
|---|---|
401 Unauthenticated |
No Authorization header, or the token was revoked, deleted or has expired. |
401 Unauthorized |
The project_code does not match any project. Check for a stale value in your environment. |
403 — Organization or project access denied |
The token was issued for another Organization, or its holder is not assigned to this project. Tokens are Organization-pinned and project access is evaluated on every request. |
429 |
Rate limit. Authenticated callers get 120 sessions a minute per Organization; anything unauthenticated gets 10 a minute per IP. |
| Customer sees "session expired" | Sessions live 30 minutes. Create one when the customer is ready to check out, not when the page loads. |
Payment methods
KiasiPay collects on your behalf. Every successful charge is split automatically — no invoicing, no manual payouts — and settles to your own bank or mobile-money account. Paystack Kenya payouts are automatic on T+2: two working days after each transaction, excluding weekends and public holidays. KiasiPay cannot promise an earlier payout. Payment confirmation is separate from payout; provider checks or bank processing may delay funds reaching your account.
Collection runs through a licensed payment service provider. We name it where you actually deal with it — the sub-account opened in your name, the test credentials you use — and leave it out where it is our implementation detail rather than yours. It can change; if it does, you get notice in advance (Terms clause 6). Build against the payment method, never the provider.
| Method | How it's charged | Notes |
|---|---|---|
| M-PESA (mobile money) | Directly from the checkout popup — customer enters their phone, approves the prompt | No minimum beyond the standard checkout minimum |
| Airtel Money (mobile money) | Identical to M-PESA — the customer enters their Airtel number and approves the prompt | A separate payment_method value, so it can be enabled or disabled independently of M-PESA. The popup warns a customer whose number looks like it's on the other network, but never blocks them. |
| Bank transfer (Pesalink) | Directly from the checkout popup — KiasiPay displays a one-time account number, name and bank; the customer sends a Pesalink transfer from their own banking app | Offered at any amount the checkout accepts. Confirmation is not instant — see Pesalink below |
Pesalink bank transfer
Pesalink is the one method where the customer leaves the checkout popup to pay. They open their own banking app and send a transfer, so confirmation arrives in minutes rather than seconds. Everything on this page that differs for Pesalink follows from that.
What the customer sees
-
1
They pick Bank transfer in the popup.
-
2
The popup shows a one-time account number, account name and bank, plus the exact amount — each copyable in one tap. The account is temporary and belongs to that single payment.
-
3
They send a Pesalink transfer from their banking app for the exact amount, in one payment. A partial or rounded transfer can't be matched and is returned by their bank.
-
4
The popup counts down to the account's expiry and confirms automatically when the money lands. If the window lapses it says so and keeps checking — it never tells the customer the payment failed on a timer.
What this means for your integration
-
Don't treat "no result yet" as a failure.
The customer usually leaves the popup to pay from their banking app, so the SDK
reports
onPending(payment in flight) rather thanonApprovewhen the window closes, and the money can land minutes later. What you rely on is the same as for M-PESA: thepayment.succeededwebhook. - Don't reserve stock on popup-open alone for bank transfer, and don't cancel an order because the customer's browser closed — the transfer can still land. Wait for the webhook.
-
Webhooks are the source of truth. In the
rare case a transfer is confirmed after we'd already recorded a failure, you may
receive
payment.failedfollowed bypayment.succeededfor the same booking. The later event is correct — treat these as at-least-once and key off the latest event per booking.
Availability
- Offered at any amount the checkout accepts — there is currently no separate bank-transfer minimum.
- Bank transfer is enabled per merchant by our payment provider. If your buyers report it failing, contact support — it may not be switched on for your account yet.
- Customers banking with DTB (Diamond Trust Bank) cannot pay via Pesalink and should use another method.
- Settlement, fees and the 3% split work exactly as they do for every other method.
Add the button
Three steps: your server creates a checkout session, your page loads the SDK, and the button opens that session. The session is what carries the price, and it is created with your API token — so the price is set by code you control, on a machine your customer cannot reach.
POST /api/checkout/session requires an API token and must be called from
your backend. See Server-side
sessions for the full walkthrough.
curl -X POST https://staging.kiasipay.com/api/checkout/session \ -H "Authorization: Bearer $KIASIPAY_API_TOKEN" \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -d '{"project_code":"YOUR_PROJECT_CODE", "reference":"ORDER-10482", "product":{"id":"safari-3day-001","name":"3-Day Masai Mara Safari", "price":55000,"quantity":1}}' # => {"token":"a3f8c2…","session_id":"5b0c…","reference":"ORDER-10482", # "checkout_url":"https://staging.kiasipay.com/checkout/a3f8c2…", # "expires_at":"…","created_via":"server"}
Hand the token to your page and let the button open it.
<!-- 1. Load the SDK. No project code, no keys — the page has nothing worth stealing in it. --> <script src="https://staging.kiasipay.com/js/kiasipay.js"></script> <!-- 2. The button renders here --> <div id="kiasipay-btn"></div> <script> KiasiPay.Buttons({ // Ask YOUR OWN backend for a session when the customer clicks. // Your endpoint calls POST /api/checkout/session with your API // token and returns the token it gets back. The price is decided // there, not here. createSession: function() { return fetch('/api/my-checkout-session', { method: 'POST' }) .then(r => r.json()) .then(d => d.token); }, onApprove: function(data) { // UI hint: show "thanks — confirming your payment". Your SERVER confirms // it from the webhook; do not fulfil from here. console.log('Booking ref:', data.booking_ref); console.log('Your order:', data.reference); }, onPending: function(info) { // The window closed and the payment may still arrive (a phone prompt // awaiting its PIN, a bank transfer). Never cancel the order here. console.log('Confirming:', info.reason); }, onCancel: function(info) { // The window closed and no charge is in flight. Offer to try again. }, onError: function(err) { console.error('Payment failed:', err.reason); }, }).render('#kiasipay-btn'); </script>
Your API token stays on your server. Never put it in page source, in a bundled JS file, or in a fetch from the browser. A token in the browser is a token your customer has, and it can create sessions at any price for every project the token holder may access.
REST endpoints
All API endpoints are under /api and accept JSON. They split into two groups,
and the split is the whole security model:
-
Creating a session is yours.
POST /api/checkout/sessionrequires anAuthorization: BearerAPI token with thecheckout.managepermission, and must be called from your server. It is the call that sets the price, so a token without that permission is refused with403— including one that can manage products. -
Paying is the customer's.
POST /api/checkout/{token}/chargeandGET /api/checkout/{token}/statustake no token — the customer's browser has to reach them. All they carry is the session token, whose price was already fixed by you.
Create checkout session
Call this from your server when the customer
initiates checkout. Returns a token and a checkout_url: hand the
token to the SDK button, or redirect the customer to the URL.
Headers
| Header | Required | Description |
|---|---|---|
| Authorization | required |
Bearer YOUR_API_TOKEN. The token must belong to the Organization that
owns project_code; a token from a different Organization is refused with
403, not silently accepted. Server-side
only — a token in page source is a token your customers have.
|
Request body
| Parameter | Type | Required | Description |
|---|---|---|---|
| project_code | string | required | Your project code (e.g. KP-XXXX), printed under the business name in Workspace › Businesses |
| product.id | string | required | Your internal product/service identifier |
| product.name | string | required | Display name shown to the customer in the checkout popup |
| product.price | integer | required | Price of one unit in whole KES; the buyer owes this multiplied by product.quantity. Decimals are refused with 422, because mobile money cannot charge cents. Minimum: 1. Maximum: 10,000,000, and price multiplied by quantity may not exceed 50,000,000 |
| product.quantity | integer | required | Number of units (1–100). Usually 1 for bookings. |
| product.image_url | string (URL) | optional | Product image shown in the popup |
| product.fulfilment_date | string (date) | optional | When the customer receives or uses what they booked (YYYY-MM-DD). Omit it and everything works exactly as before — it's recorded for reporting only and never affects the checkout flow. |
| origin_url | string (URL) | optional |
Your page's origin — the only place the checkout will post the payment
outcome. Strongly recommended: omit it and the checkout stays silent, and you
learn the result from the webhook or GET /api/checkout/{token}/status.
Must be https:// (plain http:// only for
localhost and 127.0.0.1), with no username or password.
You may pass a full page URL — we store and compare only its origin, so
https://shop.example.com/cart?step=2 becomes
https://shop.example.com. Anything that is not a usable origin is
rejected with 422 when you create the session, rather than failing
silently later.
|
| reference | string (max 64) | optional |
Your own order id. Strongly recommended —
it is how your server joins a payment to the order it belongs to. We store it and
echo it back unchanged in this response, in
GET /api/checkout/{token}/status and in every
webhook for the booking,
including later instalments. Letters, digits, . _
: -, starting with a letter or digit; anything else is a
422. It need not be unique (one order may open several sessions), and
the customer can read it, so do not put a secret in it.
|
Response 201 Created
{
"token": "a3f8c2...64-char-hex-token",
"session_id": "5b0c1f6e-2a7d-4e39-b8c4-91d3e7f0a652", // not a secret — webhooks carry this
"reference": "ORDER-10482", // what you sent, or null
"checkout_url": "https://kiasipay.com/checkout/a3f8c2...",
"expires_at": "2026-06-22T07:30:00+00:00", // UTC
"created_via": "server",
"livemode": true // false when the token is a test token on the sandbox; see Testing
}
created_via is always "server". It is echoed so you can confirm
from the response alone that the call you believe is authenticated actually was.
livemode tells you which world the token belongs to: true on the
live site, false on the sandbox, which charges no real money
(see Testing).
Store token and session_id on your order before you answer the
browser. The token is a credential — it opens the checkout and the status
endpoint — so it stays out of logs and is never sent in
a webhook. session_id identifies the same session without granting
anything; it is what webhooks carry, alongside your reference.
Errors
| Status | Meaning |
|---|---|
401 | No token, or a token that is unknown, revoked or expired. Also what a browser-side call gets. |
401 | project_code matches no project. |
403 | The token's Organization does not own that project, or the token resolves to no Organization at all. |
403 | {"code": "collection_unavailable"} — your Organization cannot currently collect payments (paused by an administrator, suspended, or no active plan). No session is created; message says why. |
422 | Validation — see the errors object. |
429 | Rate limited: 120/min per Organization when authenticated, 10/min per IP otherwise. |
Initiate payment
Called by the checkout popup on confirm — you will not normally call this yourself. Documented here so you know what the popup is doing and what a successful response looks like for each method.
Request body
| Parameter | Type | Required | Description |
|---|---|---|---|
| payment_method | string | required | One of MPESA, AIRTEL_MONEY,BANK — one value per network, so each can be enabled independently. |
| phone | string | required | Kenyan mobile number — 07xx, 01xx, 254… or +254…. Required on every payment method, not just mobile money. On MPESA and AIRTEL_MONEY it is also where the prompt is sent; on bank transfer it identifies the buyer, so a returning customer is recognised and can be sent their payment instructions and receipt. |
| string | optional | A real Buyer email for delivery of the accepted booking agreement. The agreement remains stored on KiasiPay when omitted. | |
| plan_id | string | required |
The selected BNPL plan's UUID (see Payment plans).
Must be one of the plans this project currently offers — an
inactive plan, or a plan belonging to another project, is refused with
422. The popup only ever offers plans that pass this check.
|
| payment_channel_id | string | required | UUID of the merchant's channel for the chosen method |
| buyer_terms_accepted | boolean | required | Must be true after the Buyer explicitly accepts the booking-specific written agreement. Never infer or pre-tick this value. |
| buyer_terms_version | string | required | The current Buyer terms version presented by the hosted checkout. A stale version is refused with 422. |
Response 200 OK
{
"status": "awaiting_payment",
"display_instruction": "Check your phone for the M-Pesa prompt...",
"bank_transfer_details": { // BANK only, otherwise null
"account_number": "1234567890",
"account_name": "KiasiPay Collections", // banking apps require the recipient name
"bank": "Providus Bank",
"expires_at": "2026-06-24T06:00:00+00:00" // ISO-8601, UTC; when the account stops accepting the transfer
}
}
{"status": "confirming"} means the payment provider did not
give a clear answer in time (a timeout or an outage on their side). The charge may still
go through, so treat it like awaiting_payment: do not start another
charge — a retry on the same token answers 409 — and wait for the webhook or
poll session status, which moves to paid or
failed once we have confirmed with the provider. A 502 is a
definite refusal: nothing was charged and the buyer may retry.
Session status
Call this from your server to verify payment state — for example when the customer lands back on your site before the webhook has arrived. It needs no API token: the session token in the path is the only credential. The SDK also calls it, once, when the popup closes without reporting an outcome, so this one endpoint answers any browser origin. Limited to 60 requests a minute per client IP.
{
"status": "paid", // pending | awaiting_payment | paid | failed | expired
"is_expired": false,
"payment_may_arrive": false, // true while money can still land — incl. a failed bank transfer
"booking_ref": "7d2f0c5e-3b1a-4c8e-9a41-5e6f8b2d1c90", // booking UUID; null until a charge STARTS — not proof of payment
"session_id": "5b0c1f6e-2a7d-4e39-b8c4-91d3e7f0a652",
"reference": "ORDER-10482", // your order id, or null
"merchant_product_id": "safari-3day-001",
"livemode": true // false on the sandbox; never treat a session with livemode false as paid on a production server
}
-
Only
status: "paid"means paid.booking_refis set as soon as a charge starts, so it is also present whileawaiting_paymentand afterfailed. -
is_expiredis the expiry signal. It turnstruethe moment the session's 30 minutes are up, whatever the status. The stored status becomesexpiredshortly afterwards, and only for a session that was stillpendingorawaiting_payment—paidandfailedare never overwritten. -
An expired session can still be paid. If a
charge was in flight when it expired — a bank transfer made late — the status moves
from
expiredtopaidwhen the money lands andpayment.succeededfires. Don't cancel an order because a session with abooking_refexpired. - The response carries no amounts. Those are in the webhook.
KiasiPay.Buttons()
Installation
The SDK is a plain JavaScript file — no npm, no bundler, no dependencies. It works in any web page.
<script src="https://staging.kiasipay.com/js/kiasipay.js"></script>
The tag takes no configuration. Your project code belongs on your server, next to your API token; the button only receives the session token returned by your server. Load the script from the KiasiPay host you integrate with: the checkout URL is derived from the origin the script was served from.
Button options
| Option | Type | Description |
|---|---|---|
| createSession | function() => Promise<string> |
Called when the customer clicks. Ask your own
backend for a checkout session and resolve with its token.
Preferred over session: the session is minted at the moment of the
click, so it cannot expire while the page sits open.
|
| session | string | A session token your server already created, for a page rendered at checkout time. Remember the 30-minute expiry. |
| onApprove | function(data) |
Fires when the checkout reports the deposit as paid, or when the popup closed and
the session's status is paid. Receives
{ booking_ref, merchant_product_id, reference, session_id, source, plan, amount_paid }.
booking_ref is the booking UUID; reference is the order id
your server sent. source is "checkout" when the checkout
posted it, or "status" when the SDK read it from the status endpoint
after the window closed — in that case plan and
amount_paid are absent.
This is a UI hint only — use it to update
the page, never to fulfil the order. See below.
|
| onPending | function(info) |
The popup closed and the payment may still
arrive. Receives
{ reason, status, booking_ref, reference, session_id }.
reason is "payment_in_flight" (a charge was started and has
not resolved — a phone prompt awaiting its PIN, a bank transfer the customer is
making from their own app) or "status_unavailable" (the outcome could
not be read). Show "we're confirming your payment"; do
not cancel the order or release stock.
Your server settles it from the webhook.
|
| onError | function(err) | Called when payment fails or an error occurs. Receives { reason }, plus a detail string for the errors the SDK itself raises — see the reasons below |
| onCancel | function(info) |
The popup closed and nothing can arrive (the status endpoint's payment_may_arrive is false): the customer never confirmed, a phone prompt was declined, or the
charge never started. Receives { status, reference, session_id }. It is
not called just because the window
closed — a closed window with a payment under way is onPending, and a
paid one is onApprove. Still a UI hint: a failed bank transfer can be
paid late, so never cancel an order server-side because of it.
|
What happens when the popup closes
At most one of onApprove,
onPending, onCancel and onError fires per click.
The checkout posts its outcome only when the customer presses Done, and only if
the session has an origin_url — so a window that simply closed says nothing:
the customer may have paid and used the window's X, or left to pay a bank transfer. When
that happens the SDK makes one request to
GET /api/checkout/{token}/status and picks the callback from the answer.
Anything it cannot determine is onPending, never onCancel.
If your page sets a Content-Security-Policy, allow https://staging.kiasipay.com in
connect-src. Without it the browser blocks that request and every close is
reported as onPending.
onError reasons
| reason | What happened |
|---|---|
| no_session_source |
Neither createSession nor session was passed. The button
will not create one itself, so nothing opens. This is what an un-migrated v1
integration gets.
|
| session_failed |
Your createSession threw or rejected. detail carries its
message. This is your endpoint failing,
not ours — check your server logs, and whether it got a 401/403
from us.
|
| invalid_session_token |
createSession resolved with something that is not a session token —
most often the whole JSON body instead of d.token. Anything containing
a slash, a space or a query string is refused before it is put in a URL.
|
| anything else | Reported by the checkout itself over postMessage — the payment was attempted and failed. |
onApprove, onPending and onCancel run in the
customer's browser, so they tell you only what the popup or a browser request
reported — not a settlement guarantee, and their values must never be trusted as
amounts you are owed. Use them to show a thank-you or "confirming" screen. Do
not use onApprove to fulfil an order, release stock, issue
tickets, or credit an account, and do not use onCancel to
cancel one.
Confirm payment on your server using the
payment.succeeded webhook,
or a call to GET /api/checkout/{token}/status made from your backend.
Confirm there before you give anything away, and treat the booking ref from that
response, and the amount from the webhook or the price your own server set — not
from onApprove — as authoritative. The status response carries no amount.
Events
postMessage events
If you're not using the SDK, you can listen for window.postMessage events directly.
These fire from the KiasiPay popup to your parent page.
Always check event.origin before
reading the payload, as the example below does. Any script running on your page — an
analytics snippet, an ad tag, an embedded widget — can post a message that looks
identical to ours. The SDK performs this check for you, and additionally verifies the
message came from the popup window it opened. The same rule as above applies here:
these events are UI signals, and payment is confirmed only by the
payment.succeeded webhook or
GET /api/checkout/{token}/status.
origin_url. A customer who closes the window another way sends nothing, so its absence is not a cancel. Confirm server-side before fulfilling.{ type: 'KIASIPAY_APPROVE', booking_ref: '7d2f0c5e-3b1a-4c8e-9a41-5e6f8b2d1c90', plan: '3 Months',
amount_paid: 18150, merchant_product_id: 'safari-3day-001',
reference: 'ORDER-10482', session_id: '5b0c1f6e-2a7d-4e39-b8c4-91d3e7f0a652' }
{ type: 'KIASIPAY_ERROR', reason: 'payment_failed' }
window.addEventListener('message', function(event) { if (event.origin !== 'https://staging.kiasipay.com') return; if (!event.data?.type?.startsWith('KIASIPAY_')) return; if (event.data.type === 'KIASIPAY_APPROVE') { showConfirmingScreen(event.data.booking_ref); // UI only — your server confirms } });
Payment plans
The customer chooses their plan inside the popup. You receive the chosen plan name
in onApprove as the plan field (e.g. "3 Months").
All amounts round up to the nearest KES to avoid underpayment on the final instalment.
A plan is named for the span it runs, not the number of payments it takes. The first payment is the deposit, charged today; "3 Months" is therefore four payments and settles on day 90.
Payment callbacks
There is nothing to configure. KiasiPay receives payment confirmations from its payment provider directly and records them for you. You do not register a callback URL, and there is no provider endpoint you need to know about or point anything at.
What you consume is the other side of that: your
merchant webhook, which
KiasiPay sends to an endpoint you control, and
GET /api/checkout/{token}/status
if you would rather poll. Those two are the authority on whether a payment
succeeded — not the onApprove callback in the browser.
API tokens & Organizations
The KiasiPay API uses Sanctum bearer tokens for authentication on routes that require a merchant account
(auth:sanctum middleware). Tokens are issued from the KiasiPay dashboard under
API Tokens in the top navigation.
Every token is permanently bound to the Organization that was active when it was created. This means:
- Switching Organizations in the dashboard does not re-scope an already-issued token.
- API requests always act within the token's Organization, regardless of which Organization the user is currently viewing.
- Staff tokens are further restricted to the holder's current project assignments. Removing an assignment takes effect immediately.
- To operate across multiple Organizations, issue a separate token for each one.
- Two-factor authentication is required to create tokens. Anyone who can issue API tokens (the Organization owner, Administrators, and project Managers and Developers) must turn on and confirm two-factor authentication under Account settings → Two-Factor before the dashboard opens for them. Tokens already issued keep working: an API request authenticates with the token alone.
Creating & managing API tokens
Tokens are created from the KiasiPay dashboard. Follow these steps exactly — the active Organization at creation time is permanently burned into the token and cannot be changed later.
/user/api-tokens — accessible via API Tokens in the sidebar or top navigation./user/api-tokens at any time to delete a token. Deletion is immediate — all subsequent API calls using that token will be rejected with 401 Unauthorized.Usage example
Pass the token as a standard HTTP Bearer header on every request:
curl -X POST https://kiasipay.com/api/products \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Accept: application/json" \ -H "Content-Type: application/json" \ -d '{"title":"Safari Package","price":55000,"bpid":"9b2f6c1e-4d3a-4f8e-a1b2-3c4d5e6f7a80"}'
Permissions
When creating a token you tick one or more permissions. These are the same
permissions KiasiPay uses for people — the ones your role in the Organization grants you —
not a separate set of API verbs. Every one of them is checked on the server for every
request; a token missing the permission is refused with 403 and a
required_ability field naming what it needed.
| Permission | Grants | Routes |
|---|---|---|
product.view |
Search and read products. Ticked by default on a new token — it is the only read-only permission, and a token with nothing else can change nothing. | POST /api/search/product |
product.manage |
Create, update and delete products. One permission for all three: the authorisation layer underneath has never distinguished them, so a token restricted to "update only" was never actually restricted. | POST /api/products, DELETE /api/products/{id} |
booking.manage |
Create and delete bookings. Can move money:
creating a booking with paymentMode: 1 sends a live M-PESA prompt to the
buyer's phone. Delete works only for a booking that was never charged: once any
payment attempt exists it answers 409 booking_has_payments — cancel it
from the dashboard instead.
|
POST /api/bookings, DELETE /api/bookings/{id} |
checkout.manage |
Create hosted checkout sessions. Can move money:
a session fixes the amount a buyer is charged, so this is the most consequential
permission the API offers. Deliberately separate from
product.manage — editing a catalogue and pricing a charge are different
grants.
|
POST /api/checkout/session |
- If the permission you need is greyed out, ask someone with administrator rights in the Organization to create the token for you. Privileged tokens are minted by admins — there is no self-service path to a permission your role does not have, by design.
-
Not everyone can issue a token at all. Creating API credentials is its
own permission (
apitoken.manage), held by the account owner, Organization Administrators, and the Project manager and Developer project roles. Read-only staff see an empty permission list, because a bearer token is long-lived and leaves the browser in a way a dashboard session does not. - Staff who are not Administrators get their permissions from the projects they are assigned to. Being a Developer in an Organization grants nothing on its own; someone has to add you to a project first, and until they do the permission list is empty.
- Losing a permission later does not retroactively strip a live token's abilities, but it does take effect immediately at the project level: every request re-checks that the token's owner may still act on the project in question. A removed assignment breaks the call on the next request.
Authenticated API routes
These routes require a valid bearer token (Authorization: Bearer <token>).
All queries are automatically scoped to the token's Organization — records from other Organizations
are never returned or modified.
| Method | Path | Description |
|---|---|---|
| POST | /api/products |
Create or update a product. Body: title, price (integer, whole KES) and bpid (the project’s UUID). Pass the product’s UUID as pid to update. Requires the product.manage permission. |
| DELETE | /api/products/{id} |
Delete a product. Requires the product.manage permission and org ownership of the product.
A product that any booking references cannot be deleted and returns 422
naming the count — deleting it would break those customers' receipts and payment
records. Switch the product off instead.
|
| POST | /api/search/product |
Search products within your Organization by title or ID. Requires the product.view permission — a token without it cannot enumerate your price list. |
| POST | /api/bookings |
Create a new booking. Requires the booking.manage permission. buyer is a
Kenyan mobile number in any of the accepted forms — 0712345678,
254712345678 or +254712345678, with spaces and hyphens
allowed — and is normalised for you. Anything that is not a Kenyan mobile number is
refused with 422.
|
POST /api/checkout/session needs a bearer token like everything else here, and
it must be called from your server — this changed, and a browser-side call now returns
401. The two customer-facing routes
(POST /api/checkout/{token}/charge,
GET /api/checkout/{token}/status) remain public, because the customer's browser
has to reach them; all they carry is a session token whose price your server already set.
See Integration options.
Token security
- Never commit tokens to version control. Use environment variables (
.env) or a secrets manager. A leaked token in git history means you must revoke and rotate immediately. - One token per integration. Create separate tokens for your booking engine, CRM sync, and any other integration. That way you can revoke a single token without disrupting everything else.
- Rotate periodically. Treat tokens like passwords — rotate every 90 days or after any team member with access leaves.
- Tokens do not expire by date. A working integration is never cut off on an anniversary. A token that goes 180 days without a single request is revoked automatically and its owner is emailed; create a new one if you still need it.
- Revoke immediately if leaked. Go to
/user/api-tokens, delete the compromised token, issue a new one, and update your integration. - Grant minimum permissions. A read-only integration (e.g. product search) should hold
product.viewand nothing else. Never tickbooking.manageorcheckout.manageon a token that does not need to charge anyone — both can move a customer's money.
WhatsApp payment requests
KiasiPay can message your buyers on WhatsApp with a pay-now button. The buyer taps it and an M-PESA prompt appears on their phone — no app, no link, no typing an account number. SMS and email are used as fallbacks where WhatsApp is not available.
What gets sent
| Message | When | Carries a pay button |
|---|---|---|
| Payment request | You press Request Payment on a booking | Yes |
| Instalment due | 3 days before, and on, an instalment's due date | Yes |
| Instalment overdue | 3 days after the due date | Yes |
| Payment failed | A charge did not complete | Yes |
| Receipt | A payment succeeded | No |
| Booking terms to accept | A buyer taps Pay now on a booking whose terms they have never accepted | No — carries the agreement link |
Reminders run three times and stop — they are not a drip campaign. A buyer who has paid everything on time so far gets a single reminder on the due date rather than the full sequence.
A receipt goes to WhatsApp only when the buyer paid by tapping a WhatsApp button. If they paid on the web, the receipt is emailed — they already watched the payment succeed, and a second notification is noise you would be paying for.
Consent
A buyer must opt in before you can message them, and that opt-in is specific to your business — agreeing to hear from you does not let any other merchant on KiasiPay message them. This is required by both WhatsApp and Kenya's Data Protection Act 2019.
Buyers opt in at checkout, or in store when you take their number. They can reply STOP (or ACHA, SITISHA, TOKA, ONDOA) at any time, which stops messages from every merchant immediately.
What it costs
Messaging is a KES 1,000/month subscription including 1,000 messages. When the allowance runs out, sending stops — you are never billed for overage, and you will be warned at 80%.
Very small balances are not chased: below KES 500 nothing is sent, and below KES 2,000 a single reminder is sent instead of the full sequence. A message costs money whether or not it converts, and on a small balance the arithmetic does not work.
Without a subscription your buyers still receive receipts by email. You lose the WhatsApp pay-now button and SMS, not buyer communication altogether.
Who the message comes from
Messages are sent from KiasiPay's WhatsApp number, with your business name in the message body — the same way bank and payment-gateway messages work. Sending from your own WhatsApp number is not currently supported.
Outbound Webhooks
KiasiPay can POST a signed event to your server every time a payment succeeds or fails. Enable webhooks from the business list: Businesses → (your business) → Webhooks. Set your endpoint URL, generate a signing secret, then save.
Events
Payload shape
Every event body is JSON with this top-level envelope:
{
"id": "evt_550e8400-e29b-41d4-a716-446655440000", // unique delivery ID — use for idempotency
"type": "payment.succeeded",
"created_at": "2026-06-24T05:15:30+00:00", // UTC
"livemode": true, // false on the sandbox: refuse to fulfil an order from it on a production endpoint
"data": {
"booking_ref": "7d2f0c5e-3b1a-4c8e-9a41-5e6f8b2d1c90", // booking UUID, same on every surface
"session_id": "5b0c1f6e-2a7d-4e39-b8c4-91d3e7f0a652", // the checkout session it came from; may be null
"reference": "ORDER-10482", // YOUR order id, as sent at session creation; may be null
"amount_paid": 18150, // THIS payment only: a deposit or one instalment
"booking_total": 72600, // the booking's whole price (unit price × quantity)
"balance_remaining": 54450, // still owed after this event; 0 = fully paid
"currency": "KES",
"status": "paid",
"provider": "PAYSTACK", // informational — the rail used; may change, do not branch on it
"payment_method": "MPESA",
"platform_fee": 544.5, // KES kept by KiasiPay on this charge; may be null
"net_amount": 17605.5, // KES you actually settle; may be null
"receipt": "QHX5VTJB0Z", // provider-neutral receipt/reference
"phone": "254712345678",
"plan": "3 Months",
"merchant_product_id": "safari-3day-001", // the id YOU gave us for the product
"product_uuid": "b3c1a7e2-5d49-4f0a-8c63-2e9d7a41f580",
"transaction_id": "0f6a4c1e-8b27-4d93-a5e0-7c3b9d2e61a4" // transaction UUID — use for idempotency and support queries
}
}
Matching an event to your order
-
Join on
reference, else onsession_id.referenceis the order id you passed toPOST /api/checkout/session;session_idis what that call returned. Both are the same on the deposit and on every later instalment.booking_refis our id — you first learn it from the webhook, so it cannot find your order the first time; store it once you have matched. -
The session token is never in a webhook. It
is a credential (it opens the checkout and the status endpoint), and webhook bodies
get logged. If you stored only the token, start storing
session_idtoo. -
Never drop an event you cannot match.
Acknowledge it with a
2xx, keep it, retry the match for a minute or two (a webhook can beat your own database commit), then flag it for a person. It is real money. Don't fulfil it and don't create an order from it. An event with bothreferenceandsession_idnullbelongs to a booking that was not created through one of your checkout sessions — for example one made in the dashboard. -
Compare
booking_total, notamount_paid, with your price.amount_paidis a single payment, so on an instalment plan it is the deposit or one instalment and will never equal the price.balance_remainingreaching0is "fully paid". Onpayment.failed,amount_paidis0and the balance is unchanged.
Request headers
| Header | Description |
|---|---|
| X-KiasiPay-Event | The event type, e.g. payment.succeeded |
| X-KiasiPay-Delivery | The unique delivery ID matching id in the payload |
| X-KiasiPay-Signature | HMAC-SHA256 signature — see verification below. Format: t=<unix>,v1=<hex> |
Verifying the signature
The signature header has the form t=<unix-timestamp>,v1=<hex-signature>.
Reject requests where |now - t| > 300 seconds (replay protection).
function verifyKiasiPaySignature( string $rawBody, string $signatureHeader, string $secret, int $tolerance = 300 ): bool { // Parse t= and v1= from header if (!preg_match('/t=(\d+),v1=([a-f0-9]+)/', $signatureHeader, $m)) { return false; } [, $ts, $sig] = $m; // Reject stale requests (replay attack protection) if (abs(time() - (int) $ts) > $tolerance) { return false; } // Recompute HMAC and compare in constant time $expected = hash_hmac('sha256', "{$ts}.{$rawBody}", $secret); return hash_equals($expected, $sig); }
hash_equals (not ===) to prevent timing attacks.
Read the raw body with $request->getContent() — parsing JSON first can alter byte ordering.
Delivery behaviour
Webhooks are delivered at least once — your endpoint may receive duplicate
events on retries. Use the id field as an idempotency key to safely deduplicate.
An event with "livemode": false was produced on the sandbox: a production
endpoint must acknowledge it and fulfil nothing.
Each retry is signed afresh, with a new t, so the 300-second window applies
to every attempt. The dashboard's Send test event
delivers a signed payment.succeeded whose data carries
"test": true and all-zero UUIDs — verify it, answer 2xx, and
fulfil nothing.
The signature is what proves a delivery came from KiasiPay — verify it on every request.
If your firewall restricts inbound HTTP, deliveries currently come from
63.185.130.56 .
Treat the address as a convenience, not as authentication: it can change.
Retry schedule
If your endpoint returns a non-2xx response or fails to connect, KiasiPay retries up to 5 times with exponential backoff:
| Attempt | Delay after previous |
|---|---|
| 1 (initial) | — |
| 2 | 10 seconds |
| 3 | 1 minute |
| 4 | 5 minutes |
| 5 | 30 minutes |
| 6 | 2 hours |
Testing your integration
There is no separate test environment yet. A token issued on this site is a live token: a checkout it creates charges a real phone or bank account, and the buyer receives a real receipt. A sandbox with test tokens and simulated payments is planned; until it is available, test in the order below.
Telling test from live: livemode
Three things carry a boolean livemode field: the body of
every webhook (top level, beside id and
type, not inside data), the response to
creating a session, and the
session status response. It is true only on
the live site and false everywhere else. The dashboard's
Send test event carries the same livemode as any other event
from that site, plus "test": true, so check test as well.
"livemode": false: acknowledge it with a 2xx, record
it and do nothing else. This is what stops a test webhook, pointed at the wrong
endpoint, from shipping goods. Also de-duplicate on the event id: a
delivery can arrive more than once.
Tokens issued on this site start with kp_test_.
Tokens issued before the prefixes existed have none; treat a token with no
kp_ prefix as live.
- Fake the API in your automated tests. Unit and integration tests should never call KiasiPay. Stub the HTTP client and assert on what your code sends.
- Send yourself a signed test webhook. On your project's webhook settings, press Send test event. It is signed exactly like a real event, carries
"test": true, and moves no money. Your handler must verify it and must not fulfil an order from it. - Make one small real payment to yourself. Create a low-priced product, pay with your own phone, and confirm the webhook, the status endpoint and your order all agree. The money settles to your own payout account, less the platform fee.
payment.succeeded and must not have cancelled the order in
the meantime.
Building with AI coding agents
If you use a coding agent such as Claude Code or Cursor, you can give it KiasiPay Agent Skills: short Markdown instructions that teach it this integration and the rules it must not break. They are documentation only — no scripts, no credentials, nothing that runs when installed — and they say nothing this page does not. Where the two ever differ, this page wins.
| Skill | What it covers |
|---|---|
| kiasipay-checkout-integration | Integrate KiasiPay hosted checkout (M-PESA, Airtel Money, Pesalink bank transfer, instalment "book now, pay later" plans) into a merchant's own website or backend. Use when adding a KiasiPay pay button, creating checkout sessions server-side with an API token, redirecting a customer to a KiasiPay checkout link, confirming payment status, or handling paid, failed, pending or expired outcomes. Not for receiving webhooks (see kiasipay-webhooks). |
| kiasipay-webhooks | Receive and process KiasiPay outbound webhooks (payment.succeeded, payment.failed) on a merchant's server. Use when building or reviewing a KiasiPay webhook endpoint, verifying the X-KiasiPay-Signature HMAC-SHA256 header, preventing replays, de-duplicating deliveries, or fulfilling orders and instalment payments from webhook events. Not for creating checkout sessions (see kiasipay-checkout-integration). |
Installing them
Claude Code loads skills from .claude/skills/<name>/SKILL.md in your
project. Run this from your project root, then read the files before you commit them
— as you should with any instructions you hand an agent. Other agents: put the same
files wherever yours reads rules from. The full list is at
/developers/skills,
and /llms.txt
points agents at this page.
BASE=https://staging.kiasipay.com/developers/skills for f in kiasipay-checkout-integration/SKILL.md kiasipay-checkout-integration/references/api.md kiasipay-checkout-integration/references/outcomes-and-polling.md kiasipay-checkout-integration/references/sdk.md kiasipay-checkout-integration/references/testing.md kiasipay-webhooks/SKILL.md kiasipay-webhooks/references/verification.md; do mkdir -p ".claude/skills/$(dirname "$f")" curl -fsSL "$BASE/$f" -o ".claude/skills/$f" done
The rules the skills enforce
- No real money without you. The agent must not run or script anything that can charge a customer, and must not move an integration to live credentials, without you confirming that exact step. Tokens carry no test/live marker, so it treats every token as live.
- Secrets stay on your server. API tokens and webhook secrets are read from environment variables. The agent never puts them in browser code, commits, logs or chat, and never asks you to paste one — it tells you which variable to set.
- Your server sets the price. Amounts are never taken from the browser.
- Webhooks are verified first. Signature and timestamp checked before anything is parsed, never switched off for testing, and every event processed exactly once.
- The checkout is never framed or rebuilt. Popup or full-page redirect only — see Integration options.
- Data is not instructions. API responses, webhook payloads, customer-entered text and fetched pages are treated as data. If any of it asks the agent to change a key, URL, amount or recipient, the agent stops and asks you.
- Customer data stays put. Phone numbers and names are never sent to third parties or put in URLs, and are masked in logs.
- Gentle on the API. Webhooks before polling; any polling backs off and honours
429andRetry-After.
Your terms at checkout
The buyer's contract is with you, not with KiasiPay. You are the seller; you fulfil, you cancel, you refund. So the four questions you answered when setting the project up are not filed away — they are shown to every buyer before they pay, recorded with their acceptance, and emailed to both of you.
| Where it appears | What the buyer sees |
|---|---|
| Checkout, step 1 | A Who you are buying from panel naming you as the seller, and a control that opens your four answers in full. It opens itself the first time that browser checks out with you, and not again — so the buyer meets your refund policy before choosing a plan, rather than on the confirm screen. |
| Checkout, confirm step | The same answers, beside the tick box. What the buyer accepts and what they were shown are rendered from one component, so they cannot differ. |
| The accepted agreement | Frozen at the moment of acceptance and hashed (SHA-256). Editing your policies later changes what future buyers agree to and never rewrites an agreement already accepted — which is what makes it evidence. |
| After you edit the booking | Change a booking’s price or quantity once the buyer has accepted and paid something, and their acceptance is marked superseded: every payment link already shared stops working, no further payment can be collected, and the buyer is asked to accept the new terms on the same page as before. Their earlier acceptance is kept on record, not replaced. Edits before the first payment, and changes to the outstanding balance or the service date, need no re-acceptance. |
| A copy to the buyer and a copy to your business contact address, with the same four answers. |
Answer plainly and in your own words; these are read by customers, not by a legal team. They do not replace your own full terms — add a URL for those and it is linked alongside. Neither one can limit the buyer's statutory consumer rights.
Merchant onboarding requirements
KiasiPay collects on your behalf via Paystack. You don't need your own Paystack account — KiasiPay creates and manages a Paystack sub-account for you automatically as part of setting up your business. All you provide is where the money should go.
| Requirement | Detail |
|---|---|
| Business details | Your business name and contact details, provided during business setup. One record per organization. |
| Payment methods | Each way you take money is a channel, and a channel is both how a customer pays you and where that money lands: an M-PESA Till, an M-PESA Paybill, an Airtel Money business number, or a bank account. You can hold several at once, and each is registered separately with the payment service — the channel a buyer picks at checkout decides which of your destinations receives the money. Manage them on Workspace → Payment methods. Bank account numbers are encrypted at rest and only ever shown to you masked (last 4 digits). |
| Per-project channels | A project offers only the channels you attach to it, so a buyer at checkout sees exactly the ways that project accepts. Pick them on the Payment Rules step of the project wizard — you can add a new channel from there without losing the form. |
| Pesalink enablement | Bank transfer needs our payment provider to switch Pesalink on for your account — that is separate from your account existing, and it is the one method that isn't automatic. M-PESA works as soon as your business is approved. Check the How you get paid list on your Payment methods page, and contact support if buyers report bank transfer failing. See Pesalink. |
transaction_charge; fee retention at the rail must therefore be
confirmed with Paystack before an automated refund workflow is enabled.
Fulfilment Marketplace
Signed-in merchants can source replacement stock for a paid booking through the Merchant Marketplace. The customer booking and payment stay with the original merchant. A supplier payment is agreed and settled directly between the merchants; KiasiPay records the fixed terms and status but does not hold, process, or guarantee that payment.