Appearance
Confirming payments
Before you ship anything, read the payment with your own secret key and check that it is the one you expect. Do this on every order, whichever way the news reached you: a redirect, a webhook or a poll.
The redirect is not proof
After a completed hosted checkout, the payer lands on your return_url with query parameters:
text
https://shop.example.com/paid?checkout=cs_ke_4f1c9a0b7d2e6f3a8b5c1d09&reference=order-1042&status=completedAnybody can type that address. Take checkout from it, ignore status and reference, and read the checkout. A direct charge has no redirect at all: your own screen polls it.
What to check
| Check | Checkout field | Charge field |
|---|---|---|
| It is paid | status is completed | status is succeeded |
| It is your order | reference matches the order | reference matches the order |
| It is the right amount | amount (a string) equals the order total in minor units | amount (a number) equals the order total |
| It is the right currency | currency | currency |
| It is real | test is false | test is false |
| You have not fulfilled it already | Your own record of the checkout id | Your own record of the charge id |
A key reads only its own payments: an id another account made answers 404, the same as an unknown one (code 2783 for a checkout, 3001 for a charge). A 404 on an id from a redirect means it is not yours.
Confirm a checkout or a charge
These functions read the payment, run the checks above, and answer whether the order may be fulfilled.
sh
curl https://payments-ke-staging.mookhpay.co/v1/payments/merchant/checkouts/cs_ke_4f1c9a0b7d2e6f3a8b5c1d09 \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"
curl https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges/ch_ke_8a3f0c2d9b1e4f5a6c7d8e9f \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"js
const API = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
const headers = { Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}` };
export async function checkoutIsPaid(checkoutId, order) {
if (!/^cs_[a-z]{2}_[0-9a-f]{24}$/.test(checkoutId)) return false;
const res = await fetch(`${API}/checkouts/${checkoutId}`, { headers });
if (res.status === 404) return false;
const body = await res.json();
if (!body.ok) throw new Error(`${body.code}: ${body.description}`);
const c = body.data;
return (
c.status === "completed" &&
c.reference === order.reference &&
c.amount === String(order.amountMinor) &&
c.currency === order.currency &&
c.test === false
);
}
export async function chargeIsPaid(chargeId, order) {
const res = await fetch(`${API}/charges/${encodeURIComponent(chargeId)}`, { headers });
if (res.status === 404) return false;
const body = await res.json();
if (!body.ok) throw new Error(`${body.code}: ${body.description}`);
const c = body.data;
return (
c.status === "succeeded" &&
c.reference === order.reference &&
c.amount === order.amountMinor &&
c.currency === order.currency
);
}python
import os
import re
import requests
API = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant"
HEADERS = {"Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}"}
def checkout_is_paid(checkout_id, order):
if not re.fullmatch(r"cs_[a-z]{2}_[0-9a-f]{24}", checkout_id or ""):
return False
res = requests.get(f"{API}/checkouts/{checkout_id}", headers=HEADERS, timeout=15)
if res.status_code == 404:
return False
body = res.json()
if not body["ok"]:
raise RuntimeError(f"{body['code']}: {body['description']}")
c = body["data"]
return (
c["status"] == "completed"
and c["reference"] == order["reference"]
and c["amount"] == str(order["amount_minor"])
and c["currency"] == order["currency"]
and c["test"] is False
)
def charge_is_paid(charge_id, order):
res = requests.get(f"{API}/charges/{charge_id}", headers=HEADERS, timeout=15)
if res.status_code == 404:
return False
body = res.json()
if not body["ok"]:
raise RuntimeError(f"{body['code']}: {body['description']}")
c = body["data"]
return (
c["status"] == "succeeded"
and c["reference"] == order["reference"]
and c["amount"] == order["amount_minor"]
and c["currency"] == order["currency"]
)php
<?php
function mookhpayGet(string $path): array
{
$ch = curl_init("https://payments-ke-staging.mookhpay.co/v1/payments/merchant" . $path);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => ["Authorization: Bearer " . getenv("MOOKHPAY_SECRET_KEY")],
]);
$raw = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [$status, json_decode($raw, true)];
}
function checkoutIsPaid(string $checkoutId, array $order): bool
{
if (!preg_match('/^cs_[a-z]{2}_[0-9a-f]{24}$/', $checkoutId)) {
return false;
}
[$status, $body] = mookhpayGet("/checkouts/$checkoutId");
if ($status === 404) {
return false;
}
if (!$body["ok"]) {
throw new RuntimeException($body["code"] . ": " . $body["description"]);
}
$c = $body["data"];
return $c["status"] === "completed"
&& $c["reference"] === $order["reference"]
&& $c["amount"] === (string) $order["amount_minor"]
&& $c["currency"] === $order["currency"]
&& $c["test"] === false;
}
function chargeIsPaid(string $chargeId, array $order): bool
{
[$status, $body] = mookhpayGet("/charges/" . rawurlencode($chargeId));
if ($status === 404) {
return false;
}
if (!$body["ok"]) {
throw new RuntimeException($body["code"] . ": " . $body["description"]);
}
$c = $body["data"];
return $c["status"] === "succeeded"
&& $c["reference"] === $order["reference"]
&& $c["amount"] === $order["amount_minor"]
&& $c["currency"] === $order["currency"];
}The charge check leaves test out on purpose: every charge made with a staging key is a test charge, so a staging integration would never pass it. Add test === false to your production build, or compare test with the key you run on.
Fulfil each payment once
A redirect, a webhook and a poll can all tell you about the same payment, and webhooks are delivered at least once. Make fulfilment idempotent on the payment's id: record the checkout id or charge id in a table with a unique constraint, and fulfil only when your insert created the row.
sql
CREATE TABLE fulfilments (
payment_id text PRIMARY KEY,
order_id text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO fulfilments (payment_id, order_id)
VALUES ($1, $2)
ON CONFLICT (payment_id) DO NOTHING
RETURNING payment_id;sh
curl https://payments-ke-staging.mookhpay.co/v1/payments/merchant/checkouts/cs_ke_4f1c9a0b7d2e6f3a8b5c1d09 \
-H "Authorization: Bearer $MOOKHPAY_SECRET_KEY"js
import pg from "pg";
import { checkoutIsPaid } from "./confirm.js";
const db = new pg.Pool({ connectionString: process.env.DATABASE_URL });
export async function fulfilOnce(checkoutId, order, ship) {
if (!(await checkoutIsPaid(checkoutId, order))) return "not_paid";
const claimed = await db.query(
"INSERT INTO fulfilments (payment_id, order_id) VALUES ($1, $2) ON CONFLICT (payment_id) DO NOTHING RETURNING payment_id",
[checkoutId, order.id],
);
if (claimed.rowCount === 0) return "already_fulfilled";
await ship(order);
return "fulfilled";
}python
import psycopg
from confirm import checkout_is_paid
def fulfil_once(conn: psycopg.Connection, checkout_id, order, ship):
if not checkout_is_paid(checkout_id, order):
return "not_paid"
with conn.transaction():
row = conn.execute(
"INSERT INTO fulfilments (payment_id, order_id) VALUES (%s, %s) "
"ON CONFLICT (payment_id) DO NOTHING RETURNING payment_id",
(checkout_id, order["id"]),
).fetchone()
if row is None:
return "already_fulfilled"
ship(order)
return "fulfilled"php
<?php
require __DIR__ . "/confirm.php";
function fulfilOnce(PDO $db, string $checkoutId, array $order, callable $ship): string
{
if (!checkoutIsPaid($checkoutId, $order)) {
return "not_paid";
}
$stmt = $db->prepare(
"INSERT INTO fulfilments (payment_id, order_id) VALUES (?, ?) "
. "ON CONFLICT (payment_id) DO NOTHING RETURNING payment_id"
);
$stmt->execute([$checkoutId, $order["id"]]);
if ($stmt->fetch() === false) {
return "already_fulfilled";
}
$ship($order);
return "fulfilled";
}The Node sample uses the pg package and the Python sample psycopg; any database with a unique constraint works the same way. For a charge, pass the charge id and use chargeIsPaid.
Use webhooks, and poll for late payments
MOOKHPay sends payment.succeeded when a payment is booked and payment.failed when an attempt fails, to every webhook endpoint you subscribed. Treat the webhook as the signal and the read as the check:
- Verify the signature. It proves MOOKHPay sent the event.
- Read the checkout or charge it names (
checkout_id, orchargeon a direct charge) with your key, and run the checks above. A signature says who sent the event; the read says the order is paid in full now. - Fulfil once, keyed on the id.
- Answer
2xxwithin 8 seconds. Do slow work after you answer.
Poll the payments you are still waiting on, in case a webhook is late or your endpoint was down:
- Poll a hosted checkout every 10 to 30 seconds while it can still complete. Reads share 120 requests a minute with your creates.
- Poll a direct charge every 2 seconds while the payer is on your screen, and stop at
expires_at. - A checkout still
openafterexpires_athas an attempt in flight. Keep reading it. - On Kenya, an exact Pay Bill payment can complete a checkout after
expires_at, and a charge can move tosucceededup to 7 days after it ended. If a customer says they paid from the menu, read the payment again. - A payment can arrive after you gave up. Keep your webhook endpoint subscribed to
payment.succeededfor orders you have marked unpaid.
Receipts and references
Store these with the order once it is paid. They are what you need to match the payment to a statement or answer a customer.
| Value | Where | What it is |
|---|---|---|
Checkout id or charge id | Every read and every webhook | MOOKHPay's id for the payment |
reference | Every read and every webhook | Your own order id, as you sent it |
payment.provider_receipt | Checkout read | The M-Pesa or MoMo receipt the payer's SMS carries, the CyberSource transaction id for a card, or MOOKHPay's own reference for a balance payment |
payment.reference | Checkout read | MOOKHPay's receipt reference (SM…), once booked |
receipt_number | Charge read | The M-Pesa or MoMo receipt, once succeeded. null for a card charge, where the rail gives the payer no receipt code |
provider_receipt, ledger_reference | payment.succeeded webhook | The same two values as payment.provider_receipt and payment.reference |
intent_id | Checkout read (payment.intent_id) and webhooks | The attempt that paid. A checkout can fail on one attempt and be paid on the next |
A test payment's receipt starts with TEST.
Show the payer the mobile-money receipt where there is one: it is the code on their own SMS.