> For the complete documentation index, see [llms.txt](https://docs-sdk.crypto-chief.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-sdk.crypto-chief.com/processing/python/guides/webhooks.md). Agents can also search and read this documentation through its [MCP server](https://docs-sdk.crypto-chief.com/~gitbook/mcp).

# Webhooks

Verify and handle Crypto Chief webhooks in Python with typed event payloads.

Webhooks are signed with your API key using HMAC-SHA256.

| Header               | Value                                                                               |
| -------------------- | ----------------------------------------------------------------------------------- |
| `X-Webhook-Delivery` | Delivery id, 1–128 characters `[A-Za-z0-9_-]`; the same on every attempt and resend |
| `X-CC-Timestamp`     | Unix time of the attempt, seconds                                                   |
| `X-CC-Signature`     | `v1=` + 64 hex characters                                                           |

The string to sign is four lines joined with `\n`, with no line break after the last one:

```
CC-HMAC-SHA256-WEBHOOK-V1
<X-CC-Timestamp>
<X-Webhook-Delivery>
<lowercase hex SHA-256 of the body>
```

`X-CC-Signature` is `v1=` followed by the lowercase hex HMAC-SHA256 of that string under your API key.

`body` is the raw request body. The SDK checks, in order: the three headers, the timestamp window (300 seconds), the signature (constant-time, hex in any case).

A retry or resend carries the same `X-Webhook-Delivery` and a new `X-CC-Timestamp`. Deduplicate by the delivery id — see [Webhook deliveries](https://docs-sdk.crypto-chief.com/processing/python/guides/webhook-deliveries.md#keep-the-delivery-id).

## FastAPI

Read the raw bytes off the request, then verify and parse in one step. `parse_webhook_event` returns a typed event picked by the event-name prefix:

```python
from fastapi import FastAPI, Request, HTTPException
from cryptochief import (
    parse_webhook_event, WebhookVerificationError, PayInWebhookEvent, PayoutWebhookEvent,
)

app = FastAPI()
API_KEY = "..."

@app.post("/webhook")
async def webhook(request: Request):
    raw = await request.body()  # the EXACT bytes — do not re-encode
    try:
        evt = parse_webhook_event(API_KEY, raw, request.headers)
    except WebhookVerificationError:
        raise HTTPException(status_code=401, detail="webhook verification failed")

    if isinstance(evt, PayInWebhookEvent) and evt.status == "paid":
        ...  # invoice.paid — fulfill the order for evt.order_id
    elif isinstance(evt, PayoutWebhookEvent):
        ...  # payout.paid / payout.system_fail — reconcile your ledger
    return {"ok": True}
```

## Plain stdlib server

The verification helpers do no I/O, so a plain `http.server` works too. A handler that raises leaves the request unanswered, so catch both errors:

```python
from http.server import BaseHTTPRequestHandler
from cryptochief import parse_webhook_event, CryptoChiefError, WebhookVerificationError

class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        raw = self.rfile.read(int(self.headers.get("Content-Length", "0")))
        try:
            evt = parse_webhook_event(API_KEY, raw, self.headers)
        except WebhookVerificationError:
            self.send_response(401); self.end_headers(); return
        except CryptoChiefError:  # signed, but not a JSON object
            self.send_response(400); self.end_headers(); return
        print(evt.get("event") if isinstance(evt, dict) else evt.event)  # e.g. "payout.paid"
        self.send_response(200); self.end_headers()
```

## Manual verification

For any other stack, pass the raw body and the request headers. `verify_webhook` returns `None` and raises on failure:

```python
from cryptochief import verify_webhook, WebhookVerificationError

try:
    verify_webhook(API_KEY, raw_body, headers)
except WebhookVerificationError:
    ...  # reject with 401
```

`headers` is anything with `items()` — a `dict`, Starlette, Werkzeug, httpx or `http.server` headers — or an iterable of `(name, value)` pairs. Names match ignoring ASCII case, and one name under two spellings is a repeat.

Catch the subclass to tell the checks apart:

| Exception               | `reason`      | Cause                                                                    |
| ----------------------- | ------------- | ------------------------------------------------------------------------ |
| `WebhookHeadersError`   | `"headers"`   | A signature header is missing, repeated or malformed                     |
| `WebhookTimestampError` | `"timestamp"` | `X-CC-Timestamp` differs from the local clock by more than the tolerance |
| `WebhookSignatureError` | `"signature"` | The signature does not match the body                                    |

All three subclass `WebhookVerificationError`. An empty `API_KEY` raises `CryptoChiefError`. `tolerance` and `now` set the window and the time source, in `verify_webhook` and `parse_webhook_event` alike:

```python
verify_webhook(API_KEY, raw_body, headers, tolerance=60, now=1789430400)
```

`sign_webhook_v1(api_key, timestamp, delivery_id, body)` returns the `X-CC-Signature` value, for testing a receiver.

## Event types

Typed payloads: `PayoutWebhookEvent`, `TransactionWebhookEvent`, `PayInWebhookEvent`, `StaticDepositWebhookEvent`, `SweepWebhookEvent`. Event-name prefixes are `payout.*`, `transaction.*`, `invoice.*` (pay-ins), `static_deposit.*`, and `sweep.*`. `parse_webhook_event` returns the matching dataclass, or the raw `dict` for an unknown prefix. Payout and transaction webhooks fire **only on terminal status**.

`sweep.confirmed` is the moment swept funds reach the network's finality depth in your master wallet — the other half of a deposit's life, and what treasury reporting should key off. See [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/python/guides/sweep-callbacks.md).

Confirmation fields on events:

| Event type                | Field                                     | Meaning                                                                                                                                                                                 |
| ------------------------- | ----------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `PayoutWebhookEvent`      | `confirmations`                           | The lowest count among the sources; `None` while no source has a transaction. See [Send a payout](https://docs-sdk.crypto-chief.com/processing/python/guides/payouts.md#confirmations). |
| `PayoutWebhookEvent`      | `required_confirmations`                  | The network's finality depth, at least `1`; `None` when not sent.                                                                                                                       |
| `TransactionWebhookEvent` | `confirmations`, `required_confirmations` | Always sent. See [Sign & execute](https://docs-sdk.crypto-chief.com/processing/python/guides/sign-execute.md#confirm).                                                                  |
| `SweepWebhookEvent`       | `sweep_confirmations`                     | At least `required_confirmations`. See [Sweep callbacks](https://docs-sdk.crypto-chief.com/processing/python/guides/sweep-callbacks.md#payload).                                        |
| `SweepWebhookEvent`       | `required_confirmations`                  | The network's finality depth; `None` when not sent.                                                                                                                                     |

On a payout event, `sources` and `service_operations` are raw lists of dicts. Read each entry's count with `.get("confirmations")`; the key is absent until its transaction is on chain.

{% hint style="warning" %}
**"No value" is not spelled the same way in every payload.** A static-deposit webhook reports a native-coin transfer as `contract=""`, not `None` — the opposite of the wallet endpoints, where an unset value is always `null` — so test it with `if not evt.contract`. `confirmed_at` and `paid_at` stay `None` until the deposit is confirmed and paid, and `amount_fiat` can come through empty when no rate was available. A sweep webhook goes the other way again: an optional field it has no value for is **omitted**, so a native sweep's `asset_contract` reads `None`.
{% endhint %}

{% hint style="info" %}
`WEBHOOK_SENDER_IPS` lists the addresses webhooks are delivered from — whitelist them at your edge for defence in depth.
{% endhint %}
