Appearance
Quickstart: direct charge
Take a mobile money payment without sending the payer anywhere. Your server creates a charge, MOOKHPay sends the prompt straight to the payer's phone, and your screen waits for the answer.
This guide runs on staging with the test numbers, so nothing reaches a phone and no money moves. Staging issues only mkp_test_ keys, and a charge made with an mkp_test_ key is always a test charge.
Before you start
- Direct charges must be switched on for the deployment. Where they are off,
/chargesanswers404. - You need a key with the
charges:writescope. In an organisation only an Owner can be issued one: in the hub, API Integrations, API Keys, Secret Key, the Owner chooses Create A Key (or Replace Key), ticks Direct Charges and enters their PIN. Replacing a key keeps the old one working for 24 hours. See API keys and scopes.
sh
export MOOKHPAY_SECRET_KEY=mkp_test_EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEKEY1. Create the charge
Send the amount, your own reference for the order, and the payer's number. On a test key, use 254700000000 (Kenya) or 256700000000 (Uganda): it approves after 3 seconds.
referenceis required. Only one charge per reference can be pending at a time.Idempotency-Keyis required. The same key with the same body returns the same charge; the same key with a different body is refused with422and code3015.phoneis the number with its country code. A leading+is optional.
sh
curl -X POST https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
-H "Idempotency-Key: order-2071-attempt-1" \
-H "Content-Type: application/json" \
-d '{
"amount": 25000,
"reference": "order-2071",
"description": "Weekly veg box",
"payment_method": { "type": "mobile_money", "phone": "+254700000000" }
}'js
const base = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
const headers = {
Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
"Content-Type": "application/json",
};
const res = await fetch(`${base}/charges`, {
method: "POST",
headers: { ...headers, "Idempotency-Key": "order-2071-attempt-1" },
body: JSON.stringify({
amount: 25000,
reference: "order-2071",
description: "Weekly veg box",
payment_method: { type: "mobile_money", phone: "+254700000000" },
}),
});
const body = await res.json();
if (!body.ok) throw new Error(`${res.status} ${body.code}: ${body.description}`);
const charge = body.data;
console.log(charge.id, charge.status, charge.next_action.display);python
import os
import requests
BASE = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant"
AUTH = {"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"}
res = requests.post(
f"{BASE}/charges",
headers={**AUTH, "Idempotency-Key": "order-2071-attempt-1"},
json={
"amount": 25000,
"reference": "order-2071",
"description": "Weekly veg box",
"payment_method": {"type": "mobile_money", "phone": "+254700000000"},
},
timeout=15,
)
body = res.json()
if not body["ok"]:
raise RuntimeError(f"{res.status_code} {body['code']}: {body['description']}")
charge = body["data"]
print(charge["id"], charge["status"], charge["next_action"]["display"])php
<?php
$base = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
$ch = curl_init("$base/charges");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("MOOKHPAY_SECRET_KEY"),
"Idempotency-Key: order-2071-attempt-1",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode([
"amount" => 25000,
"reference" => "order-2071",
"description" => "Weekly veg box",
"payment_method" => ["type" => "mobile_money", "phone" => "+254700000000"],
]),
]);
$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']}");
}
$charge = $body["data"];
echo $charge["id"], " ", $charge["status"], " ", $charge["next_action"]["display"], PHP_EOL;The prompt is sent during the call. The answer is 201 Created:
json
{
"ok": true,
"description": "Charge created",
"data": {
"id": "ch_ke_5b0e2d9c4a7f1e3b8c6d2a90",
"status": "pending",
"test": true,
"amount": 25000,
"currency": "KES",
"fee": 0,
"net": 25000,
"reference": "order-2071",
"description": "Weekly veg box",
"payment_method": { "type": "mobile_money", "rail": "mpesa", "phone": "+254 7•• ••• 000" },
"next_action": {
"type": "await_payer",
"expires_at": "2026-11-20T09:06:00.000Z",
"display": "Enter your M-Pesa PIN on your phone"
},
"failure": null,
"receipt_number": null,
"hosted_url": "https://mookhpay.co/checkout/cs_ke_1a2b3c4d5e6f7a8b9c0d1e2f",
"metadata": {},
"expires_at": "2026-11-20T09:06:00.000Z",
"created_at": "2026-11-20T09:00:00.000Z"
}
}Show next_action.display to the payer, and store id with the order. Unlike a checkout, a charge's amount is a number. A mobile money charge expires 6 minutes after it is made (the prompt's 5 minutes plus a minute's grace, by default).
2. Wait for the answer
Read the charge every 2 seconds while it is pending, and stop at next_action.expires_at. Each read also moves the charge on if its payment has settled.
sh
curl https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges/ch_ke_5b0e2d9c4a7f1e3b8c6d2a90 \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"js
const base = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
const auth = { Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}` };
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
export async function waitForCharge(charge) {
const stopAt = Date.parse(charge.next_action?.expires_at ?? charge.expires_at);
let current = charge;
while (current.status === "pending" && Date.now() < stopAt) {
await sleep(2000);
const res = await fetch(`${base}/charges/${current.id}`, { headers: auth });
const body = await res.json();
if (body.ok) current = body.data;
}
return current;
}python
import os
import time
from datetime import datetime
import requests
BASE = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant"
AUTH = {"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"}
def wait_for_charge(charge: dict) -> dict:
until = (charge.get("next_action") or {}).get("expires_at") or charge["expires_at"]
stop_at = datetime.fromisoformat(until.replace("Z", "+00:00")).timestamp()
current = charge
while current["status"] == "pending" and time.time() < stop_at:
time.sleep(2)
body = requests.get(f"{BASE}/charges/{current['id']}", headers=AUTH, timeout=15).json()
if body["ok"]:
current = body["data"]
return currentphp
<?php
function wait_for_charge(array $charge): array
{
$base = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
$until = $charge["next_action"]["expires_at"] ?? $charge["expires_at"];
$stopAt = strtotime($until);
$current = $charge;
while ($current["status"] === "pending" && time() < $stopAt) {
sleep(2);
$ch = curl_init("$base/charges/" . rawurlencode($current["id"]));
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);
if ($body["ok"] ?? false) {
$current = $body["data"];
}
}
return $current;
}3. Read the outcome
status | Meaning | What to do |
|---|---|---|
succeeded | The payment is booked. receipt_number is set | Fulfil the order once |
failed | The payer did not pay. failure.code says why | Show failure.message or your own words, and offer to try again with a new charge |
expired | Nobody answered before expires_at | Offer to try again |
cancelled | You cancelled it | Nothing |
pending after expires_at | Your last read came before the charge moved | Read it once more, or wait for the webhook |
failure.code | Meaning |
|---|---|
payer_cancelled | The payer cancelled the prompt |
insufficient_funds | The payer did not have enough money |
wrong_pin | The payer entered a wrong PIN |
prompt_timed_out | The prompt was not answered in time |
phone_unreachable | The phone could not be reached |
limit_exceeded | The payment is over a limit on the payer's account |
rail_unavailable | The mobile money network could not take the payment |
declined | Declined for another reason |
Try the other test numbers to see each path: 254700000001 fails with insufficient_funds, 254700000002 fails with prompt_timed_out after 60 seconds, and 254700000003 fails with payer_cancelled. Each new attempt needs a new Idempotency-Key; the same reference can be used again once the previous charge has ended.
A charge can succeed after it expired
If the payer approves a prompt that was already on their phone when the charge expired or was cancelled, the payment is still booked and the charge moves to succeeded, and payment.succeeded is sent. Treat the webhook as the source of truth and do not cancel an order the moment a charge expires.
To hear the outcome without polling, subscribe an endpoint to payment.succeeded, payment.failed and charge.expired. The payment events carry the charge id in charge. See Event catalogue.
Pay Bill instead of a prompt
In Kenya, where the deployment has M-Pesa Pay Bill on, a charge can give the payer a business number and account number to pay from the M-Pesa menu instead. Pay Bill is real money only: a test key is refused with 400 and code 3004, so this part runs in production, against your production host with an mkp_live_ key. The samples keep the staging host only to match the rest of the page.
sh
curl -X POST https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
-H "Idempotency-Key: order-2072-attempt-1" \
-H "Content-Type: application/json" \
-d '{
"amount": 25000,
"reference": "order-2072",
"payment_method": { "type": "paybill" }
}'js
const res = await fetch("https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
"Idempotency-Key": "order-2072-attempt-1",
"Content-Type": "application/json",
},
body: JSON.stringify({ amount: 25000, reference: "order-2072", payment_method: { type: "paybill" } }),
});
const { ok, data, code } = await res.json();
if (!ok) throw new Error(`refused: ${code}`);
const { business_number, account_number, amount } = data.next_action;python
import os
import requests
BASE = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant"
AUTH = {"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"}
res = requests.post(
f"{BASE}/charges",
headers={**AUTH, "Idempotency-Key": "order-2072-attempt-1"},
json={"amount": 25000, "reference": "order-2072", "payment_method": {"type": "paybill"}},
timeout=15,
)
body = res.json()
if not body["ok"]:
raise RuntimeError(f"refused: {body['code']}")
step = body["data"]["next_action"]
print(step["business_number"], step["account_number"], step["amount"])php
<?php
$ch = curl_init("https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
"Authorization: Bearer " . getenv("MOOKHPAY_SECRET_KEY"),
"Idempotency-Key: order-2072-attempt-1",
"Content-Type: application/json",
],
CURLOPT_POSTFIELDS => json_encode([
"amount" => 25000,
"reference" => "order-2072",
"payment_method" => ["type" => "paybill"],
]),
]);
$body = json_decode(curl_exec($ch), true);
curl_close($ch);
if (!$body["ok"]) {
throw new RuntimeException("refused: " . $body["code"]);
}
$step = $body["data"]["next_action"];The charge answers with what to show the payer:
json
"next_action": {
"type": "pay_to_paybill",
"business_number": "4087123",
"account_number": "CS40271936",
"amount": 25000,
"expires_at": "2026-11-20T09:30:00.000Z"
}Show the business number, the account number and the amount (in minor units: 25000 is KES 250.00). A Pay Bill charge waits 30 minutes by default. Wait for it the same way: poll, or listen for the webhook. payer_email is not taken on a Pay Bill charge.
Next
- Direct charges: the full lifecycle, retries, cancelling and limits
- Card payments: cards with the card element (production only)
- Create a charge
- Testing