# Example: Tracking client consent

Use this guide to copy a client's consent decision (for example an IRS Section 7216 consent) from Aiwyn into
another system, such as your workflow or tax software, as soon as the client answers.

You combine two things:

1. **A webhook** that tells you the moment a consent is decided.
2. **A reconciliation job** that catches anything the webhook missed. Each webhook is sent once and is not
retried, so a short outage on your side would otherwise lose decisions.


## Before you start

- **An API key** with these roles: `EVNT_SUB` (subscriptions and the signing secret) and `RECD_C` (writing
your IDs onto clients). The base `API_ADMIN` role every key has covers reading engagements, their documents,
and clients. Add `WEBHK_TST` while you build, to use the webhook test endpoints. See [Authorization](/reference/authorization).
- **The `Engagement` `CONSENT_RECORDED` event enabled for your firm.** Check
`GET /api/v1/event-subscriptions/catalog`. If it is not listed, ask your Aiwyn contact to enable it.
- **A way to match clients.** Aiwyn's client ID is not your system's client ID. See
[Match Aiwyn clients to your system](#match-aiwyn-clients-to-your-system).


The examples use `$AIWYN_BASE_URL` and `$TOKEN` as set up in the [Quickstart](/reference/quickstart). On Sandbox
and Staging, also send the Cloudflare Access headers described in [Base URLs](/reference/base-urls).

## How a consent is decided

A consent document can have more than one signer, for example both spouses on a joint return. The
document's `signatureRequirementType`, which the event carries, says whether every signer has to agree:

| Signers' answers | `ALL_SIGNATURES_REQUIRED` | `ONE_SIGNATURE_REQUIRED` |
|  --- | --- | --- |
| Every active signer agreed | `AFFIRMATIVE`, dated by the last agreement | `AFFIRMATIVE`, dated by the first agreement |
| One signer agreed, the others have not answered | No decision yet, no event | `AFFIRMATIVE`, dated by that agreement |
| One signer declined, the others have not answered | `NEGATIVE`, dated by that decline | No decision yet, no event |
| Every active signer declined | `NEGATIVE`, dated by the first decline | `NEGATIVE`, dated by the last decline |


For `ALL_SIGNATURES_REQUIRED` documents these are the same rules as `affirmativeStatus` on the documents
endpoint, so the webhook and the reconciliation below agree. For `ONE_SIGNATURE_REQUIRED` documents they
can differ: see the reconciliation step. Once a decision is reached, a later answer from another signer does not change
it and raises no new event. If the firm resends the consent and the client answers again, you get a new
event. A paper consent the firm records when it executes an engagement manually raises the same event, with
the staff member as the actor.

`decidedAt` and each signer's `consentProvidedAt` have no time zone offset. Answers given in the client
portal are recorded in UTC. A paper consent carries the date and time the firm entered for it. `decidedAt`
is `null` for a decline that was recorded without a date.

## 1. Subscribe to the event

```bash
curl --request POST "$AIWYN_BASE_URL/api/v1/event-subscriptions" \
  --header "Authorization: Bearer $TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{
    "entityType": "Engagement",
    "operation": "CONSENT_RECORDED",
    "deliveryUrl": "https://example.com/webhooks/aiwyn"
  }'
```

Get your signing secret from `GET /api/v1/event-subscriptions/webhook/secret`.

## 2. Receive the webhook

For every request:

1. **Verify `X-Signature`** over the raw body before parsing it. It is `sha256=` followed by the Base64
HMAC-SHA256 of the body, keyed with your signing secret.
2. **Respond `2xx` within 30 seconds**, then do the work. A slow response counts as a failed delivery.
3. **Ignore repeats.** Before you write a decision, check whether you have already recorded it for that document, rather than relying on `X-Aiwyn-Event-Id` alone.


The decision is in `event.data.metadata`:

```json
{
  "engagementDocumentId": 8840,
  "engagementDocumentTypeId": 4,
  "signatureRequirementType": "ALL_SIGNATURES_REQUIRED",
  "consentStatus": "NEGATIVE",
  "decidedAt": "2026-11-01T18:19:58.402",
  "signers": [
    {
      "engagementDocumentContactId": 9911,
      "contactId": 2044,
      "consentStatus": "NEGATIVE",
      "consentProvidedAt": "2026-11-01T18:19:58.402"
    }
  ]
}
```

`event.entityId` is the engagement ID. `event.data.relatedEntitiesData` lists the engagement's clients
(`Client`), their client groups (`ClientGroup`) and its projects (`Job`). Use the client to find the matching
record in your system, then write the decision there.

## 3. Reconcile on a schedule

Run this every few hours, and once after any outage on your side. Answering a consent does not change the
engagement itself, so you can't find answered consents by the engagement's `updatedAt` alone. Each run,
check two sets of engagements that have a consent document:

- **Every engagement still out with the client** (`SENT` or `UNDER_REVISION`), since a signer can answer at
any time.
- **Every engagement changed since your last run**, which catches engagements that were executed or canceled
in the meantime.


```bash
curl --request POST "$AIWYN_BASE_URL/gql/v1/engagements/search" \
  --header "Authorization: Bearer $TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{
    "pageSize": 100,
    "page": 0,
    "where": {
      "_and": [
        { "documents": { "engagementDocumentTypeId": { "_eq": 4 } } },
        {
          "_or": [
            { "status": { "_in": ["SENT", "UNDER_REVISION"] } },
            { "updatedAt": { "_gte": "2026-11-01T00:00:00Z" } }
          ]
        }
      ]
    },
    "orderBy": [{ "id": "asc" }]
  }'
```

Page with `page` until you pass `total.aggregate.count`. Save the run's start time as the next `updatedAt`
checkpoint. To keep runs small, you can skip engagements whose consent your system already holds.

**Read each engagement's consent status:**

```bash
curl "$AIWYN_BASE_URL/gql/v1/engagement_documents/by_engagement/{engagementId}" \
  --header "Authorization: Bearer $TOKEN"
```

For the document with `engagementDocumentTypeId` `4`, `affirmativeStatus` is `AFFIRMATIVE` or `NEGATIVE` once
the consent is decided. It is `INDETERMINATE` or empty while signers still have to answer: do nothing yet.
For a `ONE_SIGNATURE_REQUIRED` document, `affirmativeStatus` doesn't apply the one-signature rule: any decline makes it `NEGATIVE`, and an agreement while other signers haven't answered makes it `INDETERMINATE`. Leave those documents to the `CONSENT_RECORDED` webhook.
Write the status only if your system does not already hold it, so the webhook and this job never fight.

## Match Aiwyn clients to your system

Store your system's client ID on each Aiwyn client as a client custom field, so every event and every
reconciliation run can look it up directly.

1. Ask your Aiwyn contact to add a client custom field for it, for example `workflow_client_id`.
2. Write it once per client, addressing the client by its Aiwyn ID:


```bash
curl --request PUT "$AIWYN_BASE_URL/api/v1/records" \
  --header "Authorization: Bearer $TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{
    "records": [
      {
        "type": "Client",
        "systemRef": { "system": "aiwyn", "reference": "1001" },
        "attributes": { "workflow_client_id": "10031.5" }
      }
    ]
  }'
```

1. Read it back from the client's `customFieldValues` with `GET /gql/v1/client/{id}`.


Keep the mapping up to date when clients are added or merged in either system. If one client in Aiwyn maps
to several records in your system, decide which record each consent belongs to before you start.