# Webhooks


Set the **webhook URL** and see the **signing secret** (`whsec_…`, created with every app) on your API app
(Dashboard → Developers → Apps). There is no per-payment callback URL.

## Events
| type | When |
|---|---|
| `payment.confirming` | Matching transfer seen on-chain, waiting for confirmations |
| `payment.paid` | Confirmed. **Ship the order.** (`flags` may include `late`, `overpaid`, `manual`) |
| `payment.underpaid` | Window + grace ended with less than the expected amount |
| `payment.expired` | Window ended with nothing received |
| `payment.cancelled` | Cancelled by you or the customer |
| `payment_link.completed` | One-time link got paid |
| `test.ping` | Sent by "Send test event" |

Subscribe to all or some events per app.

## Request we send
```
POST https://shop.example.com/webhooks/razcrypto
Content-Type: application/json
User-Agent: RazCrypto-Webhooks/1.0
webhook-id: evt_2kLq9VxP0aR7mN4sTz1c
webhook-timestamp: 1759400100
webhook-signature: v1,K5oZfzN95Z9UVu1EsfQmfVNQhnkZ2pj9o9NDN/H/pI4=

{
  "type": "payment.paid",
  "timestamp": "2026-10-02T10:15:00Z",
  "data": { "object": { …the full payment object… } }
}
```

## Verify the signature
1. Take the **raw request body** exactly as received (do not re-serialize JSON).
2. `signed_content = webhook-id + "." + webhook-timestamp + "." + raw_body`
3. `key = base64_decode(secret without "whsec_" prefix)`
4. `expected = base64(HMAC_SHA256(key, signed_content))`
5. `webhook-signature` is a space-separated list of `v1,<sig>`; accept if **any** matches
   (constant-time compare). Several appear while you roll the secret.
6. Reject if `|now − webhook-timestamp| > 300 s`.
7. Store `webhook-id` and ignore repeats (retries reuse the same id).

### Node.js (Express)
```js
import express from "express";
import crypto from "node:crypto";

const app = express();
app.post("/webhooks/razcrypto", express.raw({ type: "application/json" }), (req, res) => {
  const id = req.header("webhook-id");
  const ts = req.header("webhook-timestamp");
  const sigs = (req.header("webhook-signature") || "").split(" ");
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return res.sendStatus(400);

  const key = Buffer.from(process.env.RAZCRYPTO_WEBHOOK_SECRET.split("_")[1], "base64");
  const expected = crypto.createHmac("sha256", key)
    .update(`${id}.${ts}.${req.body.toString("utf8")}`).digest();
  const ok = sigs.some((s) => {
    const [v, b64] = s.split(",");
    const got = Buffer.from(b64 || "", "base64");
    return v === "v1" && got.length === expected.length && crypto.timingSafeEqual(got, expected);
  });
  if (!ok) return res.sendStatus(400);

  const event = JSON.parse(req.body.toString("utf8"));
  if (event.type === "payment.paid") { /* fulfil order event.data.object.reference_id */ }
  res.sendStatus(200);
});
```

### PHP
```php
<?php
$raw = file_get_contents('php://input');
$id  = $_SERVER['HTTP_WEBHOOK_ID'] ?? '';
$ts  = $_SERVER['HTTP_WEBHOOK_TIMESTAMP'] ?? '';
$sigs = explode(' ', $_SERVER['HTTP_WEBHOOK_SIGNATURE'] ?? '');
if (abs(time() - (int)$ts) > 300) { http_response_code(400); exit; }

$key = base64_decode(explode('_', getenv('RAZCRYPTO_WEBHOOK_SECRET'), 2)[1]);
$expected = base64_encode(hash_hmac('sha256', "$id.$ts.$raw", $key, true));
$ok = false;
foreach ($sigs as $s) {
    [$v, $sig] = array_pad(explode(',', $s, 2), 2, '');
    if ($v === 'v1' && hash_equals($expected, $sig)) { $ok = true; break; }
}
if (!$ok) { http_response_code(400); exit; }

$event = json_decode($raw, true);
// if ($event['type'] === 'payment.paid') { ... }
http_response_code(200);
```

### Python (Flask)
```python
import base64, hashlib, hmac, os, time
from flask import Flask, request, abort

app = Flask(__name__)

@app.post("/webhooks/razcrypto")
def razcrypto_webhook():
    raw = request.get_data()  # raw bytes
    wid = request.headers.get("webhook-id", "")
    ts = request.headers.get("webhook-timestamp", "0")
    sigs = request.headers.get("webhook-signature", "").split(" ")
    if abs(time.time() - int(ts)) > 300:
        abort(400)
    key = base64.b64decode(os.environ["RAZCRYPTO_WEBHOOK_SECRET"].split("_", 1)[1])
    expected = base64.b64encode(
        hmac.new(key, f"{wid}.{ts}.".encode() + raw, hashlib.sha256).digest()
    ).decode()
    if not any(s.startswith("v1,") and hmac.compare_digest(s[3:], expected) for s in sigs):
        abort(400)
    event = request.get_json()
    # if event["type"] == "payment.paid": ...
    return "", 200
```
Or use the SDK: `razcrypto.webhooks.verify(rawBody, headers, secret)`.

## Delivery rules
- Respond **2xx within 10 s**; do slow work after responding. Redirects are not followed.
- Retries on non-2xx / timeout: 1 attempt + 10 retries after 30 s, 2 m, 10 m, 30 m, 1 h, 3 h, 6 h, 12 h, 24 h, 24 h (~3 days).
- After 3 days of continuous failure the endpoint is disabled and you get an email.
- Order is not guaranteed; use `data.object.status` and `timestamp`, or fetch the payment.
- Delivery log (request, response code, first 2 KB of response, latency) for 90 days; **Resend** any
  delivery; **Send test event** from the dashboard or `POST /v1/webhooks/test`.

## Events API
`GET /v1/events?type=payment.paid&limit=20` (cursor: `starting_after`) and `GET /v1/events/{id}` —
every event with the payment snapshot that was (or will be) delivered. Real output (shortened):
```json
{
  "object": "event",
  "id": "evt_JRJPxmtld0prouxq0gkb",
  "type": "payment.cancelled",
  "livemode": false,
  "created_at": "2026-10-02T11:35:20.506Z",
  "data": {
    "object": {
      "id": "pay_…",
      "object": "payment",
      "status": "cancelled",
      "…": "…"
    }
  }
}
```

## Delivery log (dashboard)
Developers → Webhooks shows each delivery (status `pending` · `retrying` · `succeeded` · `failed`,
attempts, response code, first 2 KB of the response, latency, next retry). **Resend** creates a new
delivery with the same `webhook-id`, so your dedupe still works.

## Rolling the secret
Dashboard → Roll secret: for 24 h we sign with both old and new secrets (two `v1,` entries).
