# Receive webhooks

Subscribe an HTTPS endpoint to account events, verify the X-FB-Signature header, process deliveries idempotently and inspect or redeliver failed deliveries.

- Canonical: https://fineproxy.org/developers/docs/guides/webhooks/

Webhooks let FineProxy push events — a completed deposit, a provisioned or renewed service, a low wallet balance — to your server instead of you polling the API. This guide covers creating an endpoint, verifying signatures, handling deliveries safely and debugging them.

Webhook endpoints are managed with the REST API and an API key with the `webhooks` scope. There are no MCP tools for webhooks.

## Event types

`GET /api/v1/customer/webhooks/events` returns the events you can subscribe to:

```bash
curl https://fineproxy.org/account_new/api/v1/customer/webhooks/events \
  -H "Authorization: Bearer $FINEPROXY_API_KEY"
```

```json
{
  "events": [
    "deposit.completed",
    "payment.failed",
    "payment.succeeded",
    "service.expiring",
    "service.provisioned",
    "service.renewed",
    "service.suspended",
    "service.terminated",
    "wallet.balance_low"
  ]
}
```

| Group | Events |
| --- | --- |
| Deposits and payments | `deposit.completed`, `payment.succeeded`, `payment.failed` |
| Services | `service.provisioned`, `service.renewed`, `service.expiring`, `service.suspended`, `service.terminated` |
| Wallet | `wallet.balance_low` |

Your endpoint also receives `ping` events when you send a test (see below). Read the list from the API at startup rather than hardcoding it.

Reference: [List event types](/developers/docs/api/webhooks/#get-api-list-event-types).

## Create an endpoint

`POST /api/v1/customer/webhooks` with your HTTPS `url` (8–2048 characters), the `events` to receive (at least one) and an optional `description` (up to 255 characters).

```bash
curl -X POST https://fineproxy.org/account_new/api/v1/customer/webhooks \
  -H "Authorization: Bearer $FINEPROXY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/webhooks/fineproxy",
    "events": ["deposit.completed", "service.provisioned", "service.renewed", "wallet.balance_low"],
    "description": "production backend"
  }'
```

```javascript
const response = await fetch('https://fineproxy.org/account_new/api/v1/customer/webhooks', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.FINEPROXY_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    url: 'https://example.com/webhooks/fineproxy',
    events: ['deposit.completed', 'service.provisioned', 'service.renewed', 'wallet.balance_low'],
    description: 'production backend',
  }),
});
if (!response.ok) throw new Error(`Create failed ${response.status}: ${await response.text()}`);
const endpoint = await response.json();
// Store endpoint.secret in your secret manager now: it is never shown again.
console.log(endpoint.id, endpoint.secret_prefix);
```

```python
import os
import requests

response = requests.post(
    "https://fineproxy.org/account_new/api/v1/customer/webhooks",
    headers={"Authorization": f"Bearer {os.environ['FINEPROXY_API_KEY']}"},
    json={
        "url": "https://example.com/webhooks/fineproxy",
        "events": ["deposit.completed", "service.provisioned", "service.renewed", "wallet.balance_low"],
        "description": "production backend",
    },
    timeout=30,
)
response.raise_for_status()
endpoint = response.json()
# Store endpoint["secret"] in your secret manager now: it is never shown again.
print(endpoint["id"], endpoint["secret_prefix"])
```

The `201` response is the only place the signing secret appears:

```json
{
  "id": "00000000-0000-0000-0000-000000000000",
  "url": "https://example.com/webhooks/fineproxy",
  "secret": "whsec_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "secret_prefix": "whsec_xx",
  "events": ["deposit.completed", "service.provisioned", "service.renewed", "wallet.balance_low"],
  "description": "production backend",
  "is_active": true,
  "disabled_reason": null,
  "consecutive_failures": 0,
  "created_at": "2026-11-27T09:43:36.667254Z",
  "updated_at": null
}
```

> **Important:** `secret` starts with `whsec_` and is returned **once**. Later reads show only `secret_prefix`, which helps you tell endpoints apart. If you lose the secret, delete the endpoint and create a new one.

Reference: [Create webhook](/developers/docs/api/webhooks/#post-api-create-webhook).

## What a delivery looks like

Each event arrives as an HTTPS `POST` with a JSON body:

```text
POST /webhooks/fineproxy HTTP/1.1
Content-Type: application/json
X-FB-Event-Type: ping
X-FB-Event-Id: 00000000-0000-0000-0000-000000000000
X-FB-Timestamp: 1795772675
X-FB-Signature: v1=5d41402abc4b2a76b9719d911017c592ae0c4e1f2d3b4a5968778695a4b3c2d1
traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
```

The body of that `ping` delivery:

```json
{
  "id": "00000000-0000-0000-0000-000000000000",
  "type": "ping",
  "created_at": "2026-11-27T09:43:41Z",
  "data": { "ok": true, "endpoint_id": "00000000-0000-0000-0000-000000000000" }
}
```

| Header | Meaning |
| --- | --- |
| `X-FB-Event-Type` | Event type, the same as `type` in the body. |
| `X-FB-Event-Id` | Event ID, the same as `id` in the body. Use it to drop duplicates. |
| `X-FB-Timestamp` | Unix time in seconds. Part of the signed message. |
| `X-FB-Signature` | `v1=` followed by the hex HMAC-SHA256 signature. |
| `traceparent` | W3C trace context; quote it when you report a delivery problem. |

The body is always the envelope `{"id", "type", "created_at", "data"}`; the contents of `data` depend on the event type. The example shows the `ping` data.

## Verify the signature

Compute the signature yourself and compare it with the header before trusting a delivery:

1. Take the **raw** request body bytes, exactly as received — before any JSON parsing.
2. Build the message `"{X-FB-Timestamp}.{raw body}"`.
3. Compute HMAC-SHA256 with the **full** secret string as the key, including the `whsec_` prefix, and hex-encode it.
4. Compare it with the part of `X-FB-Signature` after `v1=` using a constant-time comparison.

We also recommend rejecting deliveries whose `X-FB-Timestamp` is far from your clock — for example more than 5 minutes — so a captured request cannot be replayed later. Log such rejections; you can fetch the event again with a redelivery.

Complete receivers, reading the secret from `FINEPROXY_WEBHOOK_SECRET`:

```javascript
// npm install express
import crypto from 'node:crypto';
import express from 'express';

const WEBHOOK_SECRET = process.env.FINEPROXY_WEBHOOK_SECRET; // the full "whsec_..." string
const TOLERANCE_SECONDS = 300;
const processedEventIds = new Set(); // use a database table with a unique key in production

function isValidSignature(rawBody, timestamp, signatureHeader) {
  if (!timestamp || !signatureHeader || !signatureHeader.startsWith('v1=')) return false;
  const expected = crypto
    .createHmac('sha256', WEBHOOK_SECRET)
    .update(`${timestamp}.`)
    .update(rawBody)
    .digest('hex');
  const received = signatureHeader.slice('v1='.length);
  const a = Buffer.from(expected, 'utf8');
  const b = Buffer.from(received, 'utf8');
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

async function handleEvent(event) {
  console.log('FineProxy event', event.type, event.id, event.data);
}

const app = express();

// express.raw keeps the body as a Buffer — do not use express.json() on this route.
app.post('/webhooks/fineproxy', express.raw({ type: 'application/json' }), (req, res) => {
  const timestamp = req.get('X-FB-Timestamp');
  if (!isValidSignature(req.body, timestamp, req.get('X-FB-Signature'))) {
    return res.status(400).send('invalid signature');
  }
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) {
    return res.status(400).send('timestamp outside tolerance');
  }

  const event = JSON.parse(req.body.toString('utf8'));
  if (processedEventIds.has(event.id)) return res.sendStatus(200); // duplicate: already handled
  processedEventIds.add(event.id);

  res.sendStatus(200); // acknowledge first, then do the slow work
  handleEvent(event).catch((err) => console.error('webhook handler failed', event.id, err));
});

app.listen(3000);
```

```python
# pip install flask
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

WEBHOOK_SECRET = os.environ["FINEPROXY_WEBHOOK_SECRET"].encode()  # the full "whsec_..." string
TOLERANCE_SECONDS = 300
processed_event_ids = set()  # use a database table with a unique key in production

app = Flask(__name__)


def is_valid_signature(raw_body: bytes, timestamp: str | None, signature_header: str | None) -> bool:
    if not timestamp or not signature_header or not signature_header.startswith("v1="):
        return False
    message = timestamp.encode() + b"." + raw_body
    expected = hmac.new(WEBHOOK_SECRET, message, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature_header[len("v1="):])


def handle_event(event: dict) -> None:
    print("FineProxy event", event["type"], event["id"], event["data"])


@app.post("/webhooks/fineproxy")
def fineproxy_webhook():
    raw_body = request.get_data()  # raw bytes, before any JSON parsing
    timestamp = request.headers.get("X-FB-Timestamp")
    if not is_valid_signature(raw_body, timestamp, request.headers.get("X-FB-Signature")):
        abort(400)
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        abort(400)

    event = json.loads(raw_body)
    if event["id"] in processed_event_ids:
        return "", 200  # duplicate: already handled
    processed_event_ids.add(event["id"])

    handle_event(event)  # keep this fast, or hand it to a job queue
    return "", 200


if __name__ == "__main__":
    app.run(port=3000)
```

With FastAPI, read the raw body with `await request.body()` and move the work to a background task so the response goes out immediately:

```python
# pip install fastapi uvicorn
import hashlib
import hmac
import json
import os
import time

from fastapi import BackgroundTasks, FastAPI, HTTPException, Request, Response

WEBHOOK_SECRET = os.environ["FINEPROXY_WEBHOOK_SECRET"].encode()
TOLERANCE_SECONDS = 300
processed_event_ids = set()

app = FastAPI()


def is_valid_signature(raw_body: bytes, timestamp: str | None, signature_header: str | None) -> bool:
    if not timestamp or not signature_header or not signature_header.startswith("v1="):
        return False
    expected = hmac.new(WEBHOOK_SECRET, timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature_header[len("v1="):])


def handle_event(event: dict) -> None:
    print("FineProxy event", event["type"], event["id"], event["data"])


@app.post("/webhooks/fineproxy")
async def fineproxy_webhook(request: Request, background_tasks: BackgroundTasks):
    raw_body = await request.body()
    timestamp = request.headers.get("x-fb-timestamp")
    if not is_valid_signature(raw_body, timestamp, request.headers.get("x-fb-signature")):
        raise HTTPException(status_code=400, detail="invalid signature")
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        raise HTTPException(status_code=400, detail="timestamp outside tolerance")

    event = json.loads(raw_body)
    if event["id"] not in processed_event_ids:
        processed_event_ids.add(event["id"])
        background_tasks.add_task(handle_event, event)
    return Response(status_code=200)
```

To debug a mismatch, compute the expected value by hand from a saved body:

```bash
printf '%s.%s' "$X_FB_TIMESTAMP" "$(cat body.json)" \
  | openssl dgst -sha256 -hmac "$FINEPROXY_WEBHOOK_SECRET" -hex
```

The most common causes of a mismatch are a body that was parsed and re-serialized before hashing, a secret without its `whsec_` prefix, and comparing against the header value with the `v1=` prefix still attached.

## Handle deliveries safely

- **Respond with 2xx quickly.** Return `200` as soon as the signature is valid and the event is stored, then do the real work asynchronously.
- **De-duplicate by event ID.** Store `X-FB-Event-Id` (body `id`) with a unique constraint and skip events you have already processed, so a repeated delivery of the same event does nothing.
- **Make handlers safe to run twice.** A manual redelivery can arrive with a different event ID than the original (see below), so base side effects on the current state of the resource, not only on the event ID.
- **Don't rely on order.** Use `created_at` and re-read the current state from the API (for example `GET /api/v1/customer/services/{service_id}`) before acting.
- **Treat webhooks as hints for money.** For deposits, confirm the credit in the ledger (`GET /api/v1/customer/wallet/ledger`) before releasing anything to your users. See [Wallet and payments](/developers/docs/guides/wallet/).

## Send a test event

`POST /api/v1/customer/webhooks/{endpoint_id}/test` queues a `ping` delivery to the endpoint:

```bash
curl -X POST "https://fineproxy.org/account_new/api/v1/customer/webhooks/$ENDPOINT_ID/test" \
  -H "Authorization: Bearer $FINEPROXY_API_KEY"
```

```json
{
  "id": "00000000-0000-0000-0000-000000000001",
  "event_id": "00000000-0000-0000-0000-000000000002",
  "endpoint_id": "00000000-0000-0000-0000-000000000000",
  "event_type": "ping",
  "status": "pending",
  "attempts": 0,
  "next_attempt_at": "2026-11-27T09:43:41.442178Z",
  "last_response_code": null,
  "last_response_body": null,
  "last_error": null,
  "created_at": "2026-11-27T09:43:41.431885Z",
  "updated_at": null
}
```

Delivery is asynchronous: in testing the `ping` reached the receiver about 20 seconds after this call, and the delivery then showed `status: "delivered"`, `attempts: 1`, `last_response_code: 200`.

Reference: [Send test](/developers/docs/api/webhooks/#post-api-send-test).

## Inspect deliveries and redeliver

`GET /api/v1/customer/webhooks/{endpoint_id}/deliveries` returns an array of recent deliveries; `limit` is 1–50 (default 50).

```bash
curl "https://fineproxy.org/account_new/api/v1/customer/webhooks/$ENDPOINT_ID/deliveries?limit=20" \
  -H "Authorization: Bearer $FINEPROXY_API_KEY"
```

| Field | Meaning |
| --- | --- |
| `id` | Delivery ID. |
| `event_id`, `event_type` | The event delivered. |
| `status` | `pending` while queued, `delivered` after your endpoint accepted it. |
| `attempts` | Delivery attempts so far. |
| `next_attempt_at` | When the next attempt is scheduled. |
| `last_response_code`, `last_response_body`, `last_error` | What your endpoint answered on the last attempt, or the connection error. |

To send a delivery again, call `POST /api/v1/customer/webhooks/deliveries/{delivery_id}/redeliver`. It returns `201` with a **new** delivery: a new `id`, and in testing also a new `event_id`. The original row is not reused.

```bash
curl -X POST "https://fineproxy.org/account_new/api/v1/customer/webhooks/deliveries/$DELIVERY_ID/redeliver" \
  -H "Authorization: Bearer $FINEPROXY_API_KEY"
```

Each endpoint also reports `consecutive_failures` and `disabled_reason` (`GET /api/v1/customer/webhooks/{endpoint_id}`). If events stop arriving, check `is_active`, those two fields and the latest deliveries.

References: [List deliveries](/developers/docs/api/webhooks/#get-api-list-deliveries), [Redeliver](/developers/docs/api/webhooks/#post-api-redeliver), [Get webhook](/developers/docs/api/webhooks/#get-api-get-webhook).

## Update, disable or delete an endpoint

`PATCH /api/v1/customer/webhooks/{endpoint_id}` changes any of `url`, `events`, `description` and `is_active`. Send only the fields you change:

```bash
curl -X PATCH "https://fineproxy.org/account_new/api/v1/customer/webhooks/$ENDPOINT_ID" \
  -H "Authorization: Bearer $FINEPROXY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"is_active": false}'
```

The response is the endpoint with an updated `updated_at`. Set `is_active` back to `true` to resume. `GET /api/v1/customer/webhooks` lists all your endpoints (without secrets).

`DELETE /api/v1/customer/webhooks/{endpoint_id}` removes the endpoint and returns `{"message": "ok"}`.

References: [List webhooks](/developers/docs/api/webhooks/#get-api-list-webhooks), [Update webhook](/developers/docs/api/webhooks/#patch-api-update-webhook), [Delete webhook](/developers/docs/api/webhooks/#delete-api-delete-webhook).

## Common pitfalls

- **Losing the secret.** It is shown only in the create response.
- **Verifying a parsed body.** Frameworks that parse JSON before your handler change the bytes; use the raw body.
- **Doing slow work before responding.** Acknowledge first, then process.
- **Polling too soon after a test.** The `ping` takes a few seconds to arrive and the delivery stays `pending` until then.
