# Events and webhooks

---

## Overview

When a customer pays one of your invoices, a credit note is posted against it, a payment is reversed, or your accountant cancels it, your ledger changes — not your system. **Events** tell you about it.

* **Which invoices:** the invoices you created **through the API** — job and non-job, sales and purchase.
* **Two ways to receive them, with the same content:**
  * **Webhooks** — we POST each event to an address you choose, signed with your secret. Fast.
  * `**GET /events**` — you ask for everything after the last event you processed. The record, and your catch-up after an outage.
* **How fast:** your ledger is read every few minutes, so an event usually arrives within **5 minutes** of the change.
* **Needs the Accounting module** on, for the companies (legal entities) you picked. Payments live in your ledger.

Use both: react to webhooks, and every so often (hourly is plenty, and always after an outage on your side) read `GET /events` from the last id you processed. A missed webhook can then delay a status, never lose one.


---

## The event

```json
{
  "id": 1042,
  "type": "invoice.partly_paid",
  "occurredAt": "2026-11-03T06:40:01.982Z",
  "invoice": {
    "side": "sales",
    "ledgerName": "INV-2026-00123",
    "fmsInvoiceId": 400123,
    "company": "Example Logistics Pte Ltd",
    "party": "CUST-0042",
    "currency": "SGD",
    "total": 500,
    "outstanding": 366.67,
    "previousOutstanding": 500,
    "status": "partly_paid",
    "externalInvoiceNo": null,
    "externalJobNo": null
  },
  "cause": "credit_note",
  "documents": [
    { "kind": "credit_note", "doctype": "Sales Invoice", "name": "CN-2026-00045", "postingDate": "2026-11-03", "amount": 100, "reference": null, "cancelled": false }
  ]
}
```

| Field | Meaning |
|-------|---------|
| `id`  | The event's number. Events are numbered in the order they happened. Use it to skip duplicates and to ask `GET /events?after=` |
| `type` | `invoice.paid` (nothing left outstanding), `invoice.partly_paid` (less outstanding, not zero), `invoice.payment_cancelled` (the outstanding went back up), `invoice.cancelled` (cancelled in your ledger) |
| `invoice.ledgerName` | The invoice's name in your ledger. A job invoice is renumbered when it is posted; this is its posted name |
| `invoice.fmsInvoiceId` | For a job invoice, the `invoiceId` the invoice writes answered. `null` for a non-job invoice |
| `invoice.outstanding` / `previousOutstanding` | What is owed now, and before this change |
| `invoice.status` | `paid`, `partly_paid`, `unpaid` or `cancelled` |
| `invoice.externalInvoiceNo` / `externalJobNo` | Your own system's numbers, when you sent them on the invoice (see the operations reference). `null` otherwise. Use them to match a payment to your invoice without keeping a mapping |
| `cause` | Why it changed: `payment`, `journal`, `credit_note`, `debit_note`, `reversal`, `cancellation`, `mixed` (two kinds at once) or `unknown` |
| `documents` | The documents behind it: a payment, a journal, a note. `cancelled: true` on a reversal |

**A credit note is not a payment.** Both lower what is outstanding, and your ledger's own status can read "partly paid" for either. `cause` is how you tell them apart.

A cancel you made **through the API** (`POST /accounting/documents/{doctype}/{name}/cancel`) is not repeated as an event: you already have its answer.


---

## Reading events: `GET /events`

| Parameter | Meaning |
|-----------|---------|
| `after`   | The last event `id` you processed (default `0`: everything kept) |
| `limit`   | 1 to 100 (default 100) |

The answer is `{ "events": [...], "next": <id>, "hasMore": true|false }`, oldest first. Store `next`, and ask again with `after=<next>` while `hasMore` is true. Events are kept **30 days**. Scope: `accounting:read`.


---

## Webhooks

### Setting the address

In the Fr8Labs portal, **API access** → **Webhooks**: one **https** address per environment (Test, Live).

* The first time you set an address you get its **signing secret** (`whsec_…`). **It is shown once.** Store it with your other secrets.
* Changing the address keeps the secret.
* **Send a test** posts a signed `webhook.test` message and tells you whether it arrived.
* **New secret** makes a new one. The previous secret keeps working for **24 hours**, so you can switch over without missing a message. You can make another new secret after those 24 hours.
* **Remove** stops the messages. Events are still in `GET /events`.

The address must be reachable on the public internet over https. Private, local and internal addresses are refused. A token in the address's path or query is fine; we treat the address as a secret.

### The message

`POST` to your address, body = **one event, exactly as** `**GET /events**` **shows it**. Headers:

| Header | Meaning |
|--------|---------|
| `Fr8-Event-Id` | The event `id` |
| `Fr8-Event-Type` | The event `type` (`webhook.test` for a test) |
| `Fr8-Env` | `live` or `test` — one address may receive both |
| `Fr8-Delivery-Attempt` | 1 on the first try, then 2, 3… |
| `Fr8-Signature` | `t=<unix seconds>,v1=<hex>` — see below |

### Checking the signature

`v1` is the HMAC-SHA256 of `<t>.<raw body>` with your secret, in hex. Check it on the **raw body**, before parsing it:

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

function verify(signatureHeader, rawBody, secret) {
  const parts = signatureHeader.split(',');
  const t = Number((parts.find((p) => p.startsWith('t=')) || '').slice(2));
  if (!t || Math.abs(Date.now() / 1000 - t) > 300) return false;             // older than 5 minutes: refuse (replay)
  const want = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
  return parts.filter((p) => p.startsWith('v1=')).some((p) => {
    const got = Buffer.from(p.slice(3), 'hex');
    return got.length === want.length / 2 && crypto.timingSafeEqual(got, Buffer.from(want, 'hex'));
  });
}
```

While a new secret is being phased in, the header carries **two** `v1=` values, one per secret. Accept the message if **any** matches.

### Answering

* Answer with a **2xx** within **10 seconds**. Do the work afterwards (queue it).
* Anything else is a failure: a 3xx (redirects are not followed), 4xx, 5xx, a timeout or a TLS error.
* A failed message is tried again after about 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 15 hours — about **24 hours** in all. After that it is marked failed; **Resend failed** in the portal sends those again. `GET /events` has them either way.

### Duplicates and order

* A message can arrive **more than once**. Ignore an `id` you have already processed.
* Messages can arrive **out of order**. Each carries the invoice's current numbers, and `id` gives the order: never let an older `id` overwrite a newer one.


---

## Testing

The shared sandbox (test keys) and your live company work the same way. To see an event, create an invoice through the API, post it, then post a payment, journal or credit note against it.


---

Documentation owner: Fr8Labs Customer Success. Text reviewed: 18 October 2026.