Appearance
Quickstart: hosted checkout
Take a payment by sending the payer to a MOOKHPay page. Your server creates a checkout for a fixed amount, the payer pays on MOOKHPay's page by mobile money (or card, or M-Pesa Pay Bill where offered), and your server reads the checkout back before it fulfils the order.
This takes about fifteen minutes. You need a MOOKHPay account in the hub and a server that can make HTTPS calls.
A checkout from a secret key is real money, on staging too
Staging calls the real mobile money rails. Test with a small amount, such as KES 1, and your own phone. See Environments.
1. Get a key
- Open the hub while acting for your organisation (API Integrations is part of an organisation's account, not a personal one), then API Integrations, then the API Keys tab.
- In the Secret Key card, choose Create A Key and enter your PIN. An Owner is asked which scopes the key should have; Hosted Checkouts (
checkouts) is all this guide needs. A Member or Accountant gets acheckoutskey without being asked. - Copy the key. The hub shows it once.
- Put it in your server's environment:
sh
export MOOKHPAY_SECRET_KEY=mkp_test_EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEKEYThe examples use Kenya staging. For Uganda, use https://payments-ug-staging.mookhpay.co. See API keys and scopes.
2. Create the checkout
Create the checkout on your server when the payer chooses to pay. Work out the amount on your server from your own prices: the browser must never send the amount.
amountis an integer in minor units:100is KES 1.00,150000is KES 1,500.00.Idempotency-Keyis required. Use your order id, so a retry after a timeout returns the same checkout instead of making a second one.referenceis your order id. The payer sees it under the amount, and it comes back onreturn_url.
sh
curl -X POST https://payments-ke-staging.mookhpay.co/v1/payments/merchant/checkouts \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
-H "Idempotency-Key: order-1042" \
-H "Content-Type: application/json" \
-d '{
"amount": 100,
"reference": "order-1042",
"description": "1x Espresso",
"return_url": "https://shop.example.com/paid"
}'js
const base = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
const res = await fetch(`${base}/checkouts`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
"Idempotency-Key": "order-1042",
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: 100,
reference: "order-1042",
description: "1x Espresso",
return_url: "https://shop.example.com/paid",
}),
});
const body = await res.json();
if (!body.ok) throw new Error(`${res.status} ${body.code}: ${body.description}`);
const checkout = body.data;
console.log(checkout.id, checkout.url);python
import os
import requests
BASE = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant"
res = requests.post(
f"{BASE}/checkouts",
headers={
"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}",
"Idempotency-Key": "order-1042",
},
json={
"amount": 100,
"reference": "order-1042",
"description": "1x Espresso",
"return_url": "https://shop.example.com/paid",
},
timeout=15,
)
body = res.json()
if not body["ok"]:
raise RuntimeError(f"{res.status_code} {body['code']}: {body['description']}")
checkout = body["data"]
print(checkout["id"], checkout["url"])php
<?php
$base = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
$ch = curl_init("$base/checkouts");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("MOOKHPAY_SECRET_KEY"),
"Idempotency-Key: order-1042",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode([
"amount" => 100,
"reference" => "order-1042",
"description" => "1x Espresso",
"return_url" => "https://shop.example.com/paid",
]),
]);
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$body = json_decode($raw, true);
if (!$body["ok"]) {
throw new RuntimeException("$status {$body['code']}: {$body['description']}");
}
$checkout = $body["data"];
echo $checkout["id"], " ", $checkout["url"], PHP_EOL;A new checkout answers 201 Created. The same Idempotency-Key again answers 200 OK with the checkout it first made, as it stands now.
json
{
"ok": true,
"description": "Checkout created",
"data": {
"id": "cs_ke_3f9a1c7e5b2d4a8e6c0b91d7",
"url": "https://mookhpay.co/checkout/cs_ke_3f9a1c7e5b2d4a8e6c0b91d7",
"status": "open",
"test": false,
"amount": "100",
"currency": "KES",
"reference": "order-1042",
"description": "1x Espresso",
"line_items": null,
"return_url": "https://shop.example.com/paid",
"expires_at": "2026-11-20T09:30:00.000Z",
"created_at": "2026-11-20T09:00:00.000Z",
"payment": null
}
}Store data.id against the order. Note that amount comes back as a string of minor units. The checkout expires 30 minutes after it is made (the default) unless a payment is in flight.
3. Send the payer to url
Redirect the payer's browser to data.url. Use it exactly as given; do not build it yourself.
The page shows your name, the amount, description and reference. The payer cannot change the amount. They enter their phone number and approve the prompt on their phone.
When the payment completes, the page waits 3 seconds and then opens your return_url with three query parameters:
text
https://shop.example.com/paid?checkout=cs_ke_3f9a1c7e5b2d4a8e6c0b91d7&reference=order-1042&status=completedA failed payment does not redirect: the payer stays on the page and can try again. A payer who closes the tab never reaches return_url. So return_url tells you when to look, not what happened.
4. Confirm before you fulfil
Anyone can type your return address. Read the checkout with your key and fulfil only when status is completed. Fulfil each order once, even if this runs twice.
sh
curl https://payments-ke-staging.mookhpay.co/v1/payments/merchant/checkouts/cs_ke_3f9a1c7e5b2d4a8e6c0b91d7 \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"js
const base = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
export async function isPaid(checkoutId) {
const res = await fetch(`${base}/checkouts/${encodeURIComponent(checkoutId)}`, {
headers: { Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}` },
});
const body = await res.json();
if (!body.ok) return false;
return body.data.status === "completed";
}python
import os
import requests
BASE = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant"
def is_paid(checkout_id: str) -> bool:
res = requests.get(
f"{BASE}/checkouts/{checkout_id}",
headers={"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"},
timeout=15,
)
body = res.json()
return bool(body["ok"]) and body["data"]["status"] == "completed"php
<?php
function is_paid(string $checkoutId): bool
{
$base = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
$ch = curl_init("$base/checkouts/" . rawurlencode($checkoutId));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("MOOKHPAY_SECRET_KEY")],
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
return $body["ok"] && $body["data"]["status"] === "completed";
}A completed checkout carries the payment:
json
"payment": {
"intent_id": "pi_8d1e4b2a9c7f3e5d6a0b1c2d",
"status": "completed",
"amount_settled": "100",
"provider_receipt": "TKL2X9QW4R",
"reference": "SM8K2Q4X7P",
"phone": "254712345678"
}provider_receipt is the M-Pesa or MoMo receipt the payer received. reference is MOOKHPay's own receipt reference. A checkout made by another account answers 404 and code 2783, the same as an unknown id.
5. Get told without asking (optional)
A webhook tells your server the moment a payment succeeds or fails, including when the payer never comes back to return_url.
- In the hub, open API Integrations, then the Webhooks tab, and choose Add Endpoint and add your
httpsaddress with the eventspayment.succeededandpayment.failed. - Copy the endpoint's secret (
whsec_…) intoMOOKHPAY_WEBHOOK_SECRET. - Verify every delivery before you trust it, then confirm with
GET /checkouts/:idas above.
A delivery is a POST with the JSON body and two headers, X-Mookh-Timestamp and X-Mookh-Signature. The signature is sha256= and the hex HMAC-SHA256, keyed with the whole secret, of the timestamp, a ., and the raw body exactly as received.
sh
# A receiver is your own code, not a call. To see what one gets, send a
# sample event from the hub: API Integrations, Webhooks, Send Test.js
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyWebhook(rawBody, timestamp, signature) {
const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
if (!timestamp || !signature || !(age <= 300)) return false;
const expected =
"sha256=" +
createHmac("sha256", process.env.MOOKHPAY_WEBHOOK_SECRET)
.update(`${timestamp}.${rawBody}`)
.digest("hex");
const a = Buffer.from(expected);
const b = Buffer.from(signature);
return a.length === b.length && timingSafeEqual(a, b);
}python
import hashlib
import hmac
import os
import time
def verify_webhook(raw_body: bytes, timestamp: str, signature: str) -> bool:
if not timestamp or not signature or not timestamp.isdigit():
return False
if abs(int(time.time()) - int(timestamp)) > 300:
return False
mac = hmac.new(
os.environ["MOOKHPAY_WEBHOOK_SECRET"].encode(),
timestamp.encode() + b"." + raw_body,
hashlib.sha256,
)
return hmac.compare_digest("sha256=" + mac.hexdigest(), signature)php
<?php
function verify_webhook(string $rawBody, ?string $timestamp, ?string $signature): bool
{
if (!$timestamp || !$signature || !ctype_digit($timestamp)) {
return false;
}
if (abs(time() - (int) $timestamp) > 300) {
return false;
}
$expected = "sha256=" . hash_hmac(
"sha256",
$timestamp . "." . $rawBody,
getenv("MOOKHPAY_WEBHOOK_SECRET")
);
return hash_equals($expected, $signature);
}Answer 2xx within 8 seconds. Anything else is retried. See Set up webhooks and Verify signatures.
Next
- Hosted checkout: status, expiry, line items and the payer page
- Confirming payments
- Kahawa: this flow as a small shop on Cloudflare Pages
- Create a checkout
- Going live