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

# Webhooks Overview

> Receive real-time notifications for payments, subscriptions, wallet operations, settlements, disputes, and order fulfillment.

# Webhooks

## Intro

Khaime sends an HTTP POST request to your webhook URL whenever a notable event happens on your account — a payment succeeds, a subscription renews, a payout settles, a dispute opens. Webhooks are the most reliable way to track transaction state; don't rely solely on redirect callbacks, since a customer can close their browser before the redirect fires.

## Context

Webhooks are configured per **Partner API key** (sandbox or live), so sandbox activity notifies your sandbox webhook URL and live activity notifies your live one. You set the URL and read the signing secret from the same place you manage API keys.

This page is the entry point for the webhooks documentation. Once you understand the envelope and delivery model here, go to:

* [Events](https://docs.khaime.com/webhooks/events.md) — the full catalog of event types and payload shapes
* [Signature Verification](https://docs.khaime.com/webhooks/verification.md) — how to confirm a request really came from Khaime
* [API Versioning](https://docs.khaime.com/webhooks/versioning.md) — how payload schemas change over time
* [Best Practices](https://docs.khaime.com/webhooks/best-practices.md) — patterns for reliable handling

## Hows

### Setup

1. Go to **Khaime Dashboard → Settings → API**
2. Set your **Webhook URL** (e.g., `https://yoursite.com/webhooks/khaime`)
3. Copy your **Webhook Secret** (`whsec_...`)

Or set the webhook URL programmatically:

```bash theme={null}
curl -X PUT https://api.khaime.com/api/v1/api-keys/YOUR_KEY_ID/webhook \
  -H "x-id-key: YOUR_AUTH_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"webhook_url": "https://yoursite.com/webhooks/khaime"}'
```

### Envelope structure

Every webhook delivery shares the same outer envelope regardless of event type:

```json theme={null}
{
  "api_version": "2026-03-28",
  "event_id": "evt_a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "event_type": "payment.succeeded",
  "occurred_at": "2026-03-27T14:32:00Z",
  "is_live": true,
  "business_id": "1042",
  "data": { ... }
}
```

| Field | Type | Description |
| - | - | - |
| `api_version` | string | Date-versioned schema pinned to your API key (e.g., `"2026-03-28"`) |
| `event_id` | string | Globally unique ID (`evt_{uuid4}`) — use for idempotency |
| `event_type` | string | Dot-notation event name (e.g., `payment.succeeded`) |
| `occurred_at` | string | ISO 8601 UTC timestamp |
| `is_live` | boolean | `false` for sandbox/test events |
| `business_id` | string | Merchant's platform ID |
| `data` | object | Event-specific payload (see [Events](https://docs.khaime.com/webhooks/events.md)) |

> [!NOTE]
>
> The `event_id` is the idempotency key. You **must** store processed `event_id` values and skip duplicates — retries reuse the same `event_id`.

### Webhook headers

Every webhook request includes these headers:

| Header | Description |
| - | - |
| `X-Khaime-Event` | Event type (e.g., `payment.succeeded`) |
| `X-Khaime-Event-Id` | Unique event ID (matches `event_id` in the body) |
| `X-Khaime-Signature` | HMAC-SHA256 signature for verification |
| `X-Khaime-Api-Version` | API version for this delivery (e.g., `2026-03-28`) |
| `Content-Type` | `application/json` |

### Delivery

| Property | Value |
| - | - |
| Timeout | 10 seconds |
| Attempts | Up to 3 total (1 initial + 2 retries) |
| Retry delay | 2 seconds, fixed, between attempts |
| Success | Any HTTP 2xx response |

> [!WARNING]
>
> Respond to webhooks within **5 seconds** with a `200` status. Process the event asynchronously after acknowledging receipt — a slow handler that blocks on downstream work risks hitting the 10-second timeout and triggering a retry (and a duplicate delivery) for an event you actually already received.

### Shared data types

These types appear across multiple event payloads.

#### MoneyAmount

All monetary values are in the **smallest currency unit** (cents for USD, kobo for NGN). Never floats.

```json theme={null}
{
  "amount": 5000,
  "currency": "USD"
}
```

#### MulticurrencyBreakdown

Present on payment and order events. Provides a full breakdown of amounts, fees, and currency conversion.

```json theme={null}
{
  "customer_paid": { "amount": 5000000, "currency": "NGN" },
  "merchant_gross": { "amount": 306, "currency": "USD" },
  "merchant_net": { "amount": 270, "currency": "USD" },
  "fees": {
    "platform_fee": { "amount": 18, "currency": "USD" },
    "gateway_fee": { "amount": 18, "currency": "USD" },
    "total": { "amount": 36, "currency": "USD" }
  },
  "conversion": {
    "from_currency": "NGN",
    "to_currency": "USD",
    "rate": 1630.5,
    "surcharge_percent": 1.0
  }
}
```

If the customer and merchant currencies are the same, `conversion` is omitted and `customer_paid` equals `merchant_gross`.

#### Customer

```json theme={null}
{
  "email": "jane@example.com",
  "first_name": "Jane",
  "last_name": "Doe",
  "id": "cust_123"
}
```

The `id` field is present only if the customer has a platform account.

### Example handler

```javascript Express.js theme={null}
app.post('/webhooks/khaime', express.raw({ type: 'application/json' }), (req, res) => {
  const signature = req.headers['x-khaime-signature'];
  const rawBody = req.body.toString();
  const payload = JSON.parse(rawBody);

  // 1. Verify signature (use raw body, not re-serialized)
  const expected = crypto
    .createHmac('sha256', process.env.KHAIME_WEBHOOK_SECRET)
    .update(rawBody)
    .digest('hex');

  if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
    return res.status(401).send('Invalid signature');
  }

  // 2. Check for duplicate using event_id
  if (await isDuplicate(payload.event_id)) {
    return res.status(200).send('Already processed');
  }

  // 3. Acknowledge immediately
  res.status(200).send('OK');

  // 4. Process asynchronously
  processEvent(payload);
});
```

```python Flask theme={null}
@app.route('/webhooks/khaime', methods=['POST'])
def handle_webhook():
    signature = request.headers.get('X-Khaime-Signature')
    raw_body = request.get_data(as_text=True)
    payload = json.loads(raw_body)

    # Verify using raw body
    expected = hmac.new(
        WEBHOOK_SECRET.encode(),
        raw_body.encode(),
        hashlib.sha256
    ).hexdigest()

    if not hmac.compare_digest(signature, expected):
        abort(401)

    # Process
    handle_event(payload)
    return '', 200
```

```php WordPress theme={null}
add_action('rest_api_init', function() {
    register_rest_route('khaime/v1', '/webhook', [
        'methods' => 'POST',
        'callback' => 'handle_khaime_webhook',
    ]);
});

function handle_khaime_webhook($request) {
    $signature = $request->get_header('X-Khaime-Signature');
    $raw_body = $request->get_body();
    $payload = json_decode($raw_body, true);

    $expected = hash_hmac('sha256', $raw_body, WEBHOOK_SECRET);

    if (!hash_equals($expected, $signature)) {
        return new WP_Error('invalid_signature', '', ['status' => 401]);
    }

    // Process event...
    return new WP_REST_Response(['status' => 'ok'], 200);
}
```

## Whys

Webhooks exist because payment, subscription, and settlement state changes asynchronously and often outside the request/response cycle your customer is in — a bank transfer settles hours later, a dispute is opened by a card network days later, a subscription renews on a schedule with no customer present at all. A redirect callback only covers the moment right after checkout; it can't tell you about anything that happens afterward.

The envelope carries a stable `event_id` specifically so retries are safe to replay: delivery is **at-least-once**, not exactly-once, so your handler has to be idempotent rather than relying on the network to deliver each event exactly one time. Signing over the **raw request body** (rather than a parsed-and-reserialized one) means the check only depends on bytes you actually received, with no dependency on your JSON library preserving key order or whitespace.

## Why nots

Webhooks are not a substitute for reconciliation. Delivery to your endpoint can fail — DNS issues, deploys, firewall rules — and after 3 attempts Khaime stops retrying. For payments created through the Charge API, treat the webhook as the primary signal but don't assume silence means nothing happened; if you must be certain, check the record directly (see [Best Practices](https://docs.khaime.com/webhooks/best-practices.md#4-handle-missing-events)).

Khaime does not guarantee webhook delivery order across event types — a `payment.succeeded` and its companion `wallet.credited` are fired independently, so design handlers that don't assume strict ordering between related events. Webhooks also don't carry a response contract beyond the HTTP status code: whatever your endpoint returns in the body is logged for debugging but never parsed or acted on.


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