# Webhooks

> Hear the moment a test is completed or its level changes, and check that a request is from Lernexa.

Source: https://lernexa.com/docs/developers/language-test/webhooks

A webhook posts a test to a URL of yours the moment it is completed, and again whenever your staff
confirm or change its level. No polling.

## Setting it up

1. In the staff app, open **Integrations** and paste your URL under **Webhook**. It must start with
   `https://`. In Zapier, use a **Catch Hook** URL (see the [Zapier guide](https://lernexa.com/docs/developers/language-test/zapier)).
2. Press **Save**. A signing secret appears, starting with `whsec_`.
3. Press **Send a test event**. A sample completed test arrives at your URL, to build the rest of
   your integration from. The page says what your server answered.

## What is sent

A `POST` with a JSON body:

```json
{
  "id": "7f0c2a7e-2a1b-4bd5-9a43-0b6f8a7f3c11",
  "event": "test.completed",
  "createdAt": "2026-10-29T10:31:00.000Z",
  "test": { "id": "5c0e7a52-…", "externalId": "booking-1042", "status": "completed", "result": { "levelText": "B1 High", … }, … }
}
```

`test` is the same as `GET /tests/{externalId}` returns. See [Reading results](https://lernexa.com/docs/developers/language-test/results).

| `event`                  | When                                                                           |
| ------------------------ | ------------------------------------------------------------------------------ |
| `test.completed`         | The candidate completed the test, or someone pressed **Send again** on its page. |
| `test.placement_changed` | Someone confirmed, changed or took back the level on the test's page.          |
| `test.sample`            | Someone pressed **Send a test event**. The test in it is made up.              |

:::caution[Filter on the event]
Every event goes to the same URL. Send emails or start work on `test.completed` only, treat
`test.placement_changed` as an update of the stored level and nothing more, and ignore
`test.sample` once you are set up. Otherwise a level change sends the same email twice.
:::

## Answering

Answer with any `2xx` status within 10 seconds. Anything else, a redirect, or no answer counts as a
failure, and the request is tried again **1, 6, 21 and 51 minutes** after the first try: five tries
in all. The test event is tried once.

- Every try of one request carries the **same `id`**: if you see it twice, you have seen it before.
  **Send again** on a test's page tries a request still being tried, if there is one, and
  otherwise makes a new request with a new `id`.
- Each try sends the test **as it is at that moment**: a request retried after your staff changed
  the level carries their level.
- Redirects are not followed.

The Integrations page lists the latest requests and what came of them. Each test's page lists its
own, with **Send again** to post it once more.

## Headers

| Header                | What it holds                                         |
| --------------------- | ----------------------------------------------------- |
| `X-Lernexa-Event`     | The event, as in the body.                            |
| `X-Lernexa-Delivery`  | The request's `id`, as in the body.                   |
| `X-Lernexa-Signature` | `t=<unix time>,v1=<signature>`, to check the request. |

## Checking the signature

The signature proves a request comes from Lernexa and was not changed on the way:

- `t` is the time it was signed, in **seconds** since 1970 (Unix time).
- `v1` is the HMAC-SHA256, in lowercase hex, of `t`, a full stop and the **raw body exactly as
  received**.
- The key is the **whole signing secret as text**, `whsec_` included. It is not base64 and is not
  decoded.

Sign the bytes you received, before any JSON parsing: a body parsed and serialised again may differ
by a space and will not match. Refuse a time more than five minutes old, so a recorded request
cannot be replayed later.

```js title="verify.mjs (Node.js)"
import { createHmac, timingSafeEqual } from 'node:crypto';

/**
 * rawBody: the request body exactly as received, a Buffer (express.raw()) or the string it decodes
 * to. Never JSON.stringify(req.body).
 */
export function isFromLernexa(rawBody, signatureHeader, secret, now = Date.now()) {
  const match = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(signatureHeader ?? '');
  if (!match) return false;
  const [, t, v1] = match;
  if (Math.abs(now / 1000 - Number(t)) > 300) return false;
  const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex');
  return timingSafeEqual(Buffer.from(expected), Buffer.from(v1));
}
```

```python title="verify.py (Python)"
import hashlib, hmac, re, time

def is_from_lernexa(raw_body: bytes, signature_header: str, secret: str, now: float | None = None) -> bool:
    """raw_body: the request body exactly as received (request.get_data() in Flask, await request.body() in FastAPI)."""
    match = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", signature_header or "")
    if not match:
        return False
    t, v1 = match.groups()
    if abs((time.time() if now is None else now) - int(t)) > 300:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)
```

Zapier's Catch Hook cannot check signatures: there, the secret part is the hook's URL, so keep it
private. Making a new secret on the Integrations page stops the old one at once.
