# Guide to sajn Webhooks: Features and Best Practices

[sajn](https://sajn.se) is a Swedish platform for e-signatures and identity checks. Its webhooks report what happens in a workspace: a document is sent, a party signs or an invitation bounces, the signed PDF is sealed, an identity check passes or fails, a public form is submitted. The event list is long, covering contacts, templates, members and security events as well.

The most important thing to get right with sajn is the endpoint's API version, because it decides both the body and the signing scheme. This guide starts there and then covers events, setup, verification and delivery.

## What are sajn webhooks?

sajn webhooks are endpoints registered on a workspace, or on every workspace of an organisation, that receive JSON `POST` requests for the events they subscribe to. They come with API access, which needs the Team plan or higher; sandbox organisations always have it. The [webhooks overview](https://docs.sajn.se/webhooks/overview) describes them in full.

Each endpoint is pinned to an API version, sent in the `Sajn-Version` header and the body's `apiVersion`. On version `2026-10`, deliveries follow Standard Webhooks and the body is `{ id, type, createdAt, apiVersion, workspaceId, environment, actor, data }`. The deprecated `2026-09` version, supported until 1 October 2027, sends a different body with uppercase event names and signs with an `X-Sajn-Signature` header instead.

## sajn webhook features

| Feature | Details |
| --- | --- |
| Signature | Standard Webhooks HMAC-SHA256 |
| Signature header | `webhook-signature` |
| Body | JSON |
| Event routing | Body field `type` |
| Availability | Team plan or higher; always in sandbox organisations |
| Scope | One workspace, or every workspace in the organisation |
| API version | Per endpoint; `2026-10` for Standard Webhooks |
| Secret | `whsec_`, returned on create and rotation only; 24-hour overlap on rotation |
| Timeout | 30 seconds |
| Retries | Up to 12 attempts over about three days |
| Pausing | On `410`, or after 72 hours of failures with at least 5 in a row |
| History | Delivery log 7 days; `GET /api/v1/events` 30 days |
| Guarantees | At least once, unordered |

## Events and payloads

The events most integrations start with:

| Event | Triggered When | Common Use Cases |
| --- | --- | --- |
| `document.sent` | The document is sent to its parties | Track outstanding agreements |
| `document.fully_signed` | Every party has signed. The PDF is **not sealed yet** | Update deal status |
| `document.completed` | sajn sealed the signed PDF | Download and archive the signed file |
| `document.rejected` | A party rejects the document, ending signing | Notify the owner |
| `document.expired` / `document.expiring_soon` | A pending document passed its expiration date / expires in about a day | Chase signers |
| `document.withdrawn` | The sender withdraws a sent document (back to `DRAFT`) | Cancel follow-ups |
| `document.party.signed` | A party signs (`data.party` is the party) | Show signing progress |
| `document.party.rejected` | A party rejects the document | Notify the owner |
| `document.party.delivery_failed` | A party's invitation email bounces or SMS fails | Correct contact details |
| `approval_request.created` / `.approved` / `.rejected` / `.cancelled` | Internal approval of a document moves | Approval workflows |
| `identity_check.verified` / `identity_check.failed` | An identity check completes / fails (`data.failureReason`) | Onboarding, KYC |
| `form.submitted` | A respondent submits a public form | Create leads or records |
| `usage.limit_reached` | The organisation reaches a monthly document or eID signature quota | Alert the account owner |
| `webhook.test` | Sent only by `POST /api/v1/webhooks/{id}/test`; can't be subscribed to | Connectivity check |

The full list on `2026-10`:

* **Document (15):** `document.created`, `document.sent`, `document.fully_signed`, `document.completed`, `document.rejected`, `document.expired`, `document.expiring_soon`, `document.expiration_extended`, `document.withdrawn`, `document.updated`, `document.deleted`, `document.restored`, `document.archived`, `document.unarchived`, `document.comment.created`
* **Party (13):** `document.party.sent`, `document.party.delivery_failed`, `document.party.opened`, `document.party.read`, `document.party.verified`, `document.party.auth_failed`, `document.party.signed`, `document.party.rejected`, `document.party.delegated`, `document.party.updated`, `document.party.added`, `document.party.removed`, `document.party.reminded`
* **Approval (4):** `approval_request.created`, `approval_request.approved`, `approval_request.rejected`, `approval_request.cancelled`
* **Identity check (6):** `identity_check.created`, `identity_check.sent`, `identity_check.opened`, `identity_check.verified`, `identity_check.failed`, `identity_check.cancelled`
* **Contact and company (6):** `contact.created`, `contact.updated`, `contact.deleted`, `company.created`, `company.updated`, `company.deleted`
* **Template and form (5):** `template.created`, `template.updated`, `template.deleted`, `template.restored`, `form.submitted`
* **Workspace and usage (5):** `workspace.created`, `member.invited`, `member.invite_accepted`, `member.added`, `usage.limit_reached`
* **Security (7):** `security.document_downloaded`, `security.documents_exported`, `security.signature_identity_accessed`, `security.member_removed`, `security.member_role_changed`, `security.role_updated`, `security.workspace_retention_updated`
* **sajn Login (2):** `login.completed`, `login.failed`
* **Test (1):** `webhook.test`

[Webhook events](https://docs.sajn.se/webhooks/events) and the per-event pages under [API reference > Webhook events](https://docs.sajn.se/api-reference/webhook-events/documentcompleted) are the authoritative source.

A `2026-10` body, with `data.object` shortened as in sajn's own example:

```json
{
  "id": "cm4k2x9p10014abcd1234efgh",
  "type": "document.completed",
  "createdAt": "2026-10-01T09:30:00.000Z",
  "apiVersion": "2026-10",
  "workspaceId": "cm4k2x9p10001abcd1234efgh",
  "environment": "PRODUCTION",
  "actor": null,
  "data": {
    "object": { "id": "cm4k2x9p10003abcd1234efgh", "status": "COMPLETED" }
  }
}

```

| Field | Notes |
| --- | --- |
| `id` | Event ID, the same on every retry, replay and endpoint. Dedupe on it. Equals `webhook-id` |
| `type` | Dotted lowercase event name, e.g. `document.party.signed` |
| `createdAt` | When the event happened (not when the attempt was sent). Doesn't change across retries |
| `apiVersion` | The endpoint's API version. It sets the shape of `data` |
| `workspaceId` / `environment` | Source workspace; `SANDBOX` or `PRODUCTION` |
| `actor` | `{ type, id }` (`USER`, `API_KEY`, `OAUTH_APP`, `SYSTEM`) or `null` |
| `data.object` | The resource, as the REST API returns it. Some events add `data.party`, `data.previousAttributes`, `data.source` and similar |

`data.object` is a snapshot from when the event happened, not the current state.

## Setting up sajn webhooks

You need the **Hantera webhooks** (Manage webhooks) permission or an API key, and a public HTTPS URL. Create the sajn webhook endpoint on API version 2026-10 or later. Endpoints on the deprecated 2026-09 version sign with X-Sajn-Signature instead of Standard Webhooks and fail verification.

**In the dashboard:**

1. Open **Inställningar > Utvecklare > Webhooks** at [app.sajn.se](https://app.sajn.se) and click **Skapa webhook**.
2. Enter the **Webhook URL**, for example `https://your-app.com/webhooks/sajn`.
3. Choose **Händelser** (events), such as `document.completed`, `document.party.signed` and `document.party.delivery_failed`.
4. Set **API-version** to `2026-10` or later, and leave **Hemlighet** (secret) empty so sajn generates one.
5. Organisation administrators can pick **Alla arbetsytor** to cover every workspace.
6. Click **Skapa webhook** and copy the secret.

Before saving, sajn sends an unsigned `POST` with the body `{"test": true}` and user agent `sajn-webhook-validator/1.0`. The save fails if the URL takes longer than 5 seconds, redirects, returns `404` or returns a `2xx` HTML page. A `400` from your signature check is fine.

**Through the API:**

```bash
curl -X POST https://app.sajn.se/api/v1/webhooks \
  -H "Authorization: Bearer $SAJN_API_KEY" \
  -H "Sajn-Version: 2026-10" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/webhooks/sajn",
    "events": ["document.completed", "document.party.signed"],
    "apiVersion": "2026-10"
  }'

```

The response's `secret` is the only time you see it outside a rotation; store it as `SAJN_WEBHOOK_SECRET`. `events` is required and replaced in full on `PATCH`. Optional fields are `enabled`, `failureNotificationEmail` (notified if sajn pauses the endpoint) and a custom `secret` (`whsec_` plus base64 of 24 to 64 random bytes). `POST /api/v1/webhooks/{id}/test` sends a `webhook.test` event. For local testing, forward to your machine with the [Hookdeck CLI](/docs/cli):

```bash
npx hookdeck-cli listen 3000 sajn --path /webhooks/sajn

```

**With Hookdeck.** Create a **sajn** source, use its URL for the endpoint on API version `2026-10`, and paste the `whsec_` secret into it. Hookdeck accepts only `POST`, returns `200` to sajn, and keeps deliveries that fail verification out of your service while logging them. The unsigned dashboard probe will show up as one of those failures, which is expected. sajn describes that probe for dashboard saves, so if a save doesn't go through, create the endpoint through the API instead.

## Securing sajn webhooks

On `2026-10`, sajn signs `{webhook-id}.{webhook-timestamp}.{raw body}` with HMAC-SHA256, using the base64-decoded part of the secret after `whsec_`, and sends `v1,<base64>` values in `webhook-signature`. For 24 hours after a rotation the header holds two signatures, one per secret:

```javascript
const crypto = require('node:crypto');

function decodeBase64(value) {
  if (typeof value !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) return null;
  const bytes = Buffer.from(value, 'base64');
  return bytes.length > 0 && bytes.toString('base64').replace(/=+$/, '') === value.replace(/=+$/, '')
    ? bytes : null;
}

function verifySignature(rawBody, headers, secret) {
  if (!Buffer.isBuffer(rawBody) || typeof secret !== 'string' || !secret) return false;
  const prefix = headers['webhook-id'] !== undefined ? 'webhook' : 'svix';
  const id = headers[`${prefix}-id`];
  const timestamp = headers[`${prefix}-timestamp`];
  const signature = headers[`${prefix}-signature`];
  if (typeof id !== 'string' || !id || typeof timestamp !== 'string' ||
      !/^[0-9]+$/.test(timestamp) || typeof signature !== 'string') return false;
  const key = decodeBase64(secret.replace(/^whsec_/, ''));
  if (!key) return false;
  const message = Buffer.concat([Buffer.from(`${id}.${timestamp}.`, 'utf8'), rawBody]);
  const candidates = signature.split(/\s+/).filter((item) => item.startsWith('v1,')).map((item) => item.slice(3));
  const expected = crypto.createHmac('sha256', key).update(message).digest();
  return candidates.some((candidate) => {
    const received = decodeBase64(candidate);
    if (!received) return false;
    return received.length === expected.length && crypto.timingSafeEqual(received, expected);
  });
}

```

A handler that archives signed documents and flags bounced invitations:

```javascript
const express = require('express');

// Returns the parsed body when it is a JSON object, otherwise null.
function parseJsonObject(rawBody) {
  try {
    const value = JSON.parse(rawBody.toString('utf8'));
    return value && typeof value === 'object' && !Array.isArray(value) ? value : null;
  } catch {
    return null;
  }
}

const app = express();

app.post('/webhooks/sajn', express.raw({ type: '*/*' }), async (req, res) => {
  const secret = process.env.SAJN_WEBHOOK_SECRET;
  if (!secret) return res.sendStatus(500);
  if (!verifySignature(req.body, req.headers, secret)) return res.sendStatus(400);

  const event = parseJsonObject(req.body);
  if (!event) return res.sendStatus(400); // signed, but not a JSON object
  if (typeof event.type !== 'string' || !event.data || typeof event.data !== 'object') return res.sendStatus(400);
  if (event.environment !== process.env.SAJN_ENVIRONMENT) return res.sendStatus(200);

  const document = event.data.object;
  const needs_document = event.type === 'document.completed' || event.type === 'document.party.signed';
  if (needs_document && (!document || typeof document !== 'object')) return res.sendStatus(400);

  try {
    if (event.type === 'document.completed') {
      await archive.downloadSignedPdf(event.id, document.id);
    } else if (event.type === 'document.party.delivery_failed') {
      await contacts.flagBounce(event.id, event.data.party);
    } else if (event.type === 'document.party.signed') {
      await progress.record(event.id, document.id, event.data.party, event.createdAt);
    }
  } catch {
    return res.sendStatus(503); // not processed, so don't acknowledge
  }
  return res.sendStatus(200);
});

```

`archive`, `contacts` and `progress` are your own modules. Returning `400` on a bad signature lets the unsigned dashboard probe pass. `SAJN_ENVIRONMENT` is `SANDBOX` or `PRODUCTION`.

sajn's verification steps include rejecting timestamps more than five minutes from your clock, in either direction, and the Standard Webhooks libraries do the same by default. Hookdeck has no timestamp window and reuses sajn's original `webhook-timestamp` on retries and replays, so services behind it should verify without the age check.

> **Make sajn webhooks production-ready.** [Hookdeck Event Gateway](/event-gateway) keeps every signing event beyond sajn's 7-day delivery log and stops a slow receiver from getting your endpoint paused.

## sajn webhook limitations and pain points

### The API version changes the signature

**The Problem:** Every delivery fails Standard Webhooks verification.

**Why It Happens:** Endpoints on `2026-09` sign with `X-Sajn-Signature` (`t=<unix>,v1=<hex>` over `<t>.<raw body>` with the secret as text), send the secret itself in `X-Sajn-Secret`, and use a `{ event, payload }` body. An endpoint created without an explicit version gets the organisation's default, which may still be `2026-09`.

**Workarounds:**

* Always pass `"apiVersion": "2026-10"` or pick it in the form.
* To migrate, update your handler for the new body, `PATCH /api/v1/webhooks/{id}` with `{"apiVersion": "2026-10"}`, then rotate the secret to get a `whsec_` value.

**How Hookdeck Can Help:** Hookdeck's request log shows the headers on each delivery, so an endpoint still on `2026-09` is obvious.

### `fully_signed` isn't the end

**The Problem:** You download the PDF on `document.fully_signed` and get an unsealed file.

**Why It Happens:** sajn seals the PDF after everyone signs and reports that with `document.completed`.

**Workarounds:**

* Download the signed file on `document.completed` only.

**How Hookdeck Can Help:** A [filter](/docs/filters) can send only `document.completed` to your archiving service.

### Unordered delivery

**The Problem:** `document.party.signed` arrives after `document.completed` and moves a document backwards.

**Why It Happens:** Delivery is at least once and unordered.

**Workarounds:**

* Compare `createdAt` before overwriting state, or read current state from the API.

**How Hookdeck Can Help:** [Deduplication](/docs/deduplication) on the event `id` removes repeats; ordering still belongs in your code.

### Pausing and short history

**The Problem:** After a long outage the endpoint is paused and some events are gone.

**Why It Happens:** sajn pauses an endpoint on `410`, or after 72 hours of failures with at least 5 in a row. Reactivating doesn't resend missed events. The delivery log keeps 7 days and `GET /api/v1/events` 30 days.

**Workarounds:**

* Set `failureNotificationEmail`, retry from the delivery log within 7 days, or rebuild from `GET /api/v1/events` within 30.

**How Hookdeck Can Help:** Hookdeck always answers `200`, so the sajn endpoint isn't paused while your service recovers.

## Best practices

### Keep one secret per endpoint and environment

Sandbox and production endpoints have different secrets. Route by URL, or check `environment` when both share one.

### Rotate with the 24-hour overlap

`POST /api/v1/webhooks/{id}/rotate-secret` returns the new secret, and both sign for 24 hours. Deploy the new one within that window.

### Deduplicate on `id`

The event `id` equals `webhook-id` and is stable across retries, replays and even endpoints. Our [idempotency guide](/webhooks/guides/implement-webhook-idempotency) shows how to record it with the resulting change.

### Answer within 30 seconds

Queue slow work such as PDF downloads. `429` responses are honoured with `Retry-After` (60 seconds by default), and redirects are never followed.

## Conclusion

sajn's webhooks follow a document from sending through signing to the sealed PDF, along with identity checks, forms and account activity. Create endpoints on API version `2026-10`, download files on `document.completed`, order by `createdAt`, and plan for a 7-day delivery log.

[Hookdeck Event Gateway](https://hookdeck.com) keeps your endpoint active and every event replayable. [Create an account](https://dashboard.hookdeck.com/signup) and register a sajn source on API version `2026-10`.