# Webhooks

> Get told the moment a customer confirms a verification link, with signed messages, retries and a log.

A webhook is an address on your system that OTP.ps posts to when something happens. Add one on the dashboard (**Webhooks**) or with the API. Each address belongs to one mode: it receives events of **live** links or of **test** links.

## Events

| Type | When |
|---|---|
| `link.approved` | The customer confirmed a [verification link](/docs/verification-links) |
| `link.expired` | A link wasn't confirmed in time |
| `link.canceled` | You canceled a link |
| `ping` | You pressed "Send test event" on the dashboard |

The body (JSON):

```json
{
  "id": "evt_9aB3cD4eF5gH6iJ7",
  "type": "link.approved",
  "created_at": "2026-11-19T10:03:00.000Z",
  "test": false,
  "data": {
    "id": "lnk_Xq3vB9kLm2Pz7RtY", "object": "link", "status": "approved",
    "to": "0599 ••• 456", "network": "jawwal", "purpose": "order", "locale": "ar",
    "delivery": "sms", "reference": "#1042", "return_url": null, "segments": 1, "test": false,
    "created_at": "2026-11-19T10:00:00.000Z", "expires_at": "2026-11-20T10:00:00.000Z",
    "opened_at": "2026-11-19T10:02:41.000Z", "approved_at": "2026-11-19T10:03:00.000Z"
  }
}
```

Use `data.reference` to find your order. The full number is never sent; you already know it.

## Check the signature

Every request carries `OTP-Signature: t=<unix seconds>,v1=<signature>`, where the signature is the hex HMAC-SHA256 of `"<t>.<raw body>"` with your address's secret (`whsec_…`, shown once when the address is made). Always check it, using the **raw** body (before parsing the JSON), and refuse anything older than 5 minutes. The [SDKs](/docs/sdks/javascript) do this for you (`verifyWebhook`, `OtpPs\Webhook::verify`).

```js title="examples/webhooks/verify-node.mjs"
// Checking an OTP.ps webhook in Node.js (Express shown; any framework works).
// Use the RAW body: parsing the JSON first changes the bytes and the signature won't match.
//   OTP_PS_WEBHOOK_SECRET=whsec_…   (from the dashboard, or POST /api/v1/webhooks)
import { createHmac, timingSafeEqual } from "node:crypto";

/** Returns the event, or throws when the signature is wrong or more than 5 minutes old. */
export function verifyOtpWebhook(rawBody, signatureHeader, secret = process.env.OTP_PS_WEBHOOK_SECRET) {
  const m = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(signatureHeader ?? "");
  if (!m) throw new Error("Missing or malformed OTP-Signature");
  if (Math.abs(Date.now() / 1000 - Number(m[1])) > 300) throw new Error("Webhook too old");
  const expected = createHmac("sha256", secret).update(`${m[1]}.${rawBody}`).digest();
  if (!timingSafeEqual(expected, Buffer.from(m[2], "hex"))) throw new Error("Bad signature");
  return JSON.parse(rawBody);
}

// Express:
//   app.post("/webhooks/otp", express.raw({ type: "application/json" }), (req, res) => {
//     let event;
//     try { event = verifyOtpWebhook(req.body.toString("utf8"), req.get("OTP-Signature")); }
//     catch { return res.sendStatus(400); }
//     if (event.type === "link.approved") markOrderConfirmed(event.data.reference); // your code
//     res.sendStatus(200); // answer fast; OTP.ps retries anything that isn't 2xx
//   });
```

```php title="examples/webhooks/verify-php.php"
<?php
// Checking an OTP.ps webhook in plain PHP. Use the RAW body (php://input).
//   OTP_PS_WEBHOOK_SECRET=whsec_…

/** Returns the event as an array, or null when the signature is wrong or more than 5 minutes old. */
function verify_otp_webhook(string $rawBody, string $signatureHeader, string $secret): ?array
{
    if (!preg_match('/^t=(\d+),v1=([0-9a-f]{64})$/', $signatureHeader, $m)) {
        return null;
    }
    if (abs(time() - (int) $m[1]) > 300) {
        return null;
    }
    $expected = hash_hmac('sha256', $m[1] . '.' . $rawBody, $secret);
    return hash_equals($expected, $m[2]) ? json_decode($rawBody, true) : null;
}

// As a webhook endpoint (webhook.php):
if (PHP_SAPI !== 'cli') {
    $event = verify_otp_webhook(file_get_contents('php://input'), $_SERVER['HTTP_OTP_SIGNATURE'] ?? '', getenv('OTP_PS_WEBHOOK_SECRET'));
    if ($event === null) {
        http_response_code(400);
        exit;
    }
    if ($event['type'] === 'link.approved') {
        // mark_order_confirmed($event['data']['reference']); // your code
    }
    http_response_code(200);
}
```

```python title="examples/webhooks/verify_python.py"
"""Checking an OTP.ps webhook in Python (Flask shown). Use the RAW body.

    OTP_PS_WEBHOOK_SECRET=whsec_...
"""
import hashlib
import hmac
import json
import os
import re
import time


def verify_otp_webhook(raw_body: bytes, signature_header: str, secret: str = None):
    """Returns the event, or raises ValueError when the signature is wrong or more than 5 minutes old."""
    secret = secret or os.environ["OTP_PS_WEBHOOK_SECRET"]
    m = re.fullmatch(r"t=(\d+),v1=([0-9a-f]{64})", signature_header or "")
    if not m:
        raise ValueError("Missing or malformed OTP-Signature")
    if abs(time.time() - int(m.group(1))) > 300:
        raise ValueError("Webhook too old")
    expected = hmac.new(secret.encode(), m.group(1).encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, m.group(2)):
        raise ValueError("Bad signature")
    return json.loads(raw_body)


# Flask:
#   @app.post("/webhooks/otp")
#   def otp_webhook():
#       try:
#           event = verify_otp_webhook(request.get_data(), request.headers.get("OTP-Signature", ""))
#       except ValueError:
#           return "", 400
#       if event["type"] == "link.approved":
#           mark_order_confirmed(event["data"]["reference"])  # your code
#       return "", 200
```

## Answer quickly, handle repeats

- Answer `2xx` within 8 seconds; do slow work afterwards. Anything else (including redirects, which are not followed) counts as a failure.
- Failed deliveries are retried after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours, 12 hours and 24 hours, then given up. The dashboard shows every delivery and its last result.
- The same event can arrive more than once. Use the event `id` (also in the `OTP-Event-Id` header) to ignore repeats.

## Manage addresses with the API

For tools that subscribe themselves (Zapier, Make, n8n), with the `read` scope:

| | |
|---|---|
| `POST /api/v1/webhooks` | `{ url, events?, description? }` → the address and its `secret` (once) |
| `GET /api/v1/webhooks` | the key's mode's addresses (no secrets) |
| `DELETE /api/v1/webhooks/{id}` | stop sending there |

Addresses must be public `https://` addresses: private networks, `localhost` and IP addresses of internal networks are refused, and the address is checked again before every delivery. At most 10 addresses per account.
