Appearance
Build a creator marketplace
This tutorial builds the payments side of Sanaa Market, an invented marketplace where illustrators sell prints. Every illustrator gets a MOOKHPay account that Sanaa Market opens for them. Buyers pay the illustrator, Sanaa Market keeps a 10% fee from each sale, and illustrators see their earnings and get paid out without leaving the site.
By the end you have one Node file, server.mjs, that:
- opens a seller account when an illustrator signs up
- takes a payment for a print on the illustrator's behalf, with Sanaa Market's fee
- confirms the payment by reading it back and from a signed webhook
- keeps a copy of every movement on every seller account, for a dashboard
- pays an illustrator out with a signed request
- sends an illustrator to MOOKHPay with a one-time login link
Each MOOKHPay call is shown on its own first, in curl, Node, Python and PHP. The whole server is at the end. It uses Node 18 or later and nothing outside Node's standard library.
It does not cover your own sign-in, a real database or a storefront. The server keeps its data in memory so the payment code is easy to read; What to change for production lists what to replace.
What you need
| Thing | Where it comes from |
|---|---|
| An organisation switched on as a platform | MOOKHPay staff switch it on and agree your fee share, daily payout cap and daily account limit. Until then every platform route answers 403 and code 2942. See How platforms work |
| A secret key with the scopes below | Only an Owner can be issued platform scopes. The Owner chooses them on Create A Key in the hub, and the PIN is bound to them; see API keys and scopes |
A payout signing secret (mps_…) | In the hub, API Integrations, made by an Owner with their PIN. It is shown once. See Pay out sellers |
A webhook endpoint and its secret (whsec_…) | In the hub, API Integrations, Webhooks. See Set up webhooks |
The key needs these scopes. A scope cannot be added to a key later; issuing a new key replaces the old one.
| Scope | Used for |
|---|---|
accounts:write | Opening seller accounts |
accounts:read | Balances, transactions and the all-accounts feed |
accounts:link | Asking an illustrator who already has MOOKHPay to link their account |
checkouts | Opening and reading hosted checkouts |
payments:write | Taking a payment on a seller's behalf with a fee |
payouts:write | Paying a seller out |
login_links:write | The "View on MOOKHPay" button |
Subscribe the endpoint to payment.succeeded, payment.failed, payout.paid, payout.failed, account.created, account.linked, account.claimed and account.disconnected.
Set four environment variables:
sh
export MOOKHPAY_API="https://payments-ke-staging.mookhpay.co/v1/payments/merchant"
export MOOKHPAY_SECRET_KEY="mkp_test_…"
export MOOKHPAY_PAYOUT_SECRET="mps_…"
export MOOKHPAY_WEBHOOK_SECRET="whsec_…"Staging moves real money for checkouts
A hosted checkout made with a secret key is never a test checkout, on staging included. Test a sale with a small price and your own phone. Seller accounts created on staging are real accounts too. See Testing.
The examples use Kenya (KES, +254). For Uganda, use the Uganda host, UGX and +256: a key reaches only accounts in its own country.
Open a seller account when an illustrator signs up
When an illustrator signs up on Sanaa Market and accepts MOOKHPay's terms there, create their account with POST /accounts.
| Field | What Sanaa Market sends |
|---|---|
phone | The illustrator's own mobile number in E.164, +254 and nine digits |
first_name, last_name | Their name, 1 to 100 characters each |
external_reference | Sanaa Market's own creator id. Unique among your accounts, 1 to 100 printable ASCII characters with no spaces |
terms.accepted_at | When they accepted MOOKHPay's terms on your site, ISO 8601 with a time zone. It cannot be more than five minutes in the future |
terms.version | Which version of the terms they saw, such as 2026-11 |
email and username are optional. Any other field is refused. MOOKHPay records the IP address your request came from with the terms.
Send an Idempotency-Key. Derive it from your creator id, so a retry after a timeout returns the same account (200) rather than failing. The same key with a different body answers 422 and code 3015.
sh
curl -X POST "$MOOKHPAY_API/accounts" \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
-H "Idempotency-Key: open-account-creator_1042" \
-H "Content-Type: application/json" \
-d '{
"phone": "+254712345678",
"first_name": "Wanjiku",
"last_name": "Kamau",
"email": "[email protected]",
"external_reference": "creator_1042",
"terms": { "accepted_at": "2026-11-20T09:14:03Z", "version": "2026-11" }
}'js
const res = await fetch(`${process.env.MOOKHPAY_API}/accounts`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
"Idempotency-Key": "open-account-creator_1042",
"Content-Type": "application/json",
},
body: JSON.stringify({
phone: "+254712345678",
first_name: "Wanjiku",
last_name: "Kamau",
email: "[email protected]",
external_reference: "creator_1042",
terms: { accepted_at: "2026-11-20T09:14:03Z", version: "2026-11" },
}),
});
const body = await res.json();
if (res.status === 409 && body.code === 2944) {
// The phone already has a MOOKHPay account: ask them to link it instead.
} else if (!body.ok) {
throw new Error(`${res.status} ${body.code}: ${body.description}`);
} else {
console.log(body.data.id); // acct_ke_…
}python
import os
import requests
res = requests.post(
f"{os.environ['MOOKHPAY_API']}/accounts",
headers={
"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}",
"Idempotency-Key": "open-account-creator_1042",
},
json={
"phone": "+254712345678",
"first_name": "Wanjiku",
"last_name": "Kamau",
"email": "[email protected]",
"external_reference": "creator_1042",
"terms": {"accepted_at": "2026-11-20T09:14:03Z", "version": "2026-11"},
},
timeout=30,
)
body = res.json()
if res.status_code == 409 and body["code"] == 2944:
pass # The phone already has a MOOKHPay account: ask them to link it instead.
elif not body["ok"]:
raise RuntimeError(f"{res.status_code} {body['code']}: {body['description']}")
else:
print(body["data"]["id"]) # acct_ke_…php
<?php
$ch = curl_init(getenv('MOOKHPAY_API') . '/accounts');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY'),
'Idempotency-Key: open-account-creator_1042',
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'phone' => '+254712345678',
'first_name' => 'Wanjiku',
'last_name' => 'Kamau',
'email' => '[email protected]',
'external_reference' => 'creator_1042',
'terms' => ['accepted_at' => '2026-11-20T09:14:03Z', 'version' => '2026-11'],
]),
]);
$body = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status === 409 && $body['code'] === 2944) {
// The phone already has a MOOKHPay account: ask them to link it instead.
} elseif (!$body['ok']) {
throw new RuntimeException("$status {$body['code']}: {$body['description']}");
} else {
echo $body['data']['id'], PHP_EOL; // acct_ke_…
}The answer is 201 with the account:
json
{
"ok": true,
"description": "Account created",
"data": {
"id": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"username": "wanjikukamau4821",
"status": "active",
"origin": "created",
"external_reference": "creator_1042",
"requirements": { "currently_due": ["identity"], "pending": [] },
"capabilities": { "payments": true, "payouts": true },
"created_at": "2026-11-20T09:14:05.000Z"
}
}Store data.id against the creator. Every later call names the account by it. It is your platform's id for the account, not the illustrator's username.
MOOKHPay texts the illustrator that Sanaa Market opened an account for them and that they set a PIN with Forgot PIN in MOOKHPay. Until they do, nobody can sign in to the account with a PIN. Payments can still be taken for them straight away, and account.created arrives at your endpoint.
The ledger sets up the wallet just after the account is made. A checkout for the seller in the first moments can answer 409 and code 2709; retry after a few seconds.
When the illustrator already has MOOKHPay
A phone number that already has a MOOKHPay account answers 409 and code 2944, and nothing is created. You cannot open a second account for that person, and you get no access to theirs. Ask them to link it with POST /account-links:
sh
curl -X POST "$MOOKHPAY_API/account-links" \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
-H "Idempotency-Key: link-account-creator_1042" \
-H "Content-Type: application/json" \
-d '{
"phone": "+254712345678",
"scopes": ["accounts:read", "payments:write", "payouts:write", "login_links:write"]
}'js
const res = await fetch(`${process.env.MOOKHPAY_API}/account-links`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
"Idempotency-Key": "link-account-creator_1042",
"Content-Type": "application/json",
},
body: JSON.stringify({
phone: "+254712345678",
scopes: ["accounts:read", "payments:write", "payouts:write", "login_links:write"],
}),
});
const { data } = await res.json();
// Send the illustrator to data.url now (it is shown once); store data.id as the creator's linkRequestId.python
res = requests.post(
f"{os.environ['MOOKHPAY_API']}/account-links",
headers={
"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}",
"Idempotency-Key": "link-account-creator_1042",
},
json={
"phone": "+254712345678",
"scopes": ["accounts:read", "payments:write", "payouts:write", "login_links:write"],
},
timeout=30,
)
data = res.json()["data"] # send the illustrator to data["url"]; keep data["id"]php
<?php
$ch = curl_init(getenv('MOOKHPAY_API') . '/account-links');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY'),
'Idempotency-Key: link-account-creator_1042',
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'phone' => '+254712345678',
'scopes' => ['accounts:read', 'payments:write', 'payouts:write', 'login_links:write'],
]),
]);
$data = json_decode(curl_exec($ch), true)['data']; // send them to $data['url']The answer is 201 with id (plr_ke_…), url, expires_at and status (pending). Send the illustrator to url. They sign in to MOOKHPay with their own account, read what Sanaa Market asks for, and approve with their PIN. Nothing happens until they do, and the request expires after 30 minutes.
When they approve, MOOKHPay sends account.linked to your endpoint with the account id in account and data.link_id naming the link, whether or not you read the link; store the account id against the creator whose link it was. If you want your own screen to move on the moment they approve, also read GET /account-links/{id} every few seconds while they are on the approval screen, stopping at expires_at; once it reads approved it carries account. The url is in the 201 answer only: a replay with the same Idempotency-Key answers url null. See Link an existing account.
Sell a print
When a buyer chooses a print, Sanaa Market opens a hosted checkout on the illustrator's behalf. The price lives on your server; the buyer's browser sends only which print they want.
| Field | Value |
|---|---|
amount | The price in minor units. On a payment for a seller it must be whole currency units, a multiple of 100: KES 2,500 is 250000 |
on_behalf_of | The illustrator's account id. They are the payee |
platform_fee | Sanaa Market's fee in minor units, also a multiple of 100, at most the share MOOKHPay agreed with you, and leaving the seller at least 100 |
reference | Your order id, 1 to 64 characters. The buyer sees it on the checkout page, and it is added to return_url |
description | What the buyer sees, 1 to 140 characters |
return_url | Where the buyer lands after paying. https |
Sanaa Market's 10% of a KES 2,500 print is KES 250, 25000. Round a computed fee down to a multiple of 100 before sending it: a fee that is fractional, over your maximum or leaves the seller less than one whole unit answers 400 and code 3017.
sh
curl -X POST "$MOOKHPAY_API/checkouts" \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
-H "Idempotency-Key: order_5531" \
-H "Content-Type: application/json" \
-d '{
"amount": 250000,
"on_behalf_of": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"platform_fee": 25000,
"reference": "order_5531",
"description": "Nairobi at Dusk, A3 print",
"return_url": "https://sanaa.example/orders/return"
}'js
const res = await fetch(`${process.env.MOOKHPAY_API}/checkouts`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
"Idempotency-Key": "order_5531",
"Content-Type": "application/json",
},
body: JSON.stringify({
amount: 250000,
on_behalf_of: "acct_ke_9c2f41b07e5d38a6c1f0b294",
platform_fee: 25000,
reference: "order_5531",
description: "Nairobi at Dusk, A3 print",
return_url: "https://sanaa.example/orders/return",
}),
});
const body = await res.json();
if (!body.ok) throw new Error(`${res.status} ${body.code}: ${body.description}`);
// Redirect the buyer to body.data.url; store body.data.id with the order.python
res = requests.post(
f"{os.environ['MOOKHPAY_API']}/checkouts",
headers={
"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}",
"Idempotency-Key": "order_5531",
},
json={
"amount": 250000,
"on_behalf_of": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"platform_fee": 25000,
"reference": "order_5531",
"description": "Nairobi at Dusk, A3 print",
"return_url": "https://sanaa.example/orders/return",
},
timeout=30,
)
body = res.json()
if not body["ok"]:
raise RuntimeError(f"{res.status_code} {body['code']}: {body['description']}")
checkout = body["data"] # redirect to checkout["url"]; store checkout["id"]php
<?php
$ch = curl_init(getenv('MOOKHPAY_API') . '/checkouts');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY'),
'Idempotency-Key: order_5531',
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => json_encode([
'amount' => 250000,
'on_behalf_of' => 'acct_ke_9c2f41b07e5d38a6c1f0b294',
'platform_fee' => 25000,
'reference' => 'order_5531',
'description' => 'Nairobi at Dusk, A3 print',
'return_url' => 'https://sanaa.example/orders/return',
]),
]);
$body = json_decode(curl_exec($ch), true);
if (!$body['ok']) {
throw new RuntimeException("{$body['code']}: {$body['description']}");
}
header('Location: ' . $body['data']['url'], true, 303);The answer is 201. A checkout's amount is a string; platform_fee and net are numbers.
json
{
"ok": true,
"description": "Checkout created",
"data": {
"id": "cs_ke_4f1a9c03b2e8d7a6150c9e2f",
"url": "https://mookhpay.co/checkout/cs_ke_4f1a9c03b2e8d7a6150c9e2f",
"status": "open",
"test": false,
"amount": "250000",
"currency": "KES",
"reference": "order_5531",
"description": "Nairobi at Dusk, A3 print",
"line_items": null,
"return_url": "https://sanaa.example/orders/return",
"account": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"platform_fee": 25000,
"net": 225000,
"expires_at": "2026-11-20T10:02:11.000Z",
"created_at": "2026-11-20T09:32:11.000Z",
"payment": null
}
}Redirect the buyer to url exactly as returned. The page names the illustrator "via Sanaa Market", and the mobile-money prompt names the illustrator. A checkout made for a seller cannot be paid from a MOOKHPay balance (409, code 2946); mobile money and, where the deployment has it on, card can.
The Idempotency-Key is the order id, so a double click or a retry returns the checkout the first call made. A checkout's key returns that checkout whatever body comes with it, so never reuse an order id for a different order.
Confirm the sale before you ship
The buyer comes back to return_url with checkout, reference and status added to the query string. That is a hint anyone can type. Read the checkout with GET /checkouts/{id} before marking the order paid:
sh
curl "$MOOKHPAY_API/checkouts/cs_ke_4f1a9c03b2e8d7a6150c9e2f" \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"js
const res = await fetch(
`${process.env.MOOKHPAY_API}/checkouts/cs_ke_4f1a9c03b2e8d7a6150c9e2f`,
{ headers: { Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}` } },
);
const { data } = await res.json();
const paid = data.status === "completed";python
res = requests.get(
f"{os.environ['MOOKHPAY_API']}/checkouts/cs_ke_4f1a9c03b2e8d7a6150c9e2f",
headers={"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"},
timeout=30,
)
paid = res.json()["data"]["status"] == "completed"php
<?php
$ch = curl_init(getenv('MOOKHPAY_API') . '/checkouts/cs_ke_4f1a9c03b2e8d7a6150c9e2f');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY')],
]);
$data = json_decode(curl_exec($ch), true)['data'];
$paid = $data['status'] === 'completed';Ship only when status is completed and the checkout id is the one stored with that order. open means not paid yet; expired means it can no longer be paid. When it completes, the fee and the seller's share are booked together: 25000 to your organisation's main wallet and 225000 to the illustrator's.
Confirm it from the webhook too
A buyer can close the tab before the redirect. The payment.succeeded webhook is the record that does not depend on the browser. Sanaa Market's copy of it carries account, platform_fee and net:
json
{
"platform_fee": 25000,
"net": 225000,
"event": "payment.succeeded",
"checkout_id": "cs_ke_4f1a9c03b2e8d7a6150c9e2f",
"intent_id": "pi_ke_7d02c4a91e3b58f6a0d1c2b3",
"amount": "250000",
"currency": "KES",
"reference": "order_5531",
"rail": "mpesa",
"provider_receipt": "TKJ4XQ81PZ",
"ledger_reference": "SM8X2K4Q7",
"test": false,
"created_at": "2026-11-20T09:33:40.512Z",
"account": "acct_ke_9c2f41b07e5d38a6c1f0b294"
}Verify every delivery before trusting it. MOOKHPay sends x-mookh-timestamp (Unix seconds) and x-mookh-signature: sha256= and the hex HMAC-SHA256, keyed with the whole endpoint secret including whsec_, of the timestamp, a ., and the raw body exactly as it arrived. Compute it over the bytes you received, not over JSON you parsed and serialised again, compare in constant time, and refuse a timestamp more than five minutes from your clock.
sh
# Check a saved delivery by hand: body.json holds the raw body, TS the header.
TS=1763631220
{ printf '%s.' "$TS"; cat body.json; } \
| openssl dgst -sha256 -hmac "$MOOKHPAY_WEBHOOK_SECRET" -hex \
| sed 's/^.*= /sha256=/'js
import { createHmac, timingSafeEqual } from "node:crypto";
export function verifyWebhook(rawBody, timestamp, signature, secret) {
if (typeof timestamp !== "string" || typeof signature !== "string") return false;
if (!/^[0-9]+$/.test(timestamp)) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) return false;
const expected = Buffer.from(
"sha256=" +
createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest("hex"),
);
const given = Buffer.from(signature);
return given.length === expected.length && timingSafeEqual(given, expected);
}python
import hashlib
import hmac
import time
def verify_webhook(raw_body: bytes, timestamp: str, signature: str, secret: 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(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, string $secret): bool
{
if ($timestamp === null || $signature === null || !ctype_digit($timestamp)) {
return false;
}
if (abs(time() - (int) $timestamp) > 300) {
return false;
}
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
return hash_equals($expected, $signature);
}
$raw = file_get_contents('php://input');
$ok = verify_webhook(
$raw,
$_SERVER['HTTP_X_MOOKH_TIMESTAMP'] ?? null,
$_SERVER['HTTP_X_MOOKH_SIGNATURE'] ?? null,
getenv('MOOKHPAY_WEBHOOK_SECRET'),
);Answer 2xx within eight seconds and do the work after. Any other answer, a timeout or a redirect counts as a failure and is retried, about ten times over roughly twelve hours. Delivery is at least once, so the same event can arrive twice. Every event carries an id (evt_…) that is the same on every retry: Sanaa Market keeps a set of the ids it has handled and skips any it has seen. Marking an order paid is safe to repeat anyway, which is the stronger guard. See Retries and ordering.
payment.failed means one attempt failed. The buyer can try again on the same checkout until it expires, and a later attempt can still succeed, so do not cancel the order on payment.failed. It is sent at most once per checkout to each endpoint.
Show a seller dashboard
An illustrator's dashboard on Sanaa Market shows their balance and their sales. Read the balance live, and keep a copy of movements in your own store.
The balance
GET /accounts/{id}/balance answers every wallet the account holds, main first, in minor units:
sh
curl "$MOOKHPAY_API/accounts/acct_ke_9c2f41b07e5d38a6c1f0b294/balance" \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"js
const res = await fetch(
`${process.env.MOOKHPAY_API}/accounts/acct_ke_9c2f41b07e5d38a6c1f0b294/balance`,
{ headers: { Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}` } },
);
const { data } = await res.json();python
res = requests.get(
f"{os.environ['MOOKHPAY_API']}/accounts/acct_ke_9c2f41b07e5d38a6c1f0b294/balance",
headers={"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"},
timeout=30,
)
data = res.json()["data"]php
<?php
$ch = curl_init(getenv('MOOKHPAY_API') . '/accounts/acct_ke_9c2f41b07e5d38a6c1f0b294/balance');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY')],
]);
$data = json_decode(curl_exec($ch), true)['data'];json
{
"ok": true,
"description": "Balance",
"data": {
"account": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"currency": "KES",
"total": 450000,
"wallets": [{ "wallet": "main", "name": "Main", "balance": 450000 }]
}
}If the ledger does not answer, the call is 503 with code 2752. Show that the balance could not be read; never show 0 in its place.
Every sale, from one feed
GET /transactions is one feed across every account your platform reaches, newest first, up to 100 rows a page. Each row names its account. Sanaa Market pulls it on a timer into its own store and builds every dashboard from that copy, rather than asking MOOKHPay once per illustrator per page view.
The sync keeps one high-water mark: the newest created_at it has stored. Each run asks for movements from a few minutes before that mark (from is inclusive), follows next_cursor until it is null, and upserts each row. The small overlap catches a row committed just behind the mark, and the upsert makes the overlap harmless. A movement is identified by its id together with account, wallet and direction, because one transaction can produce more than one row.
sh
curl -G "$MOOKHPAY_API/transactions" \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
--data-urlencode "from=2026-11-20T09:00:00Z" \
--data-urlencode "limit=100"
# Next page: add --data-urlencode "cursor=<data.next_cursor>" and keep the same from.js
async function pullFeed(from) {
const rows = [];
let cursor = null;
do {
const query = new URLSearchParams({ from, limit: "100" });
if (cursor) query.set("cursor", cursor);
const res = await fetch(`${process.env.MOOKHPAY_API}/transactions?${query}`, {
headers: { Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}` },
});
const body = await res.json();
if (!body.ok) throw new Error(`${res.status} ${body.code}: ${body.description}`);
rows.push(...body.data.movements);
cursor = body.data.next_cursor;
} while (cursor);
return rows;
}python
def pull_feed(start: str) -> list:
rows, cursor = [], None
while True:
params = {"from": start, "limit": "100"}
if cursor:
params["cursor"] = cursor
res = requests.get(
f"{os.environ['MOOKHPAY_API']}/transactions",
headers={"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"},
params=params,
timeout=30,
)
body = res.json()
if not body["ok"]:
raise RuntimeError(f"{res.status_code} {body['code']}: {body['description']}")
rows.extend(body["data"]["movements"])
cursor = body["data"]["next_cursor"]
if not cursor:
return rowsphp
<?php
function pull_feed(string $from): array
{
$rows = [];
$cursor = null;
do {
$query = ['from' => $from, 'limit' => '100'];
if ($cursor !== null) {
$query['cursor'] = $cursor;
}
$ch = curl_init(getenv('MOOKHPAY_API') . '/transactions?' . http_build_query($query));
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY')],
]);
$body = json_decode(curl_exec($ch), true);
if (!$body['ok']) {
throw new RuntimeException("{$body['code']}: {$body['description']}");
}
array_push($rows, ...$body['data']['movements']);
$cursor = $body['data']['next_cursor'];
} while ($cursor !== null);
return $rows;
}A row looks like this. Amounts are numbers in minor units.
json
{
"id": "SM4H2PL9",
"account": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"wallet": "main",
"type": "system_topup",
"status": "completed",
"direction": "in",
"amount": 225000,
"fee": 0,
"description": "Nairobi at Dusk, A3 print",
"counterparty": null,
"source": "checkout",
"rail": "mpesa",
"external_reference": "TKJ4XQ81PZ",
"refunded_amount": 0,
"created_at": "2026-11-20T09:33:40.120Z"
}A row's type is one of system_topup, system_withdrawal, p2p_transfer, internal_transfer and transfer; a checkout sale is system_topup. The type query filter takes a different set (deposit, withdrawal, transfer, fee, adjustment). See Balances and dashboards. The cursor is opaque and signed for your platform; an edited one answers 400 and code 3012. When an illustrator disconnects Sanaa Market, their account drops out of the feed, history included, so keep what you have already stored if your own records need it. See Balances and dashboards.
For one illustrator's statement, GET /accounts/{id}/transactions pages one wallet's movements oldest first, with balance_after on each row.
Pay an illustrator out
Sanaa Market pays illustrators out when they ask. POST /accounts/{id}/payouts sends money from the illustrator's main wallet to the payout account they chose in MOOKHPay with their PIN, or, if they chose none, to their own phone. There is no destination field: Sanaa Market cannot choose or change where the money goes.
The body is amount (minor units, whole currency units, a multiple of 100) and an optional remarks (1 to 100 printable ASCII characters, shown on the illustrator's statement). Nothing else is accepted.
Every payout request is signed with the payout signing secret, so a leaked API key alone cannot pay anybody out. Send two headers:
| Header | Value |
|---|---|
X-Mookh-Timestamp | The current Unix time in seconds |
X-Mookh-Signature | sha256= and the lowercase hex HMAC-SHA256, keyed with the whole secret including mps_, of the timestamp, a ., and the raw request body |
Serialise the body once, sign that exact string and send that exact string. MOOKHPay refuses a timestamp more than 300 seconds from its clock, and a missing or wrong signature, with 401 and code 3021. Sign each attempt afresh: a retry needs a new timestamp and signature, and keeps the same Idempotency-Key.
sh
ACCOUNT=acct_ke_9c2f41b07e5d38a6c1f0b294
BODY='{"amount":400000,"remarks":"Sanaa Market sales, week 47"}'
TS=$(date +%s)
SIG=$(printf '%s.%s' "$TS" "$BODY" \
| openssl dgst -sha256 -hmac "$MOOKHPAY_PAYOUT_SECRET" -hex \
| sed 's/^.*= /sha256=/')
curl -X POST "$MOOKHPAY_API/accounts/$ACCOUNT/payouts" \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
-H "Idempotency-Key: payout-request-7781" \
-H "Content-Type: application/json" \
-H "X-Mookh-Timestamp: $TS" \
-H "X-Mookh-Signature: $SIG" \
--data-binary "$BODY"js
import { createHmac } from "node:crypto";
const account = "acct_ke_9c2f41b07e5d38a6c1f0b294";
const body = JSON.stringify({ amount: 400000, remarks: "Sanaa Market sales, week 47" });
const timestamp = Math.floor(Date.now() / 1000).toString();
const signature =
"sha256=" +
createHmac("sha256", process.env.MOOKHPAY_PAYOUT_SECRET)
.update(`${timestamp}.${body}`)
.digest("hex");
const res = await fetch(`${process.env.MOOKHPAY_API}/accounts/${account}/payouts`, {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
"Idempotency-Key": "payout-request-7781",
"Content-Type": "application/json",
"X-Mookh-Timestamp": timestamp,
"X-Mookh-Signature": signature,
},
body,
});
const answer = await res.json();python
import hashlib
import hmac
import json
import time
account = "acct_ke_9c2f41b07e5d38a6c1f0b294"
body = json.dumps(
{"amount": 400000, "remarks": "Sanaa Market sales, week 47"}, separators=(",", ":")
).encode()
timestamp = str(int(time.time()))
signature = "sha256=" + hmac.new(
os.environ["MOOKHPAY_PAYOUT_SECRET"].encode(),
timestamp.encode() + b"." + body,
hashlib.sha256,
).hexdigest()
res = requests.post(
f"{os.environ['MOOKHPAY_API']}/accounts/{account}/payouts",
headers={
"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}",
"Idempotency-Key": "payout-request-7781",
"Content-Type": "application/json",
"X-Mookh-Timestamp": timestamp,
"X-Mookh-Signature": signature,
},
data=body,
timeout=30,
)
answer = res.json()php
<?php
$account = 'acct_ke_9c2f41b07e5d38a6c1f0b294';
$body = json_encode(['amount' => 400000, 'remarks' => 'Sanaa Market sales, week 47']);
$timestamp = (string) time();
$signature = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $body, getenv('MOOKHPAY_PAYOUT_SECRET'));
$ch = curl_init(getenv('MOOKHPAY_API') . "/accounts/$account/payouts");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY'),
'Idempotency-Key: payout-request-7781',
'Content-Type: application/json',
"X-Mookh-Timestamp: $timestamp",
"X-Mookh-Signature: $signature",
],
CURLOPT_POSTFIELDS => $body,
]);
$answer = json_decode(curl_exec($ch), true);The payout is reserved from the wallet and sent to the rail during the call. The answer is 202 with the payout:
json
{
"ok": true,
"description": "Payout requested",
"data": {
"payout_id": "po_ke_0e7c3a19d4b2f68a5c1e9d07",
"account": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"status": "processing",
"amount": 400000,
"fee": 0,
"total": 400000,
"currency": "KES",
"remarks": "Sanaa Market sales, week 47",
"destination": { "rail": "mpesa", "phone_masked": "+254 7•• ••• 678" },
"approval_id": null,
"failure": null,
"created_at": "2026-11-20T11:02:44.000Z"
}
}What each status means for Sanaa Market's screen:
status | What it means | What Sanaa Market shows |
|---|---|---|
processing | Sent to the rail | "On its way" |
held | MOOKHPay is checking it before it leaves | "Being checked by MOOKHPay" |
awaiting_approval | The account is a company's; its owners must sign in MOOKHPay. approval_id names the approval. No money moves until they sign | "Waiting for your co-owners to approve" |
paid | The money reached the destination | "Paid" |
failed | It did not go. failure.code is rail_unavailable, recipient_unreachable, limit_exceeded or declined, and the money is back in the wallet | The failure.message |
The refusals worth handling on the screen:
| HTTP | Code | When | What to do |
|---|---|---|---|
422 | 2732 | The wallet does not hold the amount plus the payout fee (0 for now) | Show the balance and ask for less |
422 | 2947 | Over your platform's daily payout cap (East Africa Time). data has cap, used and remaining in minor units | Offer remaining, or try after midnight EAT |
422 | 2948 | Over the daily cap on money out for an unverified account you opened, where MOOKHPay switches it on. Same data | Tell the illustrator to finish verification in MOOKHPay |
422 | 2949 | No payout account and no phone, which happens for a business account | Ask the owners to set a payout account in MOOKHPay |
422 | 3040 | The illustrator's payout account or phone is not a number the rail can pay; data.source says which | Ask the illustrator to change it in MOOKHPay |
403 | 3025 | The account's access does not include payouts:write, which happens on a linked account whose owner did not grant it | Ask for a new link with that scope |
401 | 3021 | Signature missing, wrong, or timestamp too far out | Check the clock and that you sign the exact bytes you send |
A refused payout is stored against its Idempotency-Key: sending the same key and body again returns the same refusal. Use a new key for the corrected request. See Pay out sellers for the full list.
Sanaa Market's copy of payout.paid and payout.failed carries account, payout_id (your po_… id), intent_id and, on a failure, failure:
json
{
"event": "payout.failed",
"payout_id": "po_ke_0e7c3a19d4b2f68a5c1e9d07",
"batch_id": null,
"amount": "400000",
"currency": "KES",
"remarks": "Sanaa Market sales, week 47",
"rail": "mpesa",
"provider_receipt": null,
"ledger_reference": null,
"created_at": "2026-11-20T11:03:10.004Z",
"intent_id": "pi_ke_a19f0c27e4d3b85c6e1f2a90",
"account": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"failure": {
"code": "recipient_unreachable",
"message": "The number cannot receive this payout. The money is back in the wallet"
}
}A payout that never reached the rail sends no webhook: one a company's owners decline, or one MOOKHPay declines after holding it, moves to failed with no payout.failed. While a payout is held or awaiting_approval, read it with GET /accounts/{id}/payouts/{payout_id} now and then until it settles.
Add a "View on MOOKHPay" button
For anything Sanaa Market does not show, an illustrator can open MOOKHPay itself. When they press the button, mint a login link with POST /accounts/{id}/login-links and redirect them to it in the same response. The call takes no body and no Idempotency-Key; every call makes a new link.
sh
curl -X POST "$MOOKHPAY_API/accounts/acct_ke_9c2f41b07e5d38a6c1f0b294/login-links" \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"js
const res = await fetch(
`${process.env.MOOKHPAY_API}/accounts/acct_ke_9c2f41b07e5d38a6c1f0b294/login-links`,
{ method: "POST", headers: { Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}` } },
);
const { data } = await res.json();
// Respond 303 with Location: data.url, straight away.python
res = requests.post(
f"{os.environ['MOOKHPAY_API']}/accounts/acct_ke_9c2f41b07e5d38a6c1f0b294/login-links",
headers={"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"},
timeout=30,
)
url = res.json()["data"]["url"] # redirect to it nowphp
<?php
$ch = curl_init(getenv('MOOKHPAY_API') . '/accounts/acct_ke_9c2f41b07e5d38a6c1f0b294/login-links');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY')],
]);
$url = json_decode(curl_exec($ch), true)['data']['url'];
header('Cache-Control: no-store');
header("Location: $url", true, 303);The answer is 201 with url and expires_at. The link works once, for 60 seconds, and anyone who opens it in that time is signed in as the illustrator, so never store it, log it, email it or show it as text.
It opens a view-only MOOKHPay session of 30 minutes: balances, history and payment links. The session cannot send money or change settings. An illustrator who has not set a PIN yet can claim the account from inside it, with a code texted to their phone. A business account cannot have a login link (404, code 2943). Your platform can make 10 links an hour for one account by default, and your key 30 a minute; past either, 429 and code 3026. See Login links.
Handle claims and disconnections
Two events tell Sanaa Market what the illustrator did in MOOKHPay. They are read from MOOKHPay about once a minute, so they arrive up to a minute or so after the fact.
account.claimed means the illustrator set their PIN and owns the account in full. Sanaa Market stops showing the "set up your MOOKHPay PIN" reminder.
json
{
"event": "account.claimed",
"account": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"data": { "status": "active", "claimed_at": "2026-11-20T12:10:31.000Z" },
"created_at": "2026-11-20T12:10:31.000Z"
}account.disconnected means the illustrator removed Sanaa Market from Connected Apps in MOOKHPay, or closed their MOOKHPay account. From then on every call about that account answers 404 and code 2943, it drops out of the feed, and any session your login links opened ends. The account and its money stay with the illustrator. Stop listing their prints for sale, since you can no longer take payments for them.
json
{
"event": "account.disconnected",
"account": "acct_ke_9c2f41b07e5d38a6c1f0b294",
"data": { "revoked_at": "2026-11-21T08:45:02.000Z" },
"created_at": "2026-11-21T08:45:02.000Z"
}Deduplicate these on event, account and created_at.
The whole server
server.mjs puts the steps together. Run it with node server.mjs and the four environment variables set. Your MOOKHPay webhook endpoint must reach POST /webhooks/mookhpay over https; on your own machine, put a tunnel in front of port 3000.
js
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";
const API = process.env.MOOKHPAY_API;
const KEY = process.env.MOOKHPAY_SECRET_KEY;
const PAYOUT_SECRET = process.env.MOOKHPAY_PAYOUT_SECRET;
const WEBHOOK_SECRET = process.env.MOOKHPAY_WEBHOOK_SECRET;
const SITE = process.env.SITE_URL ?? "https://sanaa.example";
const FEE_SHARE = 0.1;
const TERMS_VERSION = "2026-11";
const db = {
creators: new Map(),
prints: new Map([
["nairobi-dusk", { title: "Nairobi at Dusk, A3 print", price: 250000, creatorId: "creator_1042" }],
]),
orders: new Map(),
payouts: new Map(),
movements: new Map(),
handledEvents: new Set(),
feedMark: null,
};
async function mookhpay(method, path, { body, idempotencyKey, headers = {} } = {}) {
const res = await fetch(`${API}${path}`, {
method,
headers: {
Authorization: `Bearer ${KEY}`,
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
...(idempotencyKey ? { "Idempotency-Key": idempotencyKey } : {}),
...headers,
},
body,
});
return { status: res.status, body: await res.json() };
}
function feeFor(price) {
return Math.floor((price * FEE_SHARE) / 100) * 100;
}
async function openSellerAccount(creator) {
const { status, body } = await mookhpay("POST", "/accounts", {
idempotencyKey: `open-account-${creator.id}`,
body: JSON.stringify({
phone: creator.phone,
first_name: creator.firstName,
last_name: creator.lastName,
external_reference: creator.id,
terms: { accepted_at: creator.termsAcceptedAt, version: TERMS_VERSION },
}),
});
if (body.ok) {
creator.accountId = body.data.id;
return { opened: true };
}
if (status === 409 && body.code === 2944) {
const link = await mookhpay("POST", "/account-links", {
idempotencyKey: `link-account-${creator.id}`,
body: JSON.stringify({
phone: creator.phone,
scopes: ["accounts:read", "payments:write", "payouts:write", "login_links:write"],
}),
});
if (!link.body.ok) throw new Error(`account link refused: ${link.body.code}`);
creator.linkRequestId = link.body.data.id;
return { opened: false, linkUrl: link.body.data.url };
}
throw new Error(`account refused: ${status} ${body.code} ${body.description}`);
}
async function checkAccountLink(creator) {
const { body } = await mookhpay("GET", `/account-links/${creator.linkRequestId}`);
if (body.ok && body.data.status === "approved") creator.accountId = body.data.account;
return body.ok ? body.data.status : null;
}
async function startOrder(printId) {
const print = db.prints.get(printId);
if (!print) return null;
const creator = db.creators.get(print.creatorId);
if (!creator?.accountId || creator.disconnected) return null;
const orderId = `order_${randomUUID().slice(0, 8)}`;
const order = { id: orderId, printId, creatorId: creator.id, paid: false, checkoutId: null };
db.orders.set(orderId, order);
const { status, body } = await mookhpay("POST", "/checkouts", {
idempotencyKey: orderId,
body: JSON.stringify({
amount: print.price,
on_behalf_of: creator.accountId,
platform_fee: feeFor(print.price),
reference: orderId,
description: print.title,
return_url: `${SITE}/orders/return`,
}),
});
if (!body.ok) throw new Error(`checkout refused: ${status} ${body.code} ${body.description}`);
order.checkoutId = body.data.id;
return body.data.url;
}
async function confirmOrder(orderId) {
const order = db.orders.get(orderId);
if (!order?.checkoutId) return null;
const { body } = await mookhpay("GET", `/checkouts/${order.checkoutId}`);
if (body.ok && body.data.status === "completed") order.paid = true;
return order;
}
function verifyWebhook(rawBody, timestamp, signature) {
if (typeof timestamp !== "string" || typeof signature !== "string") return false;
if (!/^[0-9]+$/.test(timestamp)) return false;
if (Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300) return false;
const expected = Buffer.from(
"sha256=" +
createHmac("sha256", WEBHOOK_SECRET).update(`${timestamp}.`).update(rawBody).digest("hex"),
);
const given = Buffer.from(signature);
return given.length === expected.length && timingSafeEqual(given, expected);
}
function subjectOf(event) {
if (event.event.startsWith("payment.")) return event.checkout_id;
if (event.event.startsWith("payout.")) return event.payout_id;
if (
event.event === "account.linked" ||
event.event === "account.claimed" ||
event.event === "account.disconnected"
) {
return `${event.account}:${event.created_at}`;
}
return event.account;
}
function creatorByAccount(accountId) {
for (const creator of db.creators.values()) if (creator.accountId === accountId) return creator;
return null;
}
function handleEvent(event) {
const key = `${event.event}:${subjectOf(event)}`;
if (db.handledEvents.has(key)) return;
db.handledEvents.add(key);
if (event.event === "payment.succeeded") {
const order = db.orders.get(event.reference);
if (order && order.checkoutId === event.checkout_id) order.paid = true;
} else if (event.event === "payout.paid" || event.event === "payout.failed") {
const payout = db.payouts.get(event.payout_id);
if (payout) {
payout.status = event.event === "payout.paid" ? "paid" : "failed";
payout.failure = event.failure;
}
} else if (event.event === "account.linked") {
for (const creator of db.creators.values()) {
if (creator.linkRequestId === event.data.link_id) {
creator.accountId = event.account;
creator.claimed = true;
}
}
} else if (event.event === "account.claimed") {
const creator = creatorByAccount(event.account);
if (creator) creator.claimed = true;
} else if (event.event === "account.disconnected") {
const creator = creatorByAccount(event.account);
if (creator) creator.disconnected = true;
}
}
async function syncFeed() {
const from = new Date((db.feedMark ?? Date.parse("2026-11-01T00:00:00Z")) - 5 * 60 * 1000);
let cursor = null;
do {
const query = new URLSearchParams({ from: from.toISOString(), limit: "100" });
if (cursor) query.set("cursor", cursor);
const { status, body } = await mookhpay("GET", `/transactions?${query}`);
if (!body.ok) throw new Error(`feed refused: ${status} ${body.code}`);
for (const row of body.data.movements) {
db.movements.set(`${row.account}:${row.id}:${row.wallet}:${row.direction}`, row);
db.feedMark = Math.max(db.feedMark ?? 0, Date.parse(row.created_at));
}
cursor = body.data.next_cursor;
} while (cursor);
}
async function dashboard(creator) {
const { status, body } = await mookhpay("GET", `/accounts/${creator.accountId}/balance`);
const sales = [...db.movements.values()]
.filter((row) => row.account === creator.accountId)
.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));
return {
balance: body.ok ? body.data : null,
balanceError: body.ok ? null : `${status} ${body.code}`,
sales,
claimed: creator.claimed ?? false,
};
}
async function requestPayout(creator, amount, idempotencyKey) {
const body = JSON.stringify({ amount, remarks: "Sanaa Market sales" });
const timestamp = Math.floor(Date.now() / 1000).toString();
const signature =
"sha256=" + createHmac("sha256", PAYOUT_SECRET).update(`${timestamp}.${body}`).digest("hex");
const answer = await mookhpay("POST", `/accounts/${creator.accountId}/payouts`, {
idempotencyKey,
body,
headers: { "X-Mookh-Timestamp": timestamp, "X-Mookh-Signature": signature },
});
if (answer.body.ok) {
db.payouts.set(answer.body.data.payout_id, { ...answer.body.data, creatorId: creator.id });
}
return answer;
}
async function loginLink(creator) {
const { status, body } = await mookhpay("POST", `/accounts/${creator.accountId}/login-links`);
if (!body.ok) throw new Error(`login link refused: ${status} ${body.code}`);
return body.data.url;
}
function readBody(req) {
return new Promise((resolve, reject) => {
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => resolve(Buffer.concat(chunks)));
req.on("error", reject);
});
}
function send(res, status, value, headers = {}) {
res.writeHead(status, { "Content-Type": "application/json", ...headers });
res.end(JSON.stringify(value));
}
function redirect(res, location) {
res.writeHead(303, { Location: location, "Cache-Control": "no-store" });
res.end();
}
const server = createServer(async (req, res) => {
const url = new URL(req.url, SITE);
const parts = url.pathname.split("/").filter(Boolean);
try {
if (req.method === "POST" && url.pathname === "/webhooks/mookhpay") {
const raw = await readBody(req);
if (!verifyWebhook(raw, req.headers["x-mookh-timestamp"], req.headers["x-mookh-signature"])) {
return send(res, 400, { error: "bad signature" });
}
send(res, 200, { received: true });
return handleEvent(JSON.parse(raw.toString("utf8")));
}
if (req.method === "POST" && url.pathname === "/creators") {
const input = JSON.parse((await readBody(req)).toString("utf8"));
const creator = {
id: `creator_${randomUUID().slice(0, 8)}`,
phone: input.phone,
firstName: input.first_name,
lastName: input.last_name,
termsAcceptedAt: new Date().toISOString(),
};
db.creators.set(creator.id, creator);
const outcome = await openSellerAccount(creator);
return send(res, 201, { creator: creator.id, ...outcome });
}
if (req.method === "POST" && parts[0] === "prints" && parts[2] === "buy") {
const checkoutUrl = await startOrder(parts[1]);
return checkoutUrl ? redirect(res, checkoutUrl) : send(res, 404, { error: "not for sale" });
}
if (req.method === "GET" && url.pathname === "/orders/return") {
const order = await confirmOrder(url.searchParams.get("reference"));
return send(res, order ? 200 : 404, order ? { order: order.id, paid: order.paid } : {});
}
const creator = parts[0] === "creators" ? db.creators.get(parts[1]) : null;
if (parts[0] === "creators" && !creator) return send(res, 404, { error: "no such creator" });
if (req.method === "GET" && creator && parts[2] === "link-status") {
return send(res, 200, { status: await checkAccountLink(creator) });
}
if (req.method === "GET" && creator && parts[2] === "dashboard") {
return send(res, 200, await dashboard(creator));
}
if (req.method === "POST" && creator && parts[2] === "payouts") {
const input = JSON.parse((await readBody(req)).toString("utf8"));
const answer = await requestPayout(creator, input.amount, input.request_id);
return send(res, answer.status, answer.body);
}
if (req.method === "POST" && creator && parts[2] === "mookhpay") {
return redirect(res, await loginLink(creator));
}
send(res, 404, { error: "not found" });
} catch (err) {
console.error(err);
if (!res.headersSent) send(res, 502, { error: "MOOKHPay call failed" });
}
});
setInterval(() => syncFeed().catch((err) => console.error("feed sync", err)), 60_000);
server.listen(3000, () => console.log("Sanaa Market on http://localhost:3000"));The routes, for trying it with curl against your own server:
| Route | Does |
|---|---|
POST /creators with phone, first_name, last_name | Opens the seller account, or returns a linkUrl if the phone already has MOOKHPay |
GET /creators/{id}/link-status | Polls the account link until it is approved |
POST /prints/nairobi-dusk/buy | Opens a checkout for the print's creator and redirects the buyer |
GET /orders/return?reference=… | Confirms the order with GET /checkouts/{id} |
POST /webhooks/mookhpay | Verifies and handles webhooks |
GET /creators/{id}/dashboard | Live balance plus the creator's movements from the synced feed |
POST /creators/{id}/payouts with amount and request_id | Signed payout. request_id is your own id for the illustrator's request, used as the Idempotency-Key |
POST /creators/{id}/mookhpay | Mints a login link and redirects |
The print in db.prints belongs to creator_1042; after creating a creator, point a print at the id POST /creators returned.
What to change for production
- Keys and hosts. Production issues
mkp_live_keys and has its own hosts; the paths are the same. Issue a production key with the same scopes, make a production payout signing secret and webhook endpoint, and changeMOOKHPAY_API. See Go-live checklist. - A real database. Replace
dbwith tables for creators, orders, payouts, movements, handled events and the feed mark. Write the idempotency key with the order or payout request before calling MOOKHPay, so a crash and retry reuses it. - Your own sign-in. The
/creators/{id}/…routes trust the id in the path. Put them behind your own session, so an illustrator can only see their own dashboard, pay out their own wallet and open their own login link. - Handle webhooks off the request. Answer
200and put the event on a queue; MOOKHPay waits eight seconds at most. - Retry with care. Retry a timed-out call with the same
Idempotency-Key, and for payouts with a new timestamp and signature. A503(codes2752,3016,2782) is safe to retry after a short wait. A4xxis not, until you change the request. - Rate limits. Account reads, balances and the feed share 120 requests a minute for your key; payout requests have 60 a minute. Sync the feed on a timer rather than per page view, and back off on
429usingRetry-After. See Limits and rate limits. - Allowed addresses. An Owner can limit the organisation's keys to your servers' addresses in the hub; calls from anywhere else answer
403and code3042. MOOKHPay can also set a list for your platform routes, which answers403and code3013. See Allowed addresses. - Rotating the payout secret. A new secret signs at once and the old one keeps signing for 24 hours; deploy the new one to every server inside that window. See Security.
- Verification. Accounts you create work while
requirements.currently_dueincludesidentity, under a lower daily limit on money out (2948). Prompt illustrators to verify in MOOKHPay before their payouts grow.