---
title: "Handle webhooks"
description: "Configure webhook subscriptions and handle event deliveries."
canonical: "https://fragment.dev/docs/handle-webhooks"
---

# Handle webhooks

Source: https://fragment.dev/docs/handle-webhooks

[Documentation index](https://fragment.dev/llms.txt)

<a id="handle-webhooks"></a>

Fragment sends an HTTP POST to your server when something changes in your workspace, such as a Payment settling. Subscribe once and handle every event in one endpoint. The [JSON Schema](https://fragment.dev/schemas/webhooks/webhook.schema.json) defines every event type and its fields.

<a id="subscribe-to-webhooks"></a>

## Subscribe to webhooks

Call `createWebhookSubscription` with an HTTPS URL. The authenticated API client sets the workspace. The subscription receives every event type from every Ledger in that workspace. Errors follow the API's standard [error handling](https://fragment.dev/docs/call-the-api.md#handle-errors).

```graphql title="Create a subscription"
mutation CreateWebhookSubscription($input: CreateWebhookSubscriptionInput!) {
  createWebhookSubscription(input: $input) {
    __typename
    ... on CreateWebhookSubscriptionResult {
      subscription { id }
      signingSecret
    }
    ... on Error { code message retryable }
  }
}
```

```json title="Create variables"
{
  "input": {
    "url": "https://example.com/webhooks/fragment"
  }
}
```

The result holds the new `subscription` and its `signingSecret`. Save `signingSecret` securely on your backend, because the API returns it only in this response. A workspace has one subscription per URL:

- URLs are compared after normalization, so `https://EXAMPLE.com:443/hooks` matches `https://example.com/hooks`.
- A second subscription for the same URL returns `BadRequestError` with code `webhook_subscription_already_exists`.
- To recover a lost signing secret, delete the subscription and create it again.

Call `webhookSubscriptions` to list the active subscriptions in the workspace. The list pages forward. `first` defaults to 20 and accepts up to 100. Pass `endCursor` as `after` while `hasNextPage` is true:

```graphql title="List subscriptions"
query ListWebhookSubscriptions($first: Int, $after: String) {
  webhookSubscriptions(first: $first, after: $after) {
    nodes {
      id
      url
      created
    }
    pageInfo { endCursor hasNextPage }
  }
}
```

Call `deleteWebhookSubscription` with a subscription's ID. Deletion stops queued deliveries and future retries to that subscription. A request already in flight can still finish. A repeated deletion also returns `success: true`. A new subscription at the same URL gets a new ID and signing secret:

```graphql title="Delete a subscription"
mutation DeleteWebhookSubscription($id: ID!) {
  deleteWebhookSubscription(id: $id) {
    __typename
    ... on DeleteWebhookSubscriptionResult { success }
    ... on Error { code message retryable }
  }
}
```

<a id="process-events"></a>

## Process events

Fragment signs each request following the [Standard Webhooks](https://www.standardwebhooks.com/) specification. Verify each request with the subscription's `signingSecret` before you process its event. The [Node SDK](https://fragment.dev/docs/call-the-api.md#set-up-the-sdk) function `verifyWebhook` checks the signature, validates the body and returns a typed event. Pass it the raw request body, before any JSON parsing. An event type your SDK version does not know returns `known: false`. This handler routes events with [`ts-pattern`](https://github.com/gvergnaud/ts-pattern), so an SDK upgrade that adds event types does not break it:

```typescript title="Receive an event"
import express from "express";
import { match } from "ts-pattern";
import {
  verifyWebhook,
  WebhookVerificationError,
} from "@fragment-dev/node-client";

const app = express();

app.post(
  "/fragment/webhooks",
  express.raw({ type: "application/json" }),
  async (req, res) => {
    try {
      const verified = verifyWebhook({
        payload: req.body,
        headers: req.headers,
        secret: process.env.FRAGMENT_WEBHOOK_SECRET!,
      });
      await match(verified)
        .with({ known: false }, ({ event }) => {
          console.log(`Ignoring ${event.type}`);
        })
        .with(
          { known: true, event: { type: "payment.settled" } },
          async ({ event }) => {
            await fulfillOrder({ orderId: event.data.payment.ik });
          },
        )
        .with({ known: true }, ({ event }) => {
          console.log(`Received ${event.type}`);
        })
        .exhaustive();
      res.sendStatus(200);
    } catch (error) {
      if (error instanceof WebhookVerificationError) {
        res.status(400).send(error.code);
        return;
      }
      throw error;
    }
  },
);
```

Return HTTP `2xx` after you save the event or finish processing it. A request times out if your endpoint does not respond within 30 seconds. Fragment retries a request after a network error, a timeout or a non-`2xx` response. It waits 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours and 10 hours before each retry, then stops. The last retry is about 27.5 hours after the first attempt. An event can arrive more than once, and out of order:

- Deduplicate on the workspace ID and the event `id`.
- Find your own record by the idempotency key you set, such as `data.payment.ik`.
- Return HTTP `2xx` for event types your application does not handle.
- A retry carries the same body, including its `id` and `occurredAt`.

Without the Node SDK, verify each request yourself. Each request carries three headers:

- `webhook-id`: the message ID, unchanged across retries. It can differ from the event `id` in the body.
- `webhook-timestamp`: the delivery attempt time, in Unix seconds. Each retry uses the current time.
- `webhook-signature`: space-separated signatures, each formatted as `v1,<base64-encoded signature>`.

The signature is an HMAC-SHA256 over the message ID, the timestamp and the body. Verify it against the raw request body before you parse JSON. Reject a request with an invalid signature, or with a `webhook-timestamp` more than five minutes from your server's time. Check `webhook-timestamp`, not the body's `occurredAt`. Standard Webhooks documents the rest:

- [Signing and verification details](https://github.com/standard-webhooks/standard-webhooks/blob/main/spec/standard-webhooks.md#signature-scheme)
- [Verification libraries](https://github.com/standard-webhooks/standard-webhooks#reference-implementations)

Each request carries one event. This settlement is one example:

```json title="Settlement event"
{
  "type": "payment.settled",
  "id": "example-event-id",
  "occurredAt": "2026-10-27T18:30:00.000Z",
  "data": {
    "workspace": { "id": "example-workspace-id" },
    "ledger": { "id": "example-ledger-id", "ik": "customer-42" },
    "schema": { "key": "invoicing" },
    "payment": { "id": "example-payment-id", "ik": "invoice-1024" },
    "event": {
      "occurredAt": "2026-10-27T18:30:00.000Z",
      "ledgerEntry": { "id": "example-entry-id" }
    }
  }
}
```

Every event has these fields:

```typescript title="Event fields"
type WebhookEvent = {
  id: string; // Payment event ID. Deduplicate on it within the workspace.
  type: string; // Event name, such as payment.settled.
  occurredAt: string; // ISO 8601 source event time, independent of delivery time.
  data: {
    workspace: { id: string }; // The owning workspace.
    ledger: { id: string; ik: string }; // ik is your key for the Ledger.
    schema: { key: string }; // The owning Ledger's Schema key.
    payment: { id: string; ik: string }; // ik is the Payment's idempotency key.
    event: { occurredAt: string }; // Plus the fields of the event type.
  };
};
```

A subscription receives every event type. [Webhook Events](https://fragment.dev/api-reference/webhook-events.md) lists each one and its fields. Validate payloads with the [JSON Schema](https://fragment.dev/schemas/webhooks/webhook.schema.json).
