> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloudpay.africa/llms.txt
> Use this file to discover all available pages before exploring further.

# Webhooks

> Get told the moment a payment finishes, instead of polling.

Set one HTTPS endpoint on your server. When a collection or payout reaches a final status, Cloudpay POSTs a signed JSON event to it, retries until you answer `2xx`, and keeps every attempt so you can see what happened.

## 1. Add your endpoint

In the dashboard: **Settings → Webhooks → Add endpoint**. Enter a public `https://` URL. You get a **signing secret** (`whsec_…`) once: store it next to your API key.

> [!NOTE]
>
> Only the business owner can add, change or remove the endpoint (it decides where payment data goes). API keys can't. Anyone with `read` can see deliveries.

## 2. Handle events

Every request is a `POST` with a JSON body:

```json theme={null}
{
  "id": "44f135be-ab6c-4a7c-9562-b3b69c862815",
  "type": "collection.completed",
  "created_at": "2026-11-17T06:45:49Z",
  "data": {
    "object": "collection",
    "id": "c9675a6e-e06e-4207-a9a9-fb7cf898a601",
    "merchant_id": "8b26766a-9f1c-4099-80cd-8a13d137711b",
    "status": "completed",
    "amount": 1000,
    "fee": 10,
    "msisdn": "254712345678",
    "reference": "order-1042",
    "receipt": "PSK6771849913",
    "failure_reason": null,
    "environment": "test"
  }
}
```

| `type` | When |
| - | - |
| `collection.completed` / `.failed` / `.review` | A collection reached that status |
| `disbursement.completed` / `.failed` / `.review` | A payout reached that status |
| `ping` | You pressed **Send test event** |

`data.environment` is `test` (Development) or `live`. Amounts are in cents.

Headers: `CloudPay-Event-Id` (same as `id`), `CloudPay-Event-Type`, and `CloudPay-Signature`.

## 3. Verify the signature

`CloudPay-Signature: t=1763362000,v1=5c0a…` is HMAC-SHA256 of `<t>.<raw body>` with your secret, in hex. Check it against the **raw** body before parsing, and reject old timestamps.

```js Node.js (Express) theme={null}
import crypto from "node:crypto";
import express from "express";

const app = express();
const SECRET = process.env.CLOUDPAY_WEBHOOK_SECRET;

app.post("/cloudpay/webhook", express.raw({ type: "application/json" }), (req, res) => {
  const header = req.get("CloudPay-Signature") ?? "";
  const { t, v1 } = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const expected = crypto.createHmac("sha256", SECRET).update(`${t}.${req.body}`).digest("hex");
  const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300;
  if (!v1 || !fresh || v1.length !== expected.length || !crypto.timingSafeEqual(Buffer.from(v1), Buffer.from(expected))) {
    return res.sendStatus(400);
  }
  const event = JSON.parse(req.body);
  res.sendStatus(200); // answer fast; do the work after
  queue.add(event);    // dedupe on event.id
});
```

```python Python (Flask) theme={null}
import hashlib, hmac, json, os, time
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = os.environ["CLOUDPAY_WEBHOOK_SECRET"].encode()

@app.post("/cloudpay/webhook")
def cloudpay_webhook():
    parts = dict(p.split("=", 1) for p in request.headers.get("CloudPay-Signature", "").split(","))
    raw = request.get_data()
    expected = hmac.new(SECRET, f'{parts.get("t")}.'.encode() + raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(parts.get("v1", ""), expected) or abs(time.time() - int(parts.get("t", 0))) > 300:
        abort(400)
    event = json.loads(raw)
    enqueue(event)  # dedupe on event["id"]
    return "", 200
```

## 4. Answer quickly, process once

* Reply `2xx` within **10 seconds**. Do slow work (fulfilment, emails) after replying.
* Events can arrive more than once and out of order. Store `id` and skip ones you've seen.
* Treat the event as a nudge: if you need certainty, `GET /v1/merchants/{id}/collections/{collectionID}` and act on what that says.

## Retries and the trail

Anything other than `2xx` (or no answer) is retried after 1 min, 5 min, 30 min, 2 h, 5 h, then every 10 h: 8 attempts, about 38 hours. After that the event is `failed`.

**Settings → Webhooks → Deliveries** lists every event. Open one to see each attempt: your server's status code, the first 1 KB of its answer, how long it took, and the exact payload. **Send again** re-sends a delivered or failed event. The same is in the API:

```bash theme={null}
curl $CLOUDPAY_API/v1/merchants/$MERCHANT_ID/webhook/deliveries -H "Authorization: Bearer $CLOUDPAY_KEY"
curl $CLOUDPAY_API/v1/merchants/$MERCHANT_ID/webhook/deliveries/$EVENT_ID -H "Authorization: Bearer $CLOUDPAY_KEY"
```

## Cloudpay's own IPN addresses

Providers notify Cloudpay too. **Settings → Webhooks → Cloudpay IPN addresses** (or `GET /v1/merchants/{id}/ipn-urls`) lists them with copy buttons:

* **Paste**: Paystack has one webhook URL per account. If you use your own Paystack keys, paste Cloudpay's Paystack address there. See [Paystack](https://docs.cloudpay.africa/guides/paystack.md).
* **Automatic**: Daraja and SasaPay get their callback address with every request. Nothing to set.

## Security

* Endpoints must be public `https://` addresses. Addresses that resolve to private or local networks are refused.
* Rotate the secret from the dashboard if it leaks. The old one stops working at once.
* Don't trust an event that fails the signature check, even if it looks right.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.