# Verify signatures (/docs/webhooks/verify-signatures)

Anyone can `POST` to your webhook URL. The `Swop-Signature` header proves a request came from Swop and wasn't changed on the way. **Always verify it before acting on an event.**

## How the signature works [#how-the-signature-works]

```text
Swop-Signature: t=1761760800,v1=5f2b8c…e41c9
```

| Part | Meaning |
|---|---|
| `t` | When Swop signed it, in Unix seconds |
| `v1` | Hex-encoded HMAC-SHA256 of the string `"<t>.<raw request body>"`, keyed with your `whsec_` signing secret |

To verify:

1. Read the **raw** request body as bytes. Don't parse and re-serialize the JSON first; any whitespace change breaks the signature.
2. Split the header into `t` and `v1`.
3. Reject it if `t` is more than **5 minutes** from now. That stops someone replaying an old request.
4. Compute HMAC-SHA256 of `t + "." + rawBody` with your secret, hex-encode it, and compare it to `v1` in **constant time**.

## Verifier code [#verifier-code]

These verifiers match Swop's own signing code and were tested against it.

```js tab="Node"
// Node 18+ with Express. express.raw() keeps the exact bytes Swop signed.
import crypto from 'node:crypto';
import express from 'express';

export function verifySwopSignature(secret, header, rawBody, toleranceS = 300) {
  const parts = Object.fromEntries(
    String(header || '').split(',').map((kv) => {
      const i = kv.indexOf('=');
      return [kv.slice(0, i).trim(), kv.slice(i + 1).trim()];
    }),
  );
  const t = Number(parts.t);
  if (!Number.isFinite(t) || Math.abs(Date.now() / 1000 - t) > toleranceS) return false;
  const expected = crypto.createHmac('sha256', secret).update(`${t}.${rawBody}`).digest('hex');
  const given = String(parts.v1 || '');
  if (given.length !== expected.length) return false;
  return crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));
}

const app = express();

app.post('/webhooks/swop', express.raw({ type: 'application/json' }), (req, res) => {
  const raw = req.body.toString('utf8');
  if (!verifySwopSignature(process.env.SWOP_WEBHOOK_SECRET, req.get('Swop-Signature'), raw)) {
    return res.status(400).send('bad signature');
  }
  const event = JSON.parse(raw);
  switch (event.event) {
    case 'checkout.paid':   /* fulfil event.data.orderId */ break;
    case 'payout.released': /* book revenue for event.data.orderId */ break;
    case 'ping':            /* "Send test" from the Developer page */ break;
  }
  res.sendStatus(200); // any 2xx counts as delivered
});

app.listen(3000);
```

```python tab="Python"
# Python 3.9+ with Flask. request.get_data() returns the exact bytes Swop signed.
import hashlib, hmac, json, os, time
from flask import Flask, request

def verify_swop_signature(secret: str, header: str, raw_body: bytes, tolerance_s: int = 300) -> bool:
    parts = dict(p.strip().split("=", 1) for p in (header or "").split(",") if "=" in p)
    try:
        t = int(parts["t"])
    except (KeyError, ValueError):
        return False
    if abs(time.time() - t) > tolerance_s:
        return False
    signed = f"{t}.".encode() + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))

app = Flask(__name__)

@app.post("/webhooks/swop")
def swop_webhook():
    raw = request.get_data()
    if not verify_swop_signature(os.environ["SWOP_WEBHOOK_SECRET"], request.headers.get("Swop-Signature", ""), raw):
        return "bad signature", 400
    event = json.loads(raw)
    if event["event"] == "checkout.paid":
        pass  # fulfil event["data"]["orderId"]
    elif event["event"] == "payout.released":
        pass  # book revenue for event["data"]["orderId"]
    return "", 200
```

```bash tab="curl (send yourself a signed test)"
# Sign and send a ping to your local endpoint, exactly as Swop would.
BODY='{"id":"evt_test","event":"ping","createdAt":"2026-10-29T00:00:00.000Z","data":{"message":"Swop webhook test"}}'
T=$(date +%s)
SIG=$(printf '%s' "$T.$BODY" | openssl dgst -sha256 -hmac "$SWOP_WEBHOOK_SECRET" -hex | sed 's/^.* //')
curl -X POST http://localhost:3000/webhooks/swop \
  -H "Content-Type: application/json" \
  -H "Swop-Event: ping" \
  -H "Swop-Signature: t=$T,v1=$SIG" \
  -d "$BODY"
```

## Common mistakes [#common-mistakes]

| Symptom | Cause |
|---|---|
| Every signature fails | Your framework parsed the JSON before you read it. Use the raw body (`express.raw`, `request.get_data()`). |
| Fails only in production | Wrong secret: each webhook has its own `whsec_`, and re-adding a webhook issues a new one. |
| Fails intermittently | Your server clock is off by more than 5 minutes. Sync it with NTP. |
| Works locally, not deployed | A proxy is rewriting the body or stripping the `Swop-Signature` header. |
