# Webhook router

> Verify, finish installs and dispatch deliveries by topic.

Source: https://storeware.ai/docs/sdk/router

```ts
import { ... } from '@storeware/plugin-sdk';
```

### createWebhookRouter

```ts
function createWebhookRouter(options: { secret: SecretSource; onInstallGrant?: (install: { grant: string; installationId: string | null; storeId: string | null; }) => Promise<string>; before?: EventHandler; toleranceSeconds?: number; }): WebhookRouter
```

### EventHandler

```ts
type EventHandler<T = unknown> = (event: StorewareEvent<T>) => void | Promise<void>;
```

### DeliveryAddress

Which installation a delivery is for, read before it is verified.

| Name | Type | Description |
| --- | --- | --- |
| `storeId` | `string \| null` |  |
| `installationId` | `string \| null` | Present on events about your app (`app.*`), absent on shop events. |
| `namedInstallationId?` | `string \| null` | The installation the `storeware-installation` header names, which Storeware sends on every delivery. Not signed: naming the wrong one only picks a secret that fails. |

### SecretSource

Where the webhook secret comes from. One string for an app in one shop; otherwise a lookup by shop, because every installation has its own secret. Return nothing for a shop you hold no secret for.

```ts
type SecretSource = string | ((address: DeliveryAddress) => string | null | undefined | Promise<string | null | undefined>);
```

### WebhookRouter

| Name | Type | Description |
| --- | --- | --- |
| `on` | `<T = unknown>(topic: string, handler: EventHandler<T>) => WebhookRouter` | Handles one topic, such as `order.paid.v1`. |
| `onLifecycle` | `(handler: EventHandler) => WebhookRouter` | Handles `app.installed.v1`, `app.uninstalled.v1` and the other events about your app. |
| `onCompliance` | `(handler: EventHandler) => WebhookRouter` | Handles the requests the law obliges you to act on: a customer's data asked for, a customer erased, a shop's data to delete. Sent to `[privacy] url` when your manifest declares one. |
| `onBilling` | `(handler: EventHandler) => WebhookRouter` | Handles what happens to what a shop pays you: a plan approved, changed, declined or ended (`app_subscription.*`), a one-time charge accepted or declined (`app_purchase.*`), a period's usage near or at its cap (`app_usage.*`). |
| `handle` | `(request: Request) => Promise<Response>` | Verifies and dispatches one request. Works with any fetch-style server. |
