# Using the webhooks

## Overview

A webhook is how Aiwyn lets your automation know that something just happened, like an engagement being signed or a payment coming in. Rather than your automation checking in with Aiwyn every few minutes to ask whether anything changed, Aiwyn sends a message to a web address you choose, right when it happens.

Here's the short version:

- **You pick the events.** Each subscription is one kind of record plus one thing happening to it, for example "engagement, signed".
- **You provide a web address** (it must start with `https://`) that your automation listens on.
- **Aiwyn sends a short message** with what happened and the IDs involved. Your automation uses the API to fetch anything else it needs.
- **Aiwyn signs every message**, so your automation can prove it came from Aiwyn.
- **Aiwyn sends each event once.** If your address is down or answers with an error, the event is not sent again, so pair your webhook with a scheduled job that catches up through the API.


From here, the guide gets more technical. It's written for the developer building the receiver, and there's a full list of events at the end for anyone who wants to see what's possible.

## Finding the events available to you

The events available can vary from firm to firm. The catalog endpoint shows which ones are switched on for your firm (the examples use `$AIWYN_BASE_URL` and a token as set up in [Using the API](/guides/using-the-api); on Sandbox and Staging, also send the Cloudflare Access headers):

```bash
curl --request GET "$AIWYN_BASE_URL/api/v1/event-subscriptions/catalog" \
  --header 'Authorization: Bearer <token>'
```

Each entry has an `entity` (the kind of record, such as `Engagement` or `Payment`), an `operation` (what happened, such as `SIGNED` or `CREATED`), and whether it is `enabled`. The catalog lists enabled events; add `?enabled=false` to see the ones that are switched off. `CREATED` and `UPDATED` events for `Client`, `Contact`, `ContactClient`, `Job` and `Engagement` also need change tracking switched on for your firm. If an event you need is missing, or a subscribed event never arrives, ask your Aiwyn contact.

It's worth checking what an event means before you rely on it, because the exact moment it fires matters. For example, the engagement `SIGNED` event fires when the engagement is executed as a whole, not when each individual document is signed.

## Subscribing and testing

Your API key needs the `EVNT_SUB` role to manage subscriptions, and `WEBHK_TST` to use the test endpoints. See [Authorization](/reference/authorization).

**Create a subscription** with the entity, the operation, and your HTTPS address:

```bash
curl --request POST "$AIWYN_BASE_URL/api/v1/event-subscriptions" \
  --header 'Authorization: Bearer <token>' \
  --header 'Content-Type: application/json' \
  --data '{
    "entityType": "Engagement",
    "operation": "SIGNED",
    "deliveryUrl": "https://automation.yourfirm.com/aiwyn/engagement-signed",
    "description": "Consent outcome to workflow system"
  }'
```

The response's `data.webhookSecret` holds your signing secret. **Store it securely right away**; you need it to verify every message. You can retrieve it again later from `GET /api/v1/event-subscriptions/webhook/secret`. The secret belongs to the user or system user your API key belongs to, not to the key itself, so every subscription they own is signed with the same secret, whichever of their keys created it. Replacing a system user's key leaves the secret unchanged. Replacing a staff member's key also replaces the secret, so fetch it again from `GET /api/v1/event-subscriptions/webhook/secret` after a staff key is rotated.

Payment subscriptions also need a `filterExpression` that says which payments you want; see the reference.

**Test before going live:**

1. Use the test endpoints to sign a sample payload with a secret, and to check that your code computes the same signature. Build your parser against the example payloads in the API reference's webhook section.
2. Trigger the real event in the sandbox (for example, complete a test engagement) and confirm your receiver gets it.
3. Check the subscription's delivery history to see each delivery, the status code your receiver returned, and how long it took.


You can also update a subscription's address or description, deactivate it, and reactivate it.

## What Aiwyn sends

Each delivery is an HTTPS `POST` with a JSON body.

**Headers:**

| Header | What it holds | Use it to |
|  --- | --- | --- |
| `X-Signature` | `sha256=` followed by the message's signature | Verify the message came from Aiwyn |
| `X-Aiwyn-Event-Id` | The event's ID | Log and trace the event |
| `X-Aiwyn-Event-Operation` | What happened, such as `SIGNED` | Route the message |
| `X-Aiwyn-Subscription-Id` | The subscription that matched | Tell subscriptions apart if several share one address |
| `X-Aiwyn-Tenant` | Your firm's tenant identifier | Confirm the message is for your firm |
| `X-Aiwyn-Delivery-Id` | A new ID for each delivery | Log individual deliveries |
| `X-Aiwyn-Timestamp` | When this delivery was sent | Log; reject very old messages if you choose |


**Body** (shape shown; values are illustrative):

```json
{
  "event": {
    "id": 7001,
    "type": "SIGNED",
    "entityType": "Engagement",
    "entityId": "34567",
    "eventTimestamp": "2026-11-02T15:04:05Z",
    "data": {
      "tenant": "yourfirm",
      "primaryRecord": { "...": "the record the event is about" },
      "relatedEntitiesData": { "...": "related records, such as the client and project" },
      "metadata": { "...": "event-specific details, such as a consent decision" }
    }
  },
  "subscription": { "id": 12, "description": "Consent outcome to workflow system" }
}
```

`event.entityId` is the Aiwyn ID of the record the event is about, sent as a string. What is inside `data` depends on the event; the API reference shows an example for each. Treat the payload as a pointer: if you need a value that matters to your firm, such as a consent status, fetch it from the API rather than relying on what the event carried.

## Verifying the signature

Before your automation acts on a message, it should check that the message really came from Aiwyn. Anyone who learns your web address could send it something, but only Aiwyn can sign a message with your secret.

The signature is an HMAC-SHA256 of the **raw request body**, keyed with your webhook secret, Base64-encoded, and prefixed with `sha256=`. To check it:

1. Read the body exactly as received, before parsing it as JSON. Parsing and re-serializing changes the bytes, and the signature will not match.
2. Compute the HMAC-SHA256 of those bytes with your secret, Base64-encode it, and add `sha256=` in front.
3. Compare it with the `X-Signature` header using a constant-time comparison.
4. If they differ, return `401` and do nothing else.


```python
import base64, hashlib, hmac

def is_from_aiwyn(raw_body: bytes, signature_header: str, secret: str) -> bool:
    digest = hmac.new(secret.encode("utf-8"), raw_body, hashlib.sha256).digest()
    expected = "sha256=" + base64.b64encode(digest).decode("ascii")
    return hmac.compare_digest(expected, signature_header or "")
```

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

function isFromAiwyn(rawBody, signatureHeader, secret) {
  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(rawBody).digest("base64");
  const a = Buffer.from(expected);
  const b = Buffer.from(signatureHeader || "");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
```

The validate test endpoint checks a payload, signature, and secret for you, which helps when your result and Aiwyn's disagree. Both test endpoints sign the payload as compact JSON, with no spaces or line breaks, so send them compact JSON too.

## Delivery and duplicates

The most reliable receivers answer quickly and do the real work afterwards: verify the signature, save the event, return `200`, then process it. Aiwyn waits up to 30 seconds for a response.

How Aiwyn treats your response:

| Your receiver returns | What Aiwyn does |
|  --- | --- |
| `2xx` | Delivered. |
| `5xx` or a connection failure | Records a failed delivery and tries again, up to two more times: about a minute later, then five minutes after that. Each retry has the same `X-Aiwyn-Event-Id` and a new delivery ID. |
| Any other status, or no response within 30 seconds | Records a failed delivery in the subscription's delivery history. The event is not sent again. |


A few things that will save you trouble later:

- **Run a catch-up job.** Retries stop after three attempts, and some failures are never retried, so schedule a job that uses the API to find anything that changed while your receiver was down or failing. [Tracking client consent](/guides/track-client-consent) shows one for consent decisions.
- **Expect duplicates.** Aiwyn can report the same change twice, as two events with different IDs: a file uploaded through a client request can raise `File` `CREATED` twice, for example. Before you act, check whether you have already handled that change, using the record's current state or the event's `entityType`, `entityId`, and `type`, rather than `X-Aiwyn-Event-Id` alone. When writing to Aiwyn, use an upsert with a stable `systemRef` so a repeat changes nothing.
- **Do not rely on order.** Two events about the same record may arrive out of order. Fetch the record's current state from the API before acting.
- **Acknowledge before you process.** A slow receiver may still finish work on a request Aiwyn has already given up on.
- **Check the delivery history** when something looks missing. It shows each delivery Aiwyn made, the status code you returned, and any error. If an event doesn't appear there at all, check that the subscription is active, and ask your Aiwyn contact.


## Events you can subscribe to

These are the events Aiwyn sends for the records the API covers. Not all of them are switched on for every firm, so check your firm's catalog (above), and ask your Aiwyn contact if you need one turned on.

| Entity | Operation | When it's sent |
|  --- | --- | --- |
| `Client` | `CREATED` | A client is added |
| `Client` | `UPDATED` | A client's details or contact information change |
| `Contact` | `CREATED` | A contact is added |
| `Contact` | `UPDATED` | A contact's details or contact information change |
| `ContactClient` | `CREATED` | A contact is linked to a client |
| `ContactClient` | `UPDATED` | A contact's link to a client changes |
| `Job` | `CREATED` | A job is added |
| `Job` | `UPDATED` | A job's details change |
| `Engagement` | `CREATED` | An engagement is added |
| `Engagement` | `UPDATED` | An engagement's details or status change |
| `Engagement` | `SIGNED` | The engagement is executed, once every required document is signed and any payment step it asks for is handled. A staff member executing an engagement manually also sends it. |
| `Engagement` | `CONSENT_RECORDED` | A consent document reaches a decision. See [Tracking client consent](/guides/track-client-consent). |
| `Invoice` | `POSTED` | An invoice is posted |
| `Invoice` | `DELETED` | An invoice is reversed |
| `Credit` / `Debit` | `CREATED` | A credit or debit AR transaction is recorded |
| `Credit` / `Debit` | `UPDATED` | Staff change that AR transaction, such as its allocations |
| `Credit` / `Debit` | `DELETED` | That AR transaction is reversed |
| `Payment` | `CREATED` | A payment is started and pending |
| `Payment` | `POSTED` | A payment succeeds and is posted |
| `Payment` | `FAILED` | A payment fails |
| `Payment` | `UPDATED` | A payment made through the open payment portal is reassigned to a client, or staff change a payment's AR allocations |
| `Payment` | `DELETED` | A pending payment fails or is cancelled, or a payment is reversed |
| `Refund` | `POSTED` | A refund is posted |
| `File` | `CREATED` | A file from a client request, a deliverable, a reference file, or a direct upload is added to a client's document storage |
| `File` | `DELETED` | Such a file is removed |
| `RequestItem` | `SENT` | A request item is sent to the client. `event.data.metadata` lists the `recipients` and the item's previous status in `status_old`. |
| `RequestItem` | `APPROVED` | Staff approve an item the client submitted |
| `RequestItem` | `REJECTED` | Staff reject an item the client submitted. `event.data.metadata.notes` carries the reason. |
| `ClientRequest` | `VIEWED` | A staff member opens a client request in the Firm Portal. Sent each time it's opened, not only the first. |


A few notes:

- **Payment subscriptions need a filter** (`filterExpression`) that says which payments you want: only payments through payment links your key created, payments through any of the firm's payment links, or every payment. The last two need the `PYMT_EVNT_ALL` role. `Payment` `UPDATED`, and `Payment` `DELETED` for a reversed payment, only reach subscriptions that take every payment.
- **Deletions of clients, contacts, contact links and jobs are not sent.** Run a scheduled job that compares your records with the API if you need to catch them.
- **A change to contact details is sent as `Client` or `Contact` `UPDATED`.** There is no separate contact info event.
- **New events are added over time.** If you need one that isn't here, let your Aiwyn contact know.


## Related guides

- [Building automations](/guides/building-automations): the overview, and what your firm owns.
- [Tracing IDs](/guides/ids-and-tracing): getting from the IDs in an event to the record you need.
- [Using the API](/guides/using-the-api): getting a key and fetching the details an event points to.
- [API reference](/bundle): the Event Subscriptions endpoints in full.