Accept SendPesa on your website
1. No code: a Pay button
Create a payment link in your dashboard, then use Copy website button and paste it into your site. Customers pay on a SendPesa page by mobile money or card.
2. With code: the API
Every request needs your API key: Authorization: Bearer spk.…. Keep it on your server, never in a web page.
Create a payment link for an order
curl -X POST https://business.sendpesa.com/api/v1/payment-links \
-H "Authorization: Bearer $SENDPESA_KEY" -H "Content-Type: application/json" \
-d '{"amount": 25000, "description": "Order #1042", "expiresInMinutes": 60}'
# → { "url": "https://business.sendpesa.com/pay/…", "qrSvg": "<svg…", "expiresAt": "…" }Charge a customer's phone directly
curl -X POST https://business.sendpesa.com/api/v1/collections \
-H "Authorization: Bearer $SENDPESA_KEY" -H "Content-Type: application/json" \
-d '{"phone": "+255712345678", "amount": 25000, "method": "mpesa"}'
# → 202 { "reference": "col_…" } The customer approves on their phone.
# method: mpesa, airtel, mixx, halopesa, or "card" (returns redirectUrl)Check a payment
curl "https://business.sendpesa.com/api/v1/collections?ref=col_…" -H "Authorization: Bearer $SENDPESA_KEY"
# → { "status": "APPLIED" } (PENDING, APPLIED = paid, VOID = failed or expired)Balance and activity
GET https://business.sendpesa.com/api/v1/balance
GET https://business.sendpesa.com/api/v1/transactions3. Webhooks
Set a webhook address in your dashboard. We POST collection.succeeded or collection.failed with the payment reference. Each request carries a SendPesa-Signature: t=…,v1=… header: an HMAC-SHA256 of t + "." + body with your signing secret. Check it before trusting the message, and always confirm the status with GET /api/v1/collections before releasing goods.
4. Website checkout (Pay with SendPesa)
For a shop with a cart: your server creates a checkout session for the order, you send the shopper to its url, and they come back to your successUrl once paid. Each session takes one payment; the amount comes only from your server.
Create a session (on your server)
curl -X POST https://business.sendpesa.com/api/v1/checkout-sessions \
-H "Authorization: Bearer $SENDPESA_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: order-1042" \
-d '{"amount": 25000, "orderId": "1042", "description": "2 x T-shirt",
"successUrl": "https://shop.example/thanks", "cancelUrl": "https://shop.example/cart",
"metadata": {"customer": "c_77"}}'
# → 201 { "id": "cs_…", "url": "https://business.sendpesa.com/pay/c/cs_…", "status": "open",
# "amount": 25000, "currency": "TZS", "orderId": "1042", "expiresAt": "…" }Send the shopper to the session
Redirect the browser to url. The shopper picks mobile money (or card/crypto where on) and pays. cancelUrl is optional and shows as a link back to your shop. Sessions expire after expiresInMinutes (default 60, up to 1440); send the same Idempotency-Key to retry a create safely.
Handle the success URL
Once paid we send the shopper to successUrl with session_id, order_id and status=paid added to its query. Anyone can type that address, so never fulfil the order from it alone: confirm with the webhook checkout.session.completed (or GET the session) first. Failed webhooks are retried after 1 min, 5 min, 30 min, 2 h and 6 h with the same event id, so dedupe on it.
https://shop.example/thanks?session_id=cs_…&order_id=1042&status=paid
# webhook body
{ "id": "evt_…", "type": "checkout.session.completed", "sessionId": "cs_…", "orderId": "1042",
"amount": 25000, "currency": "TZS", "reference": "col_…", "metadata": { "customer": "c_77" } }Verify the webhook signature (Node)
import crypto from "node:crypto";
// rawBody: the request body exactly as received (not re-serialised JSON)
function verifySendPesa(rawBody, header, secret, toleranceSeconds = 300) {
const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
const t = Number(parts.t);
if (!t || Math.abs(Date.now() / 1000 - t) > toleranceSeconds) return false;
const expected = crypto.createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
const got = Buffer.from(parts.v1 ?? "", "hex");
return got.length === expected.length / 2 && crypto.timingSafeEqual(got, Buffer.from(expected, "hex"));
}
// verifySendPesa(rawBody, req.headers["sendpesa-signature"], process.env.SENDPESA_WEBHOOK_SECRET)Check a session
curl https://business.sendpesa.com/api/v1/checkout-sessions/cs_… -H "Authorization: Bearer $SENDPESA_KEY"
# → { "status": "paid", "reference": "col_…", "paidAt": "…", … } (open, paid, expired, cancelled)
curl -X POST https://business.sendpesa.com/api/v1/checkout-sessions/cs_…/cancel -H "Authorization: Bearer $SENDPESA_KEY"Pay with SendPesa button
Add a ready-made button with one script tag. Your route (here /create-sendpesa-session) creates the session above with your secret key, taking the amount from your own database, and returns { "url": session.url }. The button never sees your secret key (it refuses one), and only opens SendPesa pay pages over https. Options: data-label, data-theme="light", data-networks="false". Live demo: /checkout-demo.
<script src="https://business.sendpesa.com/v1/checkout.js" async></script>
<div data-sendpesa-button
data-session-endpoint="/create-sendpesa-session"
data-amount="25000" data-order-id="ORDER-1042"></div>No server? For a fixed-price item, point the button at a payment link: data-link="…/pay/YOUR_LINK_TOKEN".
5. Subscriptions (weekly or monthly billing)
Bill a customer's mobile money every week or month. The first payment prompt goes to their phone straight away. Each later billing date sends a new prompt, which they approve with their PIN like any other payment.
curl -X POST https://business.sendpesa.com/api/v1/subscriptions \
-H "Authorization: Bearer $SENDPESA_KEY" -H "Content-Type: application/json" \
-H "Idempotency-Key: member-883-plan" \
-d '{"phone": "+255712345678", "method": "mpesa", "amount": 15000, "interval": "month",
"description": "Gym membership", "customerId": "member-883"}'
# → 201 { "id": "sub_…", "status": "incomplete", "nextChargeAt": …, "reference": "col_…" }
GET https://business.sendpesa.com/api/v1/subscriptions?status=active
GET https://business.sendpesa.com/api/v1/subscriptions/sub_… # with its charges
DELETE https://business.sendpesa.com/api/v1/subscriptions/sub_… # cancel- If the customer doesn't approve the first payment, the subscription ends: we never keep prompting a phone that never agreed.
- A failed renewal is tried again 4 hours, 1 day and 3 days later (status
past_due). After the third retry fails, the subscription ends. - Prompts are only sent between 08:00 and 20:00 East Africa Time.
- About a day before each renewal, the customer gets a WhatsApp reminder with the amount, date and network, so the prompt doesn't come as a surprise. It includes a link where the customer can cancel themselves (reason
cancelled_by_customer). Not sent for test subscriptions. - Monthly billing keeps the day of the month: a subscription started on the 31st bills on the last day of shorter months.
- Cancel with
DELETE /api/v1/subscriptions/sub_…, or from Subscriptions in your dashboard. Test keys createsub_test_…subscriptions that bill your test balance.
Webhooks: each payment sends collection.succeeded or collection.failed with subscriptionId, then subscription.activated, subscription.renewed, subscription.payment_failed or subscription.cancelled (with reason).
6. Test mode
Build and test your integration without real money. Switch your dashboard to Test to create a test key (it starts with spk_test.) and a separate test webhook. Call the same endpoints with the test key: collections, payouts, refunds, payment links, checkout sessions, balance and transactions. Test money lives in a separate test balance: it never reaches a real phone or card, never touches your live balance, and can't be withdrawn. Test references start with col_test_, pay_test_ and cs_test_.
curl -X POST https://business.sendpesa.com/api/v1/collections \
-H "Authorization: Bearer $SENDPESA_TEST_KEY" -H "Content-Type: application/json" \
-d '{"phone": "+255700000001", "amount": 25000, "method": "mpesa"}'
# → 202 { "reference": "col_test_…", "connector": "sandbox", "livemode": false, … }Test phone numbers (any network; use your country code, e.g. +255 or 0…)
| Number | Result |
|---|---|
| +255 700 000 001 | Succeeds after about 3 seconds (collection.succeeded) |
| +255 700 000 002 | Declined by the payer (DECLINED) |
| +255 700 000 003 | Prompt not answered: fails as expired (EXPIRED) |
| +255 700 000 004 | Not enough money in the account (INSUFFICIENT_FUNDS) |
Any other number succeeds like …001. No prompt is ever sent. Test payouts may go to these numbers or your own phone.
Test card
With a test key, "method": "card" returns a redirectUrl to a SendPesa test card page with Succeed and Fail buttons. No card network is contacted. Crypto is not available in test mode.
livemode
API answers and webhook bodies carry "livemode": false in test mode and "livemode": true for real money. Hosted payment pages show an orange TEST MODE banner, and no SMS or app notification is sent for test payments. Webhooks are signed and retried exactly like live ones, with your test signing secret.
Test mode applies the same fees and monthly limit as your live account, so balances behave the same. Test keys can't reach shop, listings, bookings, QR or exchange endpoints.
Going live checklist
- Swap the
spk_test.key for your livespk.key, on your server only. - Set your live webhook in Live mode; it has its own signing secret. Keep the two secrets apart.
- Reject webhooks whose
livemodedoesn't match the key you run with, and never fulfil an order from a test event. - Remove test phone numbers from your code and fixtures.
- Activate your account (dashboard checklist) to withdraw and pay out, and to lift the monthly limit. Until then
POST /api/v1/payoutsanswers 403 withcode: "activation_required"; refunds to the payer still work.
Fees and limits
Mobile money 2.5%, card 3.5%, taken from each payment you receive, plus 2.5% of each withdrawal to mobile money. No monthly fee and no minimum volume. You can take payments as soon as your email is verified: up to TZS 200,000 a month until your account is activated. Withdrawals and payouts unlock once it is activated (staff approve your business details and documents); your balance keeps growing meanwhile.