Skip to content

Idempotency ​

A create that times out leaves you not knowing whether it happened. Send an Idempotency-Key header with every create, and retry with the same key: MOOKHPay answers with what the first request made instead of making a second one.

Idempotency-Key: order-1042

The key is 1 to 128 characters. A create that needs one and has none answers 400 and code 1701.

Which routes take a key ​

RouteKeySame key, same bodySame key, different body
POST /checkoutsRequired200, the first checkout as it is now422, code 3015. A checkout made before this changed still answers 200; see below
POST /chargesRequired200, the first charge as it is now422, code 3015
POST /accountsRequired200, the same account422, code 3015
POST /account-linksRequired200, the same link, with url null422, code 3015
POST /accounts/:id/org-requestsRequired200, the same request422, code 3015
POST /accounts/:id/payoutsRequired200, the same payout, or the same refusal if it was refused after being recorded422, code 3015
POST /refundsRequired200, the same refund as it is now422, code 3015
POST /accounts/:id/login-linksNot takenEvery call makes a new link
POST /charges/:id/cancelNot takenCancelling a cancelled charge answers it again
Document upload and submit on a business account requestNot taken
Every GETNot taken

The first request answers 201 (202 for a payout). A replay answers 200, so a 200 on a create tells you the work had already been done.

What counts as the same body ​

RouteCompared
POST /checkoutsThe whole body
POST /chargesThe whole body
POST /refundsThe whole body
POST /accountsThe whole body
POST /account-linksphone and the set of scopes. Their order does not matter
POST /accounts/:id/org-requestsThe account in the path and the whole body, including terms.accepted_at
POST /accounts/:id/payoutsThe account in the path, amount and remarks

Bodies are compared after parsing, with object keys sorted, so key order and whitespace in the JSON do not matter. Any changed value does, and so does the order of items in an array (other than scopes on an account link).

Checkouts compare the body ​

Changed in November 2026

POST /checkouts with a key it has seen now compares the new body with the first one. The same body answers the first checkout with 200, as before. A different body answers 422 and code 3015, where it used to answer 200 with the first checkout. If your code reused a key for a changed order and relied on getting the first checkout back, it now gets 3015: use a new key for the changed order.

A checkout made before the change has no stored body to compare. Its key still answers the first checkout with 200, whatever the new body says, so a retry of an order started before the change keeps working. See the changelog.

The replay is the checkout as it stands now, the same as a GET. It can already be completed.

Some checks run on the new body before the key is looked up, and refuse it instead of replaying: the field schema, the line_items sum and the return_url rules, the on_behalf_of and fee rules, the rail's amount limits, and, for a checkout paying your own account, the wallet check. A platform's key is looked up across all of its accounts, and on_behalf_of is part of the body: the same key with a different on_behalf_of answers 422 and code 3015.

Replays of each route ​

  • A charge comes back with its status now. A replay of a pending card charge answers a new client_secret, and the earlier one stops working.
  • A payout refused after it was recorded replays its refusal: the same HTTP status, code and data. Those are 2732, 2726, 2751, 2948 and a company approval that could not be filed. Refusals made before it is recorded (a field error, 3025, 3016, 2949, 3040, 2701, 2702, 2731, 2947) are worked out again on each attempt, so the same key can succeed later, for example a 2947 retried the next day. Each attempt still needs a fresh signature, because the timestamp must be within 300 seconds.
  • An account create that was refused (a phone that already has an account, a taken username, an unavailable service) frees its key. You can send a corrected request with the same key.
  • A business account request whose first call was refused also frees its key.

Two identical requests that arrive at the same moment still make one object. The second answers as a replay.

Scope ​

A key belongs to the account that owns the API key. The same string sent by two accounts is two keys.

A platform's keys are its own. A checkout or charge your platform makes for a seller never matches a key the seller used for their own checkout. MOOKHPay stores a platform's checkout key under its own prefix, so the same string used once for your own checkout and once with on_behalf_of makes two separate checkouts.

Checkout, charge and refund keys are separate: order-1042 on POST /checkouts, on POST /charges and on POST /refunds are three keys.

MOOKHPay does not expire keys today. Do not rely on that: treat a key as good for retries of one request, not as a lookup you can use months later.

Pick a key ​

  • Use an id you already store for the thing you are creating: order-1042, or payout-<your payout row id>.
  • Or make a UUID when you create the order, and store it with the order before you call MOOKHPay.
  • Do not make a new value for each attempt. Each retry would create a new payment.
  • Do not use a customer id. Many orders share it.

Retry safely ​

Retry on a network error, a timeout, 500, 502 or 503, with the same key and the same body, and wait longer between attempts. Do not retry other 4xx answers unchanged: they fail again. On 429, wait the Retry-After seconds.

sh
# Store the key with the order first, then send it on every attempt.
KEY="order-1042"

for attempt in 1 2 3 4 5; do
  status=$(curl -s -o response.json -w "%{http_code}" \
    -X POST https://payments-ke-staging.mookhpay.co/v1/payments/merchant/charges \
    -H "Authorization: Bearer $MOOKHPAY_SECRET_KEY" \
    -H "Idempotency-Key: $KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "amount": 150000,
      "reference": "order-1042",
      "payment_method": { "type": "mobile_money", "phone": "+254700000000" }
    }')
  case "$status" in
    200|201) cat response.json; break ;;
    000|429|500|502|503) sleep $((2 ** attempt)) ;;
    *) cat response.json; break ;;
  esac
done
js
const BASE = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant";
const RETRYABLE = new Set([429, 500, 502, 503]);

export async function createCharge(order) {
  // order.idempotencyKey was saved with the order before this call.
  const body = JSON.stringify({
    amount: order.amount,
    reference: order.id,
    payment_method: { type: "mobile_money", phone: order.phone },
  });

  for (let attempt = 1; attempt <= 5; attempt++) {
    let res;
    try {
      res = await fetch(`${BASE}/charges`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.MOOKHPAY_SECRET_KEY}`,
          "Idempotency-Key": order.idempotencyKey,
          "Content-Type": "application/json",
        },
        body,
        signal: AbortSignal.timeout(15_000),
      });
    } catch {
      await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
      continue;
    }
    const answer = await res.json();
    if (res.ok) return answer.data;
    if (!RETRYABLE.has(res.status)) {
      throw new Error(`${res.status} ${answer.code}: ${answer.description}`);
    }
    const wait = Number(res.headers.get("retry-after")) || 2 ** attempt;
    await new Promise((r) => setTimeout(r, wait * 1000));
  }
  throw new Error("MOOKHPay did not answer after 5 attempts");
}
python
import os
import time

import requests

BASE = "https://payments-ke-staging.mookhpay.co/v1/payments/merchant"
RETRYABLE = {429, 500, 502, 503}


def create_charge(order):
    # order["idempotency_key"] was saved with the order before this call.
    body = {
        "amount": order["amount"],
        "reference": order["id"],
        "payment_method": {"type": "mobile_money", "phone": order["phone"]},
    }
    for attempt in range(1, 6):
        try:
            res = requests.post(
                f"{BASE}/charges",
                json=body,
                headers={
                    "Authorization": f"Bearer {os.environ['MOOKHPAY_SECRET_KEY']}",
                    "Idempotency-Key": order["idempotency_key"],
                },
                timeout=15,
            )
        except requests.RequestException:
            time.sleep(2 ** attempt)
            continue
        answer = res.json()
        if res.ok:
            return answer["data"]
        if res.status_code not in RETRYABLE:
            raise RuntimeError(f"{res.status_code} {answer['code']}: {answer['description']}")
        time.sleep(int(res.headers.get("Retry-After", 2 ** attempt)))
    raise RuntimeError("MOOKHPay did not answer after 5 attempts")
php
<?php
const BASE = 'https://payments-ke-staging.mookhpay.co/v1/payments/merchant';

function createCharge(array $order): array
{
    // $order['idempotency_key'] was saved with the order before this call.
    $body = json_encode([
        'amount' => $order['amount'],
        'reference' => $order['id'],
        'payment_method' => ['type' => 'mobile_money', 'phone' => $order['phone']],
    ]);

    for ($attempt = 1; $attempt <= 5; $attempt++) {
        $ch = curl_init(BASE . '/charges');
        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 15,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . getenv('MOOKHPAY_SECRET_KEY'),
                'Idempotency-Key: ' . $order['idempotency_key'],
                'Content-Type: application/json',
            ],
        ]);
        $raw = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($raw === false) {
            sleep(2 ** $attempt);
            continue;
        }
        $answer = json_decode($raw, true);
        if ($status === 200 || $status === 201) {
            return $answer['data'];
        }
        if (!in_array($status, [429, 500, 502, 503], true)) {
            throw new RuntimeException("$status {$answer['code']}: {$answer['description']}");
        }
        sleep(2 ** $attempt);
    }
    throw new RuntimeException('MOOKHPay did not answer after 5 attempts');
}

A charge has one more guard: one pending charge per reference. A second create for a reference whose charge is still pending answers 409, code 3002, with the pending charge's id in data.charge, even with a new key.

The payer's own keys ​

The hosted page and the card element send their own keys to the public routes. A second tap while a prompt is in flight answers the attempt already running; it does not send a second prompt. You do not set these keys.

Staging documentation. A checkout made with a secret key on staging charges a real phone. See Environments.