# Webhooks

> Have Sofia Space send task, time and page events to your own system (an ERP, CRM or KPI tool) — setting one up in Settings → Integrations, the events and their payload, verifying the signature in Node.js, Python and PHP, retries, ordering and a KPI recipe.

Source: https://docs.sofiaspace.uz/integrations/webhooks/

A **webhook** makes Sofia Space call your system the moment something happens — a task is created, moves to **Done**, gets a comment, or someone logs time. Your system no longer has to ask the API every few minutes what changed. Each call carries a full copy of the task as it was at that moment, so the receiver usually doesn't need to call back.

**Who can do this:** Org Admins. **Where:** **Settings → Integrations → Webhooks**. Every plan includes webhooks.

## What a webhook is tied to

Every webhook belongs to an [integration account](https://docs.sofiaspace.uz/integrations/integration-accounts.md), the workspace member that stands for your system.

- **It only sends what that account can see.** Events from a project are sent only if the account is a member of that project (or the project is open to the whole workspace). Pages follow the same rule. A webhook can't leak a restricted project or page. To receive a project's events, add the account to the project.
- **You choose the events.** Tick only the ones your system needs.
- **You can limit it to some projects.** With no projects chosen, it sends events from every project the account can see.
- A workspace can have up to 25 webhooks.

## Add a webhook

1. Go to **Settings → Integrations**. If your system has no integration account yet, [create one](https://docs.sofiaspace.uz/integrations/integration-accounts.md#create-an-integration-account) and add it to the projects it should hear about.
2. In **Webhooks**, choose **Add webhook**.
3. Enter the **URL** your system listens on. It must start with `https://`.
4. Pick the **integration account** the webhook belongs to.
5. Tick the **events** to send (see [Events](#events)).
6. Optionally choose **projects**. Leave it empty for all projects the account can see.
7. Optionally add a **description**, such as "1C — task completion for payroll".
8. Save. **Copy the signing secret now** (it starts with `whsec_`) and store it in your system. You won't see it again; if you lose it, [rotate it](#rotate-the-secret).
9. Choose **Send test event** to check your endpoint answers (see [Test and redeliver](#test-and-redeliver)).

You can change the URL, account, events, projects and description later, switch a webhook off and on, or delete it.

### Rules for the URL

- It must be `https://`.
- It must resolve to a **public internet address**. Addresses on private networks (`10.x`, `192.168.x`, `localhost` and so on) are refused, so Sofia Space can't be turned against internal networks.
- **Redirects aren't followed.** A `301` or `302` counts as a failed delivery; give the final URL.

On a [self-hosted installation](https://docs.sofiaspace.uz/reference/self-hosting.md) the administrator can allow internal addresses, because there the ERP often sits on the same network.

## Events

| Event | Sent when |
| --- | --- |
| `task.created` | A task is created. |
| `task.updated` | A field changes: title, description, priority, assignee, story points, dates, type, team, component, parent, epic, sprint, archived, or a custom field. `changes` lists what changed. |
| `task.status_changed` | The task moves to another status. |
| `task.completed` | The task moves into a done status (sent as well as `task.status_changed`). |
| `task.reopened` | The task moves out of a done status (sent as well as `task.status_changed`). |
| `task.deleted` | The task is deleted. |
| `task.commented` | Someone comments on the task. |
| `worklog.created` | Someone logs time on a task, by hand or with the timer. |
| `worklog.updated` | A worklog is changed. |
| `worklog.deleted` | A worklog is deleted. |
| `page.published` | A Docs page is published. |
| `ping` | You chose **Send test event**. Always sent, whatever events are ticked. |

Some changes send no event:

- **Imports.** Tasks and pages brought in by a Jira, Confluence or other import don't send `task.created` or `page.published`, so an import can't flood your endpoint. To load that history, read it once through the API.
- **Restricted pages.** A page whose access is narrowed below its space (a view restriction on it or on a page above it) is never sent to any webhook. The integration account sees pages only through its role on the space.
- **One transaction, one event per kind.** If a single save changes the title and the due date, you get one `task.updated` listing both. If it moves a task into Done, you get `task.status_changed` and then `task.completed`, both with the task as it was after the save.

## What your endpoint receives

Each event is a `POST` with a JSON body, `Content-Type: application/json` and `User-Agent: SofiaSpace-Webhooks/1`, plus these headers:

| Header | Value |
| --- | --- |
| `X-Sofia-Event` | The event type, such as `task.completed`. |
| `X-Sofia-Delivery` | The event's ID. The same on every retry and redelivery of this event — use it to [skip duplicates](#duplicates). |
| `X-Sofia-Signature` | `t=<unix seconds>,v1=<signature>` — see [Verify the signature](#verify-the-signature). |

### The envelope

Every body has the same outer shape:

| Field | Meaning |
| --- | --- |
| `id` | The event's ID, the same as `X-Sofia-Delivery`. |
| `type` | The event type. |
| `occurredAt` | When it happened, in UTC. |
| `orgId` | The workspace's ID. |
| `actor` | Who did it: `id`, `name` and `kind` — `USER` (a person), `INTEGRATION` (an integration account) or `SYSTEM`. `null` when Sofia Space did it itself. |
| `data` | The event's content. For `task.*` events, a full snapshot of the task (below). |
| `changes` | What changed, for `task.updated`, `task.status_changed`, `task.completed` and `task.reopened`; otherwise `null`. |

### Example: `task.completed`

```json
{
  "id": "7d3c2a91-5e4f-4b8a-9c1d-2e3f4a5b6c7d",
  "type": "task.completed",
  "occurredAt": "2026-11-25T09:14:03.120Z",
  "orgId": "3f1a9c27-8b4d-4e6f-a2c1-5d7e9f0b1a23",
  "actor": { "id": "8e4d2b19-6c7a-4f3e-b1d0-3a5c9e8f7d62", "name": "Dilnoza Karimova", "kind": "USER" },
  "data": {
    "id": "7c3e9a15-2d4f-4b6a-9e8c-1f3a5b7d9e20",
    "key": "SUP-12",
    "number": 12,
    "projectId": "9d2e7a10-4b6c-4e8f-a1d3-5c7e9b2f4a68",
    "projectKey": "SUP",
    "title": "Printer in the Samarkand office doesn't connect",
    "type": { "id": "1a3c5e7f-9b2d-4f6a-8c1e-3d5f7a9b2c4e", "name": "Task" },
    "status": { "id": "5a2b3c4d-6e7f-4a81-9b0c-1d2e3f4a5b61", "name": "Done", "category": "DONE" },
    "priority": "MEDIUM",
    "assignee": { "id": "8e4d2b19-6c7a-4f3e-b1d0-3a5c9e8f7d62", "name": "Dilnoza Karimova", "email": "dilnoza.karimova@example.uz" },
    "reporter": { "id": "2c9a7f41-5b3e-4d1a-8f20-7e6b5c4d3a21", "name": "Ali Valiyev", "email": "ali.valiyev@example.uz" },
    "storyPoints": 3,
    "startDate": "2026-11-20",
    "dueDate": "2026-11-28",
    "createdAt": "2026-11-19T11:02:45.310Z",
    "updatedAt": "2026-11-25T09:14:03.120Z",
    "startedAt": "2026-11-20T08:31:12.004Z",
    "completedAt": "2026-11-25T09:14:03.120Z",
    "parentId": null,
    "epicId": null,
    "sprintId": null,
    "archived": false,
    "deletedAt": null,
    "customFields": [
      { "id": "f1e2d3c4-b5a6-4978-8a9b-0c1d2e3f4a5b", "name": "Branch", "type": "TEXT", "value": "Samarkand" }
    ],
    "externalRefs": [
      { "system": "1c", "externalId": "ORD-2026-0815", "url": "https://erp.example.uz/orders/0815", "label": "Order 0815" }
    ]
  },
  "changes": {
    "status": {
      "old": { "id": "0b1c2d3e-4f5a-4b6c-8d7e-9f0a1b2c3d4e", "name": "In review", "category": "IN_PROGRESS" },
      "new": { "id": "5a2b3c4d-6e7f-4a81-9b0c-1d2e3f4a5b61", "name": "Done", "category": "DONE" }
    }
  }
}
```

### The task snapshot

`data` for every `task.*` event, and `data.task` for `task.commented` and `worklog.*`, is the task as it was when the event happened:

| Field | Meaning |
| --- | --- |
| `id`, `key`, `number` | The task's ID and key, such as `SUP-12` |
| `projectId`, `projectKey` | Its project |
| `title`, `priority` | Title; `HIGHEST`, `HIGH`, `MEDIUM`, `LOW` or `LOWEST` |
| `type` | `id` and `name` |
| `status` | `id`, `name` and `category`: `TODO`, `IN_PROGRESS` or `DONE` |
| `assignee`, `reporter` | `id`, `name` and `email`, or `null` |
| `storyPoints` | A number or `null` |
| `startDate`, `dueDate` | `yyyy-MM-dd` or `null` |
| `createdAt`, `updatedAt` | Times in UTC |
| `startedAt` | When the task first left a to-do status; `null` if it never has |
| `completedAt` | When it last moved into a done status; cleared when it's reopened |
| `parentId`, `epicId`, `sprintId` | Or `null` |
| `archived` | `true` or `false` |
| `deletedAt` | Set on `task.deleted`, otherwise `null` |
| `customFields` | Each field's `id`, `name`, `type` and `value` |
| `externalRefs` | [Linked records](https://docs.sofiaspace.uz/integrations/integration-accounts.md#linked-records-on-a-task): `system`, `externalId`, `url`, `label` |

### `changes`

- **`task.updated`** — one entry per changed field, with its `old` and `new` value. The fields are `title`, `description`, `priority`, `assigneeId`, `storyPoints`, `startDate`, `dueDate`, `typeId`, `teamId`, `componentId`, `parentId`, `epicId`, `sprintId`, `archived`, and `customFields.<fieldId>` for a custom field. For `description` the values are left out (`{}`); read the new text from the task if you need it.

  ```json
  "changes": {
    "assigneeId": { "old": null, "new": "8e4d2b19-6c7a-4f3e-b1d0-3a5c9e8f7d62" },
    "dueDate": { "old": "2026-11-26", "new": "2026-11-28" },
    "description": {}
  }
  ```

- **`task.status_changed`**, **`task.completed`**, **`task.reopened`** — `changes.status` with the `old` and `new` status, each with `id`, `name` and `category` (as in the example above).

### Other events

| Event | `data` |
| --- | --- |
| `task.commented` | `comment` (`id`, `body` as plain text, `authorId`, `createdAt`) and `task` (the snapshot) |
| `worklog.created`, `.updated`, `.deleted` | `worklog` (`id`, `taskId`, `userId`, `user` with `id`, `name`, `email`, `startedAt`, `minutes`, `description`, `source`: `MANUAL` or `TIMER`) and `task` (the snapshot) |
| `page.published` | `page`: `id`, `title`, `spaceId`, `spaceKey`, `parentId`, `kind` (`RICH_TEXT` or `HTML`), `locale` (`null` for the original, else the translation's language), `version`, `publishedAt`, `authorId`, and `url` — the page's path in the app, such as `/docs/HR/3f2a…`; put your workspace address in front of it |
| `ping` | `message` (`"Test event from Sofia Space"`) and `webhookId` |

## Verify the signature

Anyone can send a `POST` to your URL. Check that each one really comes from Sofia Space before you act on it:

1. Read `X-Sofia-Signature`: a `t=` part (Unix time in seconds) and one or more `v1=` parts.
2. Compute HMAC-SHA256 with the **whole signing secret** (including `whsec_`, as text — don't decode it) as the key, over `t`, a dot, and the **raw request body**: `t + "." + body`. Write it as lower-case hex.
3. Accept the request if it equals **any** `v1` value, comparing in constant time.
4. Refuse it if `t` is more than **5 minutes** away from your clock, so an old request can't be replayed.

:::caution[Use the raw body]
Sign the bytes exactly as they arrived. If your framework has already parsed the JSON, serializing it again changes spacing or key order and the signature won't match.
:::

### Node.js (Express)

```js
import crypto from 'node:crypto';
import express from 'express';

const SECRET = process.env.SOFIA_WEBHOOK_SECRET; // whsec_...
const TOLERANCE_SECONDS = 5 * 60;

function verifySofiaSignature(rawBody, header, secret) {
  if (!header) return false;
  let timestamp = null;
  const signatures = [];
  for (const part of header.split(',')) {
    const [key, value] = part.trim().split('=', 2);
    if (key === 't') timestamp = value;
    else if (key === 'v1') signatures.push(value);
  }
  if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0) return false;
  if (Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false;

  const expected = crypto.createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest();
  return signatures.some((sig) => {
    const given = Buffer.from(sig, 'hex');
    return given.length === expected.length && crypto.timingSafeEqual(given, expected);
  });
}

const app = express();

// express.raw keeps the body as a Buffer, exactly as it was sent.
app.post('/sofia/webhook', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifySofiaSignature(req.body, req.get('X-Sofia-Signature'), SECRET)) {
    return res.status(400).send('bad signature');
  }
  const event = JSON.parse(req.body.toString('utf8'));
  res.status(200).send('ok'); // answer first, then do the work
  handleEvent(event);         // your code; skip it if you've seen event.id before
});

app.listen(3000);
```

### Python (Flask)

```python
import hashlib
import hmac
import json
import os
import time

from flask import Flask, abort, request

SECRET = os.environ["SOFIA_WEBHOOK_SECRET"]  # whsec_...
TOLERANCE_SECONDS = 5 * 60

app = Flask(__name__)


def verify_sofia_signature(raw_body: bytes, header: str | None, secret: str) -> bool:
    if not header:
        return False
    timestamp, signatures = None, []
    for part in header.split(","):
        key, _, value = part.strip().partition("=")
        if key == "t":
            timestamp = value
        elif key == "v1":
            signatures.append(value)
    if not timestamp or not timestamp.isdigit() or not signatures:
        return False
    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(
        secret.encode("utf-8"), timestamp.encode("ascii") + b"." + raw_body, hashlib.sha256
    ).hexdigest()
    return any(hmac.compare_digest(expected, sig) for sig in signatures)


@app.post("/sofia/webhook")
def sofia_webhook():
    raw_body = request.get_data()  # the raw bytes, not request.json
    if not verify_sofia_signature(raw_body, request.headers.get("X-Sofia-Signature"), SECRET):
        abort(400)
    event = json.loads(raw_body)
    handle_event(event)  # your code: be quick, or queue it; skip it if you've seen event["id"]
    return "ok", 200
```

### PHP

```php
<?php
$secret = getenv('SOFIA_WEBHOOK_SECRET'); // whsec_...
$tolerance = 5 * 60;

function verify_sofia_signature(string $rawBody, ?string $header, string $secret, int $tolerance): bool
{
    if (!$header) {
        return false;
    }
    $timestamp = null;
    $signatures = [];
    foreach (explode(',', $header) as $part) {
        $pair = explode('=', trim($part), 2);
        if (count($pair) !== 2) {
            continue;
        }
        if ($pair[0] === 't') {
            $timestamp = $pair[1];
        } elseif ($pair[0] === 'v1') {
            $signatures[] = $pair[1];
        }
    }
    if ($timestamp === null || !ctype_digit($timestamp) || !$signatures) {
        return false;
    }
    if (abs(time() - (int) $timestamp) > $tolerance) {
        return false;
    }
    $expected = hash_hmac('sha256', $timestamp . '.' . $rawBody, $secret);
    foreach ($signatures as $signature) {
        if (hash_equals($expected, $signature)) {
            return true;
        }
    }
    return false;
}

$rawBody = file_get_contents('php://input'); // the raw body, not a re-encoded $_POST
if (!verify_sofia_signature($rawBody, $_SERVER['HTTP_X_SOFIA_SIGNATURE'] ?? null, $secret, $tolerance)) {
    http_response_code(400);
    exit('bad signature');
}
$event = json_decode($rawBody, true);
handle_event($event); // your code; skip it if you've seen $event['id']
http_response_code(200);
echo 'ok';
```

## Rotate the secret

Choose **Rotate secret** on the webhook to get a new signing secret, for example if the old one may have leaked or someone who knew it left. Copy it — it's shown once.

The **old secret keeps working for 24 hours**. During that time each request carries two signatures, `t=…,v1=<new>,v1=<old>`, so a receiver that accepts any matching `v1` keeps working while you update its secret. After 24 hours only the new one is sent.

## Delivery, retries and switching off

- **Success** is any `2xx` answer within **10 seconds**. Anything else — another status, a redirect, a timeout, a refused connection — is a failure. Answer quickly and do slow work afterwards.
- **Retries:** a failed delivery is tried again after **1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 24 hours** — eight attempts over about 45 hours. After the last one the delivery is marked **failed**; you can still [redeliver](#test-and-redeliver) it by hand.
- **Switched off after 3 days of failures:** if a webhook has had nothing but failures for 3 days, Sofia Space switches it off. Every Org Admin gets an in-app notice and an e-mail (even if they've turned e-mail off), linking to **Settings → Integrations**. Fix the endpoint, then switch the webhook back on; it continues with new events.

### Duplicates

Delivery is **at least once**: your system can receive the same event twice, for example when it handled a request but its answer was lost. Store the `X-Sofia-Delivery` value (the same as the body's `id`) and skip events you've already handled.

### Order isn't guaranteed

Events can arrive **out of order**: a retry of an older event can arrive after a newer one. Don't assume the last event you received is the latest state.

- Compare `occurredAt` with what you stored, and ignore an event older than the one you already applied for that task.
- Use the **snapshot** in `data` rather than replaying `changes` one after another. Each snapshot is complete on its own.

## Test and redeliver

The webhook's **recent deliveries** show each attempt's event, status, response code, how long it took, and the first 2 KB of your endpoint's answer — useful when something fails.

- **Send test event** sends a `ping` straight away and shows the result. It's signed like any other event.
- **Redeliver** sends a delivery again now, with the same event ID, so your duplicate check still recognises it.

## Recipe: KPIs from webhooks

A KPI or payroll system can keep its own numbers from events instead of reading reports:

1. Subscribe an integration account to `task.created`, `task.updated`, `task.completed`, `task.reopened` and `worklog.created`, `worklog.updated`, `worklog.deleted`, and add it to the projects that count.
2. Store each task's latest snapshot by task `id` (only if its `occurredAt` is newer than what you have), and each worklog by worklog `id` (delete it on `worklog.deleted`).
3. Compute, per person and period:
   - **Tasks assigned in the period** — `task.created` with that `assignee`, plus `task.updated` where `changes.assigneeId.new` is that person, with `occurredAt` in the period.
   - **Average completion time** — for tasks whose `completedAt` is in the period: `completedAt − startedAt`, or `completedAt − createdAt` if `startedAt` is empty (or if you count waiting time too).
   - **Hours on completed tasks** — the sum of `minutes` of stored worklogs whose task has a `completedAt` in the period, divided by 60.
4. A `task.reopened` clears `completedAt` in the snapshot, so a reopened task drops out until it's completed again.

**History from before the webhook:** fill your store once from the API. [List tasks](https://docs.sofiaspace.uz/api/tasks.md#list-tasks-in-a-project) with `doneFrom` and `doneTo` (for example `GET /api/v1/projects/{projectId}/tasks?doneFrom=2026-01-01&doneTo=2026-11-25`) returns finished tasks with `startedAt` and `completedAt`, and [Read a task's time](https://docs.sofiaspace.uz/api/time-tracking.md#read-a-tasks-time) returns its worklogs. If you only need the numbers, the ready-made [KPI report](https://docs.sofiaspace.uz/integrations/integration-accounts.md#the-kpi-report) has them too.

## What you can't do

- There are no sprint, project or member events yet.
- You can't choose the payload's fields or format; every event uses the envelope above.
- Webhooks can't be created or changed through the API or with a token; an Org Admin does it in **Settings → Integrations**.
- Redirects aren't followed, and on the cloud service the URL can't point to a private address.
- You can't see a signing secret again after it's shown; rotate it instead.

## Related

- [Integration accounts](https://docs.sofiaspace.uz/integrations/integration-accounts.md)
- [Integrations API](https://docs.sofiaspace.uz/api/integrations.md)
- [Tasks (API)](https://docs.sofiaspace.uz/api/tasks.md)
- [Rate limits](https://docs.sofiaspace.uz/api/rate-limits.md)
