# Receive Youniton webhooks

Build an endpoint that checks the signature, skips repeats and answers within 10 seconds.

1. **Get an endpoint registered**

   An Admin registers your HTTPS URL in **Administration › Automation › Webhooks**. Youniton checks the URL: it must be `https://` and must not resolve to a private, loopback, link-local or metadata address. Youniton does not follow redirects. The answer shows the secret, `whsec_…`, one time. Keep it in your secret store.

   Then a rule with the action "send webhook" or a help-desk connection with a webhook sends to it. The Admin can send a test delivery of type `kanseo.test`.

2. **Read the raw body**

   Verify the signature over the **raw bytes** of the body, before you parse the JSON. A parse and a new serialisation change the bytes.

3. **Verify the signature**

   The signed content is `{webhook-id}.{webhook-timestamp}.{body}`. The key is the secret after `whsec_`, base64-decoded. The header `webhook-signature` holds one or more `v1,<base64>` values, separated by spaces (two during a secret rotation). Accept the delivery when one value matches. Compare in constant time. Refuse a timestamp that is far from your clock, for example more than 5 minutes.

   *Verify a Youniton delivery*

   **Node**

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

   export function verifyYounitonWebhook(rawBody, headers, secret, toleranceSeconds = 300) {
     const id = headers["webhook-id"];
     const timestamp = headers["webhook-timestamp"];
     const signatures = (headers["webhook-signature"] || "").split(" ");
     if (!id || !timestamp) return false;
     if (Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSeconds) return false;

     const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
     const expected = createHmac("sha256", key).update(`${id}.${timestamp}.${rawBody}`).digest();
     return signatures.some((s) => {
       const [version, value] = s.split(",");
       if (version !== "v1" || !value) return false;
       const given = Buffer.from(value, "base64");
       return given.length === expected.length && timingSafeEqual(given, expected);
     });
   }

   // Express: app.post("/youniton/webhooks", express.raw({ type: "application/json" }), handler)
   // and call verifyYounitonWebhook(req.body.toString("utf8"), req.headers, process.env.YOUNITON_WEBHOOK_SECRET)
   ```

   **Python**

   ```python
   import base64, hashlib, hmac, time

   def verify_youniton_webhook(raw_body: bytes, headers, secret: str, tolerance: int = 300) -> bool:
       msg_id = headers.get("webhook-id")
       timestamp = headers.get("webhook-timestamp")
       signatures = headers.get("webhook-signature", "").split(" ")
       if not msg_id or not timestamp or abs(time.time() - int(timestamp)) > tolerance:
           return False
       key = base64.b64decode(secret.removeprefix("whsec_"))
       signed = f"{msg_id}.{timestamp}.".encode() + raw_body
       expected = base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()
       return any(
           s.startswith("v1,") and hmac.compare_digest(s[3:], expected)
           for s in signatures
       )
   ```

   **PHP**

   ```php
   <?php
   function verifyYounitonWebhook(string $rawBody, array $headers, string $secret, int $tolerance = 300): bool
   {
       $id = $headers['webhook-id'] ?? '';
       $timestamp = $headers['webhook-timestamp'] ?? '';
       $signatures = explode(' ', $headers['webhook-signature'] ?? '');
       if ($id === '' || $timestamp === '' || abs(time() - (int) $timestamp) > $tolerance) {
           return false;
       }
       $key = base64_decode(preg_replace('/^whsec_/', '', $secret));
       $expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$rawBody}", $key, true));
       foreach ($signatures as $signature) {
           [$version, $value] = array_pad(explode(',', $signature, 2), 2, '');
           if ($version === 'v1' && hash_equals($expected, $value)) {
               return true;
           }
       }
       return false;
   }
   // Laravel: verifyYounitonWebhook($request->getContent(), array_map(fn ($v) => $v[0], $request->headers->all()), config('services.youniton.webhook_secret'))
   ```

4. **Skip repeats**

   Store each `webhook-id` that you processed. The id stays the same over every retry and every redelivery, and a crash between Youniton's send and its record can repeat a delivery. When you see a known id, answer `200` and do nothing.

5. **Answer fast, then work**

   Answer a `2xx` within 10 seconds. Put slow work on your own queue. Another answer, a timeout or a network error makes Youniton retry: after 1 min, 5 min, 30 min, 2 h, 6 h, 12 h and 24 h. Answer `410 Gone` only when you want Youniton to disable the endpoint.

## Help-desk events

| Event | When |
|---|---|
| `request.created` | a request enters the connection's scope (never for the connection's own create) |
| `request.updated` | the client status or the progress changes, or the linked ticket changes as the client sees it |
| `request.message_posted` | a client-visible message; never an internal note |
| `request.decided` | a triage decision: accepted, merged or rejected |
| `request.closed` | the request closes without a decision: withdrawn, no response, or the client changed |

*Body of a help-desk event*

```json
{
  "id": "…",
  "type": "request.message_posted",
  "occurredAt": "2026-10-20T13:10:00Z",
  "tenantId": "…",
  "connection": { "id": "…", "name": "Orbit service desk" },
  "request": {
    "key": "ORB-R22", "summary": "Gift cards cannot be applied", "status": "…", "impact": "urgent",
    "categoryName": "…", "submittedAt": "…", "updatedAt": "…", "externalReference": "orbit-desk:case:88412"
  },
  "message": { }
}
```

`request` is the client view, without the description and the field values. Read them with [`GET /help-desk/requests/{requestKey}`](https://docs.youniton.com/api/reference/help-desk.md#getIntakeRequest). A `linkedTicket` appears only when the connection's client role can see the ticket.

## Calls back into Youniton

When your receiver calls the API because of a delivery, send `X-Kanso-Causation: <webhook-id>`. Then an automation loop stops at its depth limit.
