# Webhooks

> Register an endpoint, prove you own it, and receive event deliveries

Source: https://app.relvoerp.com/docs/product/guides/webhooks/

Webhook endpoints let your application receive Relvo events as HTTP callbacks, instead of polling: invoices, credit notes and debit notes accepted or rejected by the tax authority, invoices entering draft, payments, paid and voided invoices, contract and customer changes, and customer emails arriving in Relvo. The full list is in [Events](https://app.relvoerp.com/docs/product/guides/webhooks.md#events). Registering one is a two-step process: create the endpoint, then prove you control the URL.

## Endpoint lifecycle

```
pending_verification → active ⇄ disabled
          any status → deleted
```

| Status | Meaning |
|---|---|
| `pending_verification` | Registered, but ownership hasn't been confirmed yet. No events are delivered here. |
| `active` | Verified and receiving deliveries for its subscribed event types. |
| `disabled` | Paused with `POST /{id}/disable`. Resume it with `POST /{id}/enable`. |
| `deleted` | Removed. Its URL is free to register again as a new endpoint. |

## 1. Register an endpoint

Authenticate with an API token that has `webhooks:write` (or `webhooks:read` for the `GET` operations). See [Authentication](https://app.relvoerp.com/docs/product/guides/authentication.md).

| Operation | Method & path |
|---|---|
| List / get endpoints | `GET /public/webhook-endpoints`, `GET /public/webhook-endpoints/{id}` |
| Create an endpoint | `POST /public/webhook-endpoints` |
| Verify / reissue challenge | `POST /public/webhook-endpoints/{id}/verify`, `POST /{id}/reissue-challenge` |
| Disable / enable | `POST /{id}/disable`, `POST /{id}/enable` |
| Rotate the signing secret | `POST /{id}/rotate-secret` |
| Replace subscriptions | `PUT /{id}/subscriptions` |
| Delete | `DELETE /{id}` |
| List / get deliveries | `GET /{id}/deliveries`, `GET /{id}/deliveries/{delivery_id}` |
| Redeliver | `POST /{id}/deliveries/{delivery_id}/redeliver` |

Every `POST` needs an `Idempotency-Key` header with a unique value you generate, such as a UUID. Retrying with the same key and body returns the original result without repeating the action, so network retries are safe. Every write on an existing endpoint also needs `If-Match: W/"<version>"`. This covers all actions, `PUT` and `DELETE`. Take the value from the endpoint's `version` or its `ETag` header. `PUT` and `DELETE` take no `Idempotency-Key`, because `If-Match` already makes them safe to retry. `redeliver` acts on a delivery rather than the endpoint, so it takes no `If-Match`. Lists return `{items, next_cursor}`.

Errors use the [standard envelope](https://app.relvoerp.com/docs/product/guides/errors.md). Branch on `code`, never on `message`. The wire `code` is snake_case. The dotted form in brackets is the same error's internal name, which appears in older integrations and logs:

| Status | `code` | Meaning |
|---|---|---|
| `400` | `idempotency_key_required` | A `POST` without an `Idempotency-Key` header. |
| `400` | `invalid_idempotency_key` | The key is not 8–128 characters of `A–Z a–z 0–9 . _ -`. |
| `400` | `invalid_if_match` | `If-Match` is not a `W/"<version>"` ETag. |
| `404` | `webhook_endpoint_not_found` | Wrong ID or another organization's endpoint. |
| `404` | `webhook_delivery_not_found` | The delivery does not exist or belongs to another endpoint. |
| `409` | `webhook_endpoint_url_taken` | Create: a live (not `deleted`) endpoint already uses this URL. |
| `409` | `webhook_endpoint_state_conflict` | The endpoint's status does not allow the operation (e.g. `/verify` on an endpoint that is not `pending_verification`). |
| `409` | `webhook_verification_failed` | `/verify`: your endpoint did not answer 2xx with the challenge echoed, could not be reached, or resolves to a non-public address. |
| `409` | `webhook_delivery_not_eligible` | `redeliver` on a delivery that is still `pending`, `retry_scheduled` or `in_flight`. |
| `409` | `idempotency_key_reused` | The `Idempotency-Key` was already used with a different request. |
| `412` | `version_conflict` | `If-Match` is stale. Re-read the endpoint and retry. |
| `422` | `validation_failed` (`params.field`: `endpoint_url`) | Create: invalid URL or an unknown event type. |
| `422` | `validation_failed` (`params.field`: `subscriptions`) | Replace subscriptions: an unknown or duplicated pair. |
| `428` | `precondition_required` | A write on an existing endpoint without `If-Match`. |

```bash
curl -X POST "https://app.relvoerp.com/api/v1/public/webhook-endpoints" \
  -H "Authorization: Bearer rk_live_xxxxxxxxxxxxxxxxxxxx" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H "Content-Type: application/json" \
  -d '{
    "endpoint_url": "https://example.com/relvo/webhooks",
    "subscriptions": [
      { "event_type": "invoice.issued", "schema_version": 1 },
      { "event_type": "message.received", "schema_version": 1 }
    ]
  }'
```

```json
{
  "id": "018f1234-5678-7abc-def0-1234567890ab",
  "status": "pending_verification",
  "signing_secret": "kP3x_9vN2-qT7...",
  "verification_challenge": "AbC123-xyz..."
}
```

Two values in the response are shown only once — store them immediately:

- **`signing_secret`**: the key for verifying every future delivery to this endpoint. See [Verifying delivery signatures](https://app.relvoerp.com/docs/product/guides/webhooks.md#verifying-delivery-signatures). It is an opaque URL-safe string with no prefix, and it is never shown again. If it is lost or compromised, rotate it. See [Rotating the signing secret](https://app.relvoerp.com/docs/product/guides/webhooks.md#rotating-the-signing-secret).
- **`verification_challenge`**: the value your endpoint must hand back to prove ownership. It expires **15 minutes** after creation. `POST /{id}/reissue-challenge` issues a fresh one.

The response also carries `version` (here `1`) and an `ETag: W/"1"` header. Send that value as `If-Match` on the next write.

## 2. Implement the verification handshake

Before Relvo marks your endpoint `active`, it sends this to the URL you registered:

```
POST <your endpoint_url>
User-Agent: Relvo-Webhooks/1.0
Content-Type: application/json
Relvo-Verification: <challenge>
Relvo-Timestamp: <unix seconds>
Relvo-Webhook-Version: v1
Relvo-Signature: v1=<hex>

{"type":"relvo.webhook.verify","challenge":"<challenge>"}
```

The challenge is sent both ways — header and body — so you can read it from whichever is easiest. The request is signed exactly like an event delivery, with the same `signing_secret` and the same `Relvo-Timestamp` / `Relvo-Signature` headers (see [Verifying delivery signatures](https://app.relvoerp.com/docs/product/guides/webhooks.md#verifying-delivery-signatures)), so a handler that checks signatures on every request can keep doing so. If your signature check would reject it, it would reject every real delivery too, and `/verify` tells you now instead of after go-live. Your endpoint needs to:

1. Recognize `type == "relvo.webhook.verify"` instead of routing it into your normal event handling.
2. Respond `2xx`.
3. Echo the challenge back, either as a `Relvo-Verification` response header or a `{ "challenge": "..." }` JSON body. One of the two is enough.

```ts
const payload = await request.json();

if (payload.type === "relvo.webhook.verify") {
  return json({ challenge: payload.challenge }, { status: 200 });
}

// ... handle your normal event types below
```

If your handler only matches known business event types and ignores everything else, it will 2xx the verification request without echoing anything — and verification will keep failing. Match `relvo.webhook.verify` explicitly.

## 3. Trigger verification

Once your endpoint is ready to answer the handshake:

```bash
curl -X POST "https://app.relvoerp.com/api/v1/public/webhook-endpoints/{id}/verify" \
  -H "Authorization: Bearer rk_live_xxxxxxxxxxxxxxxxxxxx" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H 'If-Match: W/"1"'
```

| Result | Meaning |
|---|---|
| `200 OK` | Verified. The endpoint moves to `active` and starts receiving real deliveries. The body holds the endpoint and its new `version`. |
| `409 webhooks_verification_failed` | Your endpoint did not respond 2xx, did not echo the challenge correctly, or could not be reached. Fix your handler and call `/verify` again. You need a fresh challenge from `/reissue-challenge` only after it expires, 15 minutes after it was issued. |
| `409 webhooks_endpoint_state_conflict` | The endpoint is not `pending_verification`: it is already `active`, `disabled` or `deleted`. |
| `404 webhooks_endpoint_not_found` | Wrong ID or wrong organization. |
| `412 version_conflict` | The `If-Match` value is stale. Re-read the endpoint first. |

`/verify` is idempotent per `Idempotency-Key`: retry a timed-out call with the same key.

## Events

Subscribe with an `event_type` and `schema_version` pair from this table. It is the complete list. Any other pair, such as `payment.received` or `invoice.overdue`, is rejected with `422 validation_webhook_endpoint` when you create the endpoint.

| `event_type` | `schema_version` | Sent when | `data` fields |
|---|---|---|---|
| `invoice.drafted` | 1 | An invoice enters draft | `invoice_id` |
| `invoice.issued` | 1 | The tax authority accepts an invoice | `invoice_id`, `fiscal_uuid`, `folio` |
| `invoice.fiscal_rejected` | 1 | The tax authority rejects an invoice, or the customer claims it | `invoice_id`, `rejection_reason`, `rejection_source` |
| `credit_note.issued` | 1 | The tax authority accepts a credit note | `credit_note_id`, `source_invoice_id`, `fiscal_uuid`, `folio` |
| `credit_note.fiscal_rejected` | 1 | The tax authority rejects a credit note | `credit_note_id`, `source_invoice_id`, `rejection_reason` |
| `debit_note.issued` | 1 | The tax authority accepts a debit note | `debit_note_id`, `source_invoice_id`, `fiscal_uuid`, `folio` |
| `debit_note.fiscal_rejected` | 1 | The tax authority rejects a debit note | `debit_note_id`, `source_invoice_id`, `rejection_reason` |
| `message.received` | 1 | A customer email arrives in Relvo: a reply to a Relvo email or a new message | `message_id`, `conversation_id`, `received_at`, `sender_email`, `subject`, `text_preview`, `attachments`, `invoice_ids` |
| `invoice.payment_received` | 1 | A payment is applied to an invoice, partially or in full | `invoice_id`, `payment_id`, `amount_paid`, `currency`, `payment_status` |
| `invoice.paid` | 1 | An invoice becomes fully paid | `invoice_id`, `total_amount`, `currency`, `paid_at` |
| `invoice.voided` | 1 | An accepted credit note voids the whole invoice | `invoice_id`, `credit_note_id` |
| `payment.succeeded` | 1 | A payment is confirmed as received | `payment_id`, `customer_id`, `amount`, `currency`, `origin` |
| `contract.activated` | 1 | A contract becomes active | `contract_id`, `customer_id` |
| `contract.amended` | 1 | An amendment is applied to a contract | `contract_id`, `customer_id` |
| `contract.cancelled` | 1 | A contract is cancelled | `contract_id`, `customer_id` |
| `customer.created` | 1 | A customer is created | `customer_id` |
| `customer.updated` | 1 | A customer's details are edited | `customer_id` |
| `customer.deleted` | 1 | A customer is deleted | `customer_id` |

`fiscal_uuid`, `folio` and `rejection_reason` are `null` when the tax authority did not provide them.

`rejection_source` on `invoice.fiscal_rejected` says who rejected the invoice: `tax_authority`, `customer_claim` (the customer claimed the accepted document, which voids its acceptance) or `imported` (it was already rejected when imported). It is `null` for events sent before 2026-10-27.

Amounts are decimal strings, such as `"10.50"`, with an ISO 4217 `currency`. In `invoice.payment_received`, `amount_paid` is the **total paid on the invoice so far**, not the amount of this one payment. `payment_status` is `unpaid`, `partially_paid` or `paid`, and `payment_id` is `null` when the payment was not recorded in Relvo. `credit_note_id` on `invoice.voided` is `null` unless exactly one credit note voided the invoice. `payment.succeeded` describes the payment itself: `amount` is what was received, `customer_id` is `null` until the payment is matched to a customer, and `origin` is `manual`, `bank_transfer`, `point_of_sale` or `payment_provider`. Each time the payment is applied to an invoice, you also get an `invoice.payment_received`. Payment reversals and partial voids don't send an event, and customer events cover customers only, not vendors.

### Delivery body

Every delivery has the same envelope. Only `data` changes with the event type:

```json
{
  "id": "019a2b3c-4d5e-7f60-8a1b-2c3d4e5f6a7b",
  "type": "message.received",
  "schema_version": 1,
  "occurred_at": "2026-10-13T14:02:11.000Z",
  "organization_id": "0190f1e2-d3c4-7b5a-9687-a1b2c3d4e5f6",
  "data": {
    "message_id": "019a2b3c-5e6f-7a80-9b1c-2d3e4f5a6b7c",
    "conversation_id": "019a2b3c-6f70-7b81-8c2d-3e4f5a6b7c8d",
    "received_at": "2026-10-13T14:02:11.000Z",
    "sender_email": "ap@customer.cl",
    "subject": "OC 4512",
    "text_preview": "Adjunto la orden de compra…",
    "attachments": [
      { "id": "019a2b3c-7081-7c92-9d3e-4f5a6b7c8d9e", "filename": "oc-4512.pdf", "content_type": "application/pdf" }
    ],
    "invoice_ids": []
  }
}
```

- `id` is the event id, the same value as the `Relvo-Event-Id` header. Use it to deduplicate, because a retried or redelivered event keeps its id.
- `occurred_at` is UTC ISO-8601 with milliseconds.
- `schema_version` is the version you subscribed to. Before this release the field was named `version`. Retries and redeliveries of deliveries created before the rename keep their original body. Until those drain, read `schema_version` and fall back to `version`.

### Delivery guarantees

- **At least once.** A delivery is retried until your endpoint answers `2xx`, so the same event can arrive more than once. Deduplicate on the `Relvo-Event-Id` header, which equals the envelope `id` and stays the same across retries and redeliveries.
- **Order is not guaranteed.** `invoice.paid` can arrive before `invoice.payment_received`, for example. When order matters, fetch the current state of the resource instead of relying on arrival order.
- If your endpoint was down, the [event log](https://app.relvoerp.com/docs/product/guides/webhooks.md#event-log) keeps every event for 30 days.

### Fetching the full resource

Payloads name the resource and what happened to it. They never carry line items. To get the rest, call the public API with an API token:

| Field in `data` | Endpoint | Token scope |
|---|---|---|
| `invoice_id`, `source_invoice_id` | `GET /api/v1/public/invoices/{invoice_id}` | `invoices:read` |
| `contract_id` | `GET /api/v1/public/contracts/{contract_id}` | `contracts:read` |
| `customer_id` | `GET /api/v1/public/customers/{customer_id}` (`404` after `customer.deleted`) | `customers:read` |
| `credit_note_id` | `GET /api/v1/public/credit-notes/{credit_note_id}` | `invoices:read` |
| `debit_note_id` | `GET /api/v1/public/debit-notes/{debit_note_id}` | `invoices:read` |
| `message_id` | `GET /api/v1/public/messages/{message_id}` | `messages:read` |

A `message.received` event is sent as soon as the email is saved, before Relvo downloads its body and attachments, so `GET` the message works immediately. The body and attachments appear in that response once Relvo has fetched them. `text_preview` is the email provider's short preview, not the full body. The public API returns attachment metadata (`id`, `filename`, `content_type`) only; the file itself can be downloaded from the Relvo app, not with an API token.

## Event log

Every public event is logged for **30 days**, whether or not an endpoint subscribed to it. Use the log to catch up after downtime or to check what you missed. Both calls need a token with the `events:read` scope; webhook scopes are not enough.

```bash
curl "https://app.relvoerp.com/api/v1/public/events?type=invoice.paid&delivery_success=false" \
  -H "Authorization: Bearer rk_live_xxxxxxxxxxxxxxxxxxxx"
```

| Query parameter | Meaning |
|---|---|
| `type` | Event type. Repeat it to match several. |
| `created_at_from`, `created_at_to` | Inclusive RFC 3339 bounds on `created_at`. |
| `delivery_success` | `true`: every webhook delivery of the event succeeded. `false`: at least one delivery has not succeeded yet or failed. Events no endpoint subscribed to match neither. |
| `limit`, `cursor` | Pass `next_cursor` back as `cursor`, with the same filters. |

Results are newest first. Each item is the delivery body plus `created_at`. `GET /api/v1/public/events/{event_id}` fetches one event by its `Relvo-Event-Id`. It returns `404 event_not_found` for an unknown id or an event older than 30 days.

## Verifying delivery signatures

Every event delivery is a `POST` carrying these headers (the verification handshake carries the same signature headers, without the two id headers):

| Header | Value |
|---|---|
| `Relvo-Signature` | `v1=<hex>` — lowercase hex HMAC-SHA256, 64 characters |
| `Relvo-Timestamp` | Unix seconds at which this attempt was signed |
| `Relvo-Event-Id` | The event's id; stable across retries and redeliveries, so use it to deduplicate |
| `Relvo-Delivery-Id` | This delivery's id |
| `Relvo-Webhook-Version` | `v1` |

To verify:

1. Read the **raw request body bytes** before any JSON parsing. Re-serializing the parsed JSON changes the bytes and breaks the signature.
2. Build the signed message: `<Relvo-Timestamp>` + `.` + `<raw body>`.
3. Compute `HMAC-SHA256(key, message)` and hex-encode it. The key is the `signing_secret` string exactly as returned at creation, as UTF-8 bytes: there is no prefix to strip and nothing to base64-decode.
4. Split `Relvo-Signature` on `,` and accept the request if any entry equals `v1=<your hex>` under a constant-time comparison. There is usually one value. There are several during a [secret rotation](https://app.relvoerp.com/docs/product/guides/webhooks.md#rotating-the-signing-secret).
5. Reject deliveries whose `Relvo-Timestamp` is more than 5 minutes from your clock, to block replays.

This is **not** the Svix / Standard Webhooks scheme, even though the header names look similar: there is no `webhook-id` in the signed message, the key is not base64, and the signature is hex, not base64.

```ts
import { createHmac, timingSafeEqual } from "node:crypto";

function isValidRelvoSignature(rawBody: Buffer, headers: Headers, secret: string): boolean {
  const timestamp = headers.get("Relvo-Timestamp") ?? "";
  const received = (headers.get("Relvo-Signature") ?? "").split(",").map((s) => s.trim());
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const expected = Buffer.from(
    "v1=" + createHmac("sha256", secret).update(`${timestamp}.`).update(rawBody).digest("hex"),
  );
  // During a secret rotation the header carries one `v1=` per active secret.
  return received.some(
    (candidate) => candidate.length === expected.length && timingSafeEqual(Buffer.from(candidate), expected),
  );
}
```

**Test vector.** Check your implementation against this before you go live (skip the timestamp freshness check for this test):

| Input | Value |
|---|---|
| `signing_secret` | `Zm9vYmFyLWV4YW1wbGUtc2VjcmV0LW5vdC1yZWFs` |
| `Relvo-Timestamp` | `1767225600` |
| Raw body | `{"id":"evt_example","type":"invoice.issued"}` |
| Expected `Relvo-Signature` | `v1=5e60c0036e884bf3a74b9bac82b6566017a74fb482c5b6bdf255938d6f718ed0` |

The verification handshake is signed with the same scheme, so a handler that checks signatures on every request exercises its signature code during verification. A handler that skips the check for `relvo.webhook.verify` does not, and can still become `active` while rejecting every real delivery — run the test vector first.

## Responses, retries and failed deliveries

| Your response | What Relvo does |
|---|---|
| `2xx` | Delivered. |
| `408`, `429`, `5xx`, timeout or connection error | Retried with backoff (at least 5 seconds, at most 6 hours apart), up to 12 attempts in total. `Retry-After` is honoured within the same bounds. |
| Any other status, including `401`/`403` | Failed permanently on that attempt. Not retried. |

A delivery that fails permanently (`dead`) is kept, not discarded. List deliveries with `GET /{id}/deliveries`. You can filter by `status`, `event_type`, `created_from` and `created_to`, and repeat `status` or `event_type` to match several values. Once your endpoint is fixed, call `POST /{id}/deliveries/{delivery_id}/redeliver` with an `Idempotency-Key` on a `delivered`, `dead` or `cancelled` delivery. It resends the frozen body unchanged, with the same event `id`. A redelivery is one attempt: if your endpoint fails it again, it is not retried, so fix the endpoint before asking. Relvo does not disable an endpoint because its deliveries fail, so a misconfigured endpoint keeps failing until it is fixed. Events published while an endpoint is disabled are never queued for it.

## Managing subscriptions

Update which event types an endpoint receives without recreating it:

```
PUT /api/v1/public/webhook-endpoints/{id}/subscriptions
Authorization: Bearer rk_live_xxxxxxxxxxxxxxxxxxxx
If-Match: W/"3"
Content-Type: application/json

{
  "subscriptions": [
    { "event_type": "invoice.issued", "schema_version": 1 },
    { "event_type": "credit_note.issued", "schema_version": 1 }
  ]
}
```

This replaces the full subscription list — include every event type you still want, not just the ones you're adding. Only the pairs listed in [Events](https://app.relvoerp.com/docs/product/guides/webhooks.md#events) are accepted; anything else, and any pair listed twice, is rejected with `422 validation_webhook_subscriptions`. The response is `200` with the endpoint. Replacing works in every status except `deleted` (`409 webhooks_endpoint_state_conflict`).

## Disabling and deleting

- `POST /{id}/disable` pauses an `active` or `pending_verification` endpoint and cancels its queued deliveries.
- `POST /{id}/enable` resumes a `disabled` endpoint. If its URL was already verified, it goes back to `active`. Otherwise it goes back to `pending_verification` with a fresh challenge. Deliveries cancelled while it was disabled are not revived, so redeliver any you need.
- `DELETE /public/webhook-endpoints/{id}` with `If-Match` deletes an endpoint from any status and cancels its queued deliveries. Retrying the same `DELETE` returns `204` again. The URL can then be registered again as a new endpoint, with a new ID and secret.
- Disabled and deleted endpoints stop receiving deliveries immediately. `/verify` on them returns `409 webhooks_endpoint_state_conflict`.

## Rotating the signing secret

```bash
curl -X POST "https://app.relvoerp.com/api/v1/public/webhook-endpoints/{id}/rotate-secret" \
  -H "Authorization: Bearer rk_live_xxxxxxxxxxxxxxxxxxxx" \
  -H "Idempotency-Key: $(uuidgen)" \
  -H 'If-Match: W/"4"'
```

The response is `200` with the endpoint and a new `signing_secret`. The secret is shown only in this response, and an idempotent replay returns `null`. For the next **24 hours**, every delivery is signed with both the new and the previous secret, so `Relvo-Signature` carries two comma-separated values, such as `v1=<new>,v1=<old>`. Their order is not guaranteed. Your receiver accepts the request when any value matches a secret it holds. Deploy the new secret within those 24 hours, then remove the old one. Retries of deliveries created before the rotation are signed with the new secret as well, so a receiver that has already switched still verifies them.
