Source: https://docs.debitura.com/developer-concepts/webhooks

# Webhooks

Debitura pushes real-time event notifications to your application via webhooks.

<a id="signature-verification"></a>

## Signature Verification

Every webhook request includes an `X-Debitura-Signature` header for verification:

```text
X-Debitura-Signature: t={timestamp},v1={signature}
```

| Component | Description |
| --- | --- |
| `t` | Unix timestamp (seconds) when signed |
| `v1` | HMAC-SHA256 signature in lowercase hex |

Signature encoding

The `v1` value is a **lowercase hexadecimal** string — do NOT base64-decode it before comparing. Only the webhook secret itself is base64-encoded; the signature is always raw hex.

<a id="how-to-verify"></a>

### How to Verify

1.  **Extract timestamp and signature** from the header
2.  **Construct signed payload**: `{timestamp}.{raw_json_body}`
3.  **Decode secret**: Base64 decode your webhook secret
4.  **Compute HMAC-SHA256**: `HMAC-SHA256(secret_bytes, signed_payload)`
5.  **Compare signatures**: Use constant-time comparison
6.  **Validate timestamp**: Reject timestamps older than 300 seconds or more than 30 seconds in the future

Critical

Use the RAW request body, not parsed/re-serialized JSON. Re-serialization may change whitespace or key ordering, breaking verification.

<a id="implementation-examples"></a>

### Implementation Examples

```javascript
const crypto = require('crypto');

function verifyWebhookSignature(rawBody, signatureHeader, webhookSecret) {
    const parts = signatureHeader.split(',');
    let timestamp, signature;

    for (const part of parts) {
        const [key, value] = part.split('=');
        if (key === 't') timestamp = parseInt(value, 10);
        else if (key === 'v1') signature = value;
    }

    if (!timestamp || !signature) return false;

    const age = Math.floor(Date.now() / 1000) - timestamp;
    if (age > 300 || age < -30) return false;

    const signedPayload = `${timestamp}.${rawBody}`;
    const secretBytes = Buffer.from(webhookSecret, 'base64');
    const expected = crypto
        .createHmac('sha256', secretBytes)
        .update(signedPayload, 'utf8')
        .digest('hex');

    try {
        return crypto.timingSafeEqual(
            Buffer.from(signature, 'hex'),
            Buffer.from(expected, 'hex')
        );
    } catch {
        return false;
    }
}
```

<a id="common-mistakes"></a>

## Common Mistakes

**Not decoding Base64 secret**

```javascript
// Wrong: using Base64 string directly
crypto.createHmac('sha256', webhookSecret);

// Correct: decode first
crypto.createHmac('sha256', Buffer.from(webhookSecret, 'base64'));
```

**Using parsed JSON body**

```javascript
// Wrong: re-serialized (formatting may differ)
const body = JSON.stringify(req.body);

// Correct: raw request body
app.use(express.raw({ type: 'application/json' }));
const rawBody = req.body.toString('utf8');
```

**Middleware ordering (Express.js)** — `express.raw()` must run before any JSON body parser for the webhook route. If you use `app.use(express.json())` globally, register the webhook route first or use a dedicated router.

**Skipping timestamp validation** leaves you vulnerable to replay attacks.

**Using standard string comparison** leaks timing information. Always use constant-time comparison.

<a id="destination-requirements"></a>

## Destination requirements

Use an HTTPS URL of at most 800 characters on port 443 or 8443. The hostname must resolve to public addresses; loopback, private, link-local, metadata and unspecified addresses are refused, including IPv4 addresses mapped into IPv6.

Debitura validates the destination when you register or change its URL and again when connecting for a test or queued delivery. A DNS change to a blocked address prevents sending, even if registration previously succeeded. Connections use a validated address; redirects are not followed. Register the final endpoint URL and return `2xx` directly.

<a id="retry-behavior"></a>

## Retry Behavior

Debitura retries failed webhook deliveries with exponential backoff up to 8 attempts. Your endpoint should:

-   Return `2xx` within 10 seconds
-   Be [idempotent](https://docs.debitura.com/developer-concepts/idempotency.md#webhook-consumption) (same event may be delivered multiple times)
-   Process asynchronously if handling takes longer than 10 seconds

If a delivery is failing, see [Webhook Troubleshooting](https://docs.debitura.com/developer-concepts/webhooks/troubleshooting.md) for error message reference.

<a id="delivery-order-is-not-guaranteed"></a>

### Delivery order is not guaranteed

Each event is delivered as an independent message with its own retry schedule, so **arrival order across events is not guaranteed**. For example, a case close emits a `case.updated` event followed by a `case.closed` event, but a retry on the first can cause `case.closed` to arrive at your endpoint before `case.updated`.

Do not infer state from the order in which events arrive. Treat every event as independent and [idempotent](https://docs.debitura.com/developer-concepts/idempotency.md#webhook-consumption): key off the event `id`, and when you need the authoritative current state of a case, re-fetch it via the API rather than reconstructing it from the event sequence.

<a id="local-development"></a>

## Local Development

To receive webhook deliveries on your local machine, expose a local port via a tunneling tool before creating your test subscription.

<a id="ngrok"></a>

### ngrok

```bash
# Expose port 3000
ngrok http 3000
```

ngrok prints a forwarding URL (e.g. `https://abc123.ngrok.io`). Use this as the endpoint URL when creating a test subscription. Set `isTestMode: true` so the subscription receives only test case events and never picks up production traffic. Exception — on the Referral Partner API, non-case events (client link, onboarding, contract and `cases.replay_failed` events) go to all of the partner's subscriptions, test and live alike.

<a id="cloudflared-alternative"></a>

### cloudflared (alternative)

```bash
cloudflared tunnel --url http://localhost:3000
```

Cloudflare Tunnel provides a stable URL without requiring an ngrok account.

<a id="identifying-test-deliveries"></a>

### Identifying test deliveries

A test subscription (`isTestMode: true`) only ever receives events from test cases — production events are never delivered to it. This holds for case events. On the Referral Partner API, non-case events (client link, onboarding, contract, `cases.replay_failed`) are delivered to test subscriptions too. You don't need a special header to distinguish test traffic: if your subscription is a test subscription, every delivery it receives is from a test case.

<a id="delivery-history"></a>

## Delivery History

Each dispatched webhook event is recorded and queryable. Use `GET /webhooks/events` to inspect what fired for a given case. A result aggregates retry history in `attemptCount` and reports the latest response code or error; the endpoint does not return one row per delivery attempt.

```http
GET /webhooks/events?caseId={id}&since=2026-01-15T00:00:00Z
XApiKey: your_api_key
```

This is available on both the **Customer API** (`https://customer-api.debitura.com`) and the **Collection Partner API** (`https://collectionpartner-api.debitura.com`). For full details — including how to replay events and use the fire primitive — see the [CI Testing guide](https://docs.debitura.com/developer-concepts/webhooks/ci-testing.md).

<a id="deprecated-customer-api-post-webhooksidreplay"></a>

### Deprecated: Customer API `POST /webhooks/{id}/replay`

Deprecated

`POST /webhooks/{id}/replay` is deprecated and should not be used in new integrations. Use `GET /webhooks/events?caseId={id}` to inspect delivery history and `POST /webhooks/events/{id}/replay` to re-deliver a specific event.

Despite its name, `POST /webhooks/{id}/replay` does not replay events — it returns a count of cases created since a given timestamp (`eventsReplayed`). The endpoint is kept for backward compatibility. (An older colon form `{id}:replay` also works if the colon is percent-encoded as `%3A`, but the slash form is canonical.) See [Delivery History & Replay](https://docs.debitura.com/clients/integration-guides/webhooks.md#delivery-history--replay) in the Client webhook guide for context.

<a id="test-vs-live-subscriptions"></a>

## Test vs Live subscriptions

Every webhook subscription is either a **test subscription** or a **live subscription**, set by the `isTestMode` field. You can change it after the subscription is created — the classification is updated in place (no delete-and-recreate needed).

| `isTestMode` | What events it receives |
| --- | --- |
| `false` (default) | Events from live production cases only |
| `true` | Events from test cases only |

On the Referral Partner API, non-case events (client link, onboarding, contract, `cases.replay_failed`) are delivered to both test and live subscriptions.

Use a test subscription while building your integration — it receives events from test cases without interfering with your live production handler. Once your handler is working correctly, create a separate live subscription (`isTestMode: false`) for production traffic.

Switching test and live mode

To switch a subscription between test and live mode, update `isTestMode` on the existing subscription — `PATCH` on the Customer API, or the update (`PUT`) endpoint on the partner APIs. The classification is re-applied in place; you do not need to delete and recreate the subscription.

Run both simultaneously

Test subscriptions and live subscriptions are independent. You can run both at the same time — for example, a live subscription for production and a test subscription pointed at a staging endpoint.

<a id="integration-specific-setup"></a>

## Integration-Specific Setup

For webhook configuration and event types specific to your integration, see [Client Webhooks](https://docs.debitura.com/clients/integration-guides/webhooks.md), [Referral Partner Webhooks](https://docs.debitura.com/referral-partners/integration-guides/webhooks.md), or [Collection Partner Webhooks](https://docs.debitura.com/collection-partners/integration-guides/webhooks.md).
