> For the complete documentation index, see [llms.txt](https://docs.xtrakit.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.xtrakit.com/overview/payments/webhook.md).

# Webhook

This is the request we make to the callback URL you have sent on the merchant dashboard

XtraPay sends a webhook to your server the moment a payment or payout reaches a final state, so you can fulfil an order or update your records without polling.

Every webhook is a signed `POST` request with a JSON body. **Always verify the signature before you act on a webhook.** Anyone can send a request to your URL, and only the signature proves it came from XtraPay.

### Set up

1. In XtraPay, open **Settings → Developers**.
2. Under **API Keys & Webhooks**, set your **Callback URL**. You can also add more URLs on the **Webhooks** tab, each with its own list of events.
3. Set a **Callback Secret** and click **Save**. Use a long random string, such as 32 or more characters from a password generator.

<figure><img src="https://2825261350-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVsPq4N6DniO1ALophteI%2Fuploads%2FCbNZ2dBtZiDe7nBsvCYq%2FScreenshot%202026-10-29%20at%209.16.05%E2%80%AFPM.png?alt=media&amp;token=909754e3-eb65-45c0-b667-ad88af5340f7" alt=""><figcaption></figcaption></figure>

> **A Callback Secret is required.** XtraPay never sends an unsigned webhook. If no secret is set, the delivery is held and shows *"Not sent: no Callback Secret is set to sign webhooks"*. It goes out on the next retry once you save a secret.

Keep the secret on your server only. Never put it in a mobile app, browser code or a public repository. If it leaks, change it in **Settings → Developers**.

### Events

| Event               | Sent when                                                               |
| ------------------- | ----------------------------------------------------------------------- |
| `payment.completed` | A customer's payment succeeded and the money is in your wallet.         |
| `payment.failed`    | A payment was declined, cancelled or expired.                           |
| `payout.completed`  | A payout you made through the API reached the recipient.                |
| `payout.failed`     | A payout could not be completed. The amount is returned to your wallet. |

On the **Webhooks** tab you can limit a URL to certain events: a comma-separated list such as `payment.completed, payout.failed`, or a group such as `payment.*`. Leave it empty to receive every event.

### The request

```http
POST /your/webhook/url HTTP/1.1
Content-Type: application/json
User-Agent: XtraPay-Webhooks/1.0
X-XtraPay-Event: payment.completed
X-XtraPay-Delivery: 48211
X-XtraPay-Timestamp: 1793280000
X-XtraPay-Signature: t=1793280000,v1=5f8a0c3e9b1d4a7f2e6c8b0a9d3f1e7c5b2a4d6f8e0c1b3a5d7f9e2c4b6a8d0f
```

```json
{
  "id": "evt_3f9a1c2b7d4e8f0a6b5c1d2e",
  "event": "payment.completed",
  "created_at": "2026-10-29T14:05:12+00:00",
  "data": {
    "transaction_id": "PAY-33979516-334A3820",
    "merchant_transaction_id": "ORDER-77",
    "business_code": "33979516",
    "type": "payment",
    "source": "api",
    "status": "completed",
    "amount": "100.00",
    "fee": "2.00",
    "net_amount": "98.00",
    "currency": "GHS",
    "provider": "interpay",
    "provider_reference": "210341484",
    "transaction_date": "2026-10-29T14:04:40+00:00",
    "settled_at": "2026-10-29T14:05:11+00:00"
  }
}
```

#### Headers

| Header                | Description                                                                     |
| --------------------- | ------------------------------------------------------------------------------- |
| `X-XtraPay-Signature` | `t=<timestamp>,v1=<signature>`. See Verify the signature.                       |
| `X-XtraPay-Timestamp` | Unix time (seconds) the request was signed. Same value as `t` in the signature. |
| `X-XtraPay-Event`     | The event name, also in the body.                                               |
| `X-XtraPay-Delivery`  | ID of this delivery to this URL. Useful when you contact support.               |

#### Body

| Field                          | Type   | Description                                                                                   |
| ------------------------------ | ------ | --------------------------------------------------------------------------------------------- |
| `id`                           | string | Unique event ID. It stays the same on every retry and resend, so use it to ignore duplicates. |
| `event`                        | string | One of the events above.                                                                      |
| `created_at`                   | string | When the event was created (ISO 8601).                                                        |
| `data.transaction_id`          | string | XtraPay's reference for the transaction.                                                      |
| `data.merchant_transaction_id` | string | The `transaction_id` you sent when starting the payment. Present for API payments.            |
| `data.business_code`           | string | Your business code.                                                                           |
| `data.type`                    | string | `payment` or `payout`.                                                                        |
| `data.source`                  | string | Where the payment came from: `api`, `payment_link`, `virtual_terminal` (USSD) or `checkout`.  |
| `data.status`                  | string | `completed` or `failed`.                                                                      |
| `data.amount`                  | string | Transaction amount, two decimal places.                                                       |
| `data.fee`                     | string | XtraPay's fee.                                                                                |
| `data.net_amount`              | string | Payments: what you keep (`amount − fee`). Payouts: what left your wallet (`amount + fee`).    |
| `data.currency`                | string | ISO currency code, e.g. `GHS`.                                                                |
| `data.provider`                | string | The payment network that processed it.                                                        |
| `data.provider_reference`      | string | The network's own reference, when there is one.                                               |
| `data.reason`                  | string | Why it failed. Only present on `*.failed` events.                                             |
| `data.transaction_date`        | string | When the transaction started.                                                                 |
| `data.settled_at`              | string | When it reached its final state.                                                              |

Fields with no value are left out, so don't treat a missing field as an error.

### Verify the signature

The signature is an HMAC-SHA256 of the timestamp, a full stop and the **raw request body**, keyed with your Callback Secret:

```
signature = hex( HMAC_SHA256( key = callback_secret, message = t + "." + raw_body ) )
```

To verify a webhook:

1. Read the `X-XtraPay-Signature` header and split it on commas into `t=…` and `v1=…`.
2. Reject the request if `t` is more than **5 minutes** away from your server's current time. This stops an old, captured request being replayed.
3. Compute the HMAC above over the **exact bytes you received**. Do not parse and re-encode the JSON first, or the signature will not match.
4. Compare your result with `v1` using a **constant-time** comparison.
5. If anything fails, respond `401` and do nothing else.

#### Node.js (Express)

```js
const crypto = require('crypto');
const express = require('express');
const app = express();

// Keep the raw body: the signature is over the exact bytes sent.
app.post('/webhooks/xtrapay', express.raw({ type: 'application/json' }), (req, res) => {
  const header = req.get('X-XtraPay-Signature') || '';
  const parts = Object.fromEntries(header.split(',').map(p => p.split('=')));
  const t = Number(parts.t);

  if (!t || Math.abs(Date.now() / 1000 - t) > 300) return res.sendStatus(401);

  const expected = crypto
    .createHmac('sha256', process.env.XTRAPAY_CALLBACK_SECRET)
    .update(`${parts.t}.${req.body}`)
    .digest('hex');

  const valid = parts.v1 && expected.length === parts.v1.length &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
  if (!valid) return res.sendStatus(401);

  const event = JSON.parse(req.body);
  // Respond fast; do the real work in the background.
  res.sendStatus(200);
  handleEvent(event);
});
```

#### PHP

```php
$rawBody = file_get_contents('php://input');
$header  = $_SERVER['HTTP_X_XTRAPAY_SIGNATURE'] ?? '';
parse_str(str_replace(',', '&', $header), $parts);

$t = (int) ($parts['t'] ?? 0);
if (! $t || abs(time() - $t) > 300) {
    http_response_code(401);
    exit;
}

$expected = hash_hmac('sha256', $parts['t'] . '.' . $rawBody, getenv('XTRAPAY_CALLBACK_SECRET'));
if (! hash_equals($expected, (string) ($parts['v1'] ?? ''))) {
    http_response_code(401);
    exit;
}

$event = json_decode($rawBody, true);
http_response_code(200);
// handle $event['event'] and $event['data'] ...
```

In Laravel, use `$request->getContent()` for the raw body, and exclude the route from CSRF protection.

#### Python (Flask)

```python
import hashlib, hmac, os, time
from flask import Flask, request, abort

app = Flask(__name__)

@app.post("/webhooks/xtrapay")
def xtrapay_webhook():
    raw_body = request.get_data()  # exact bytes, before any JSON parsing
    parts = dict(p.split("=", 1) for p in request.headers.get("X-XtraPay-Signature", "").split(",") if "=" in p)

    t = int(parts.get("t", 0) or 0)
    if not t or abs(time.time() - t) > 300:
        abort(401)

    expected = hmac.new(
        os.environ["XTRAPAY_CALLBACK_SECRET"].encode(),
        parts["t"].encode() + b"." + raw_body,
        hashlib.sha256,
    ).hexdigest()
    if not hmac.compare_digest(expected, parts.get("v1", "")):
        abort(401)

    event = request.get_json()
    # handle event["event"] and event["data"] ...
    return "", 200
```

### Respond quickly

* Return any **2xx** status within **10 seconds** to confirm receipt. Anything else, a timeout or a failed connection counts as a failed attempt.
* Do slow work, such as sending emails or calling other services, after you respond.
* Redirects are not followed. Point the URL straight at your handler and use **HTTPS**.

### Retries and duplicates

If an attempt fails, XtraPay tries again after 10 seconds, 30 seconds, 1 minute, 5 minutes, 15 minutes, 30 minutes, 1 hour, 3 hours and 6 hours. That is **10 attempts over about 11 hours**, after which the delivery is marked as failed.

You can also send any webhook again at any time: open the transaction in XtraPay and click **Resend Webhook**. The **Webhook / Metadata** panel there shows every attempt and what your server answered.

Because of retries and resends, the same event can reach you more than once, and events may not arrive in order:

* Store the `id` of each event you process, and ignore one you have already handled.
* Act on `data.status`, not on the order webhooks arrive in. A `payment.completed` is final and is never followed by a `payment.failed` for the same payment.
* For extra certainty before you release goods, confirm the transaction with the Query Transaction Status endpoint.

### Test your endpoint

Use the **Resend Webhook** button on any transaction to send a real, signed webhook to your URL. Check the **Webhook / Metadata** panel for the status code and response your server returned.

### Changes from the previous version of this page

The earlier version of this page described a format that is no longer used. If you built against it, update your handler:

| Before                                                                                   | Now                                                                                                   |
| ---------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `signature` header with an HMAC of the body only                                         | `X-XtraPay-Signature: t=…,v1=…`, with an HMAC of `t.body`, checked against the timestamp              |
| `Authorization: Bearer API_KEY` header                                                   | Removed. Your API key is never sent to your webhook URL; the signature proves the request is genuine. |
| Signature only when a secret was set                                                     | Every webhook is signed. Without a Callback Secret, webhooks are not sent.                            |
| Flat body (`status`, `message`, `amount`, `transaction_id`, `currency`, `business_code`) | `id`, `event`, `created_at` and a `data` object (see Body)                                            |
