# Receive webhooks

We POST signed JSON to active webhook endpoints registered on the store for the invoice environment. Configure these endpoints in the dashboard. Use a publicly reachable HTTPS endpoint. SatLane cannot reach localhost on your computer; expose a local receiver through an HTTPS tunnel. Loopback, private-network destinations, credential-bearing URLs and redirects are rejected. Destination DNS is rechecked for delivery. A stored invoice `callback_url` is not currently used as a delivery destination.

**Success:** any `2xx`. We mark delivery `success` and stop.

**Retries (5xx + network errors / timeouts):** initial attempt, then retries at 1m → 5m → 30m → 2h → 12h → 24h. That is **7 total attempts** before the delivery moves to `dead_letter` (replayable from the dashboard).

**Permanent failures (4xx):** not retried. Delivery moves to `failed`. Common causes: wrong URL, expired auth on your reverse proxy, signature verification rejecting a legitimate event. Check the delivery result and recorded attempt diagnostics in the dashboard. Response excerpts are bounded.

The transport uses a 10-second delivery deadline as well as bounded connection/header/body waits, and records a bounded response excerpt. Redirects are not followed. Persist the verified event and queue its processing in one durable transaction, then return `2xx` quickly. Perform slow fulfillment work in the worker. If durable storage fails, return `5xx` so SatLane can retry.

## Headers

```http
POST /your-handler HTTP/1.1
Content-Type: application/json
User-Agent: SatLane-Webhook/1.0
X-SatLane-Signature: t=1721481600,v1=2a3b4c5d…
X-SatLane-Event-Id: evt_abc123
X-SatLane-Event-Type: invoice.paid
```

Header names are case-insensitive on the wire (`x-satlane-signature`, etc.).

## Body shape

```json
{
  "event_id": "evt_abc123",
  "event_type": "invoice.paid",
  "created_at": "2026-05-16T11:25:00.000Z",
  "livemode": true,
  "data": {
    "invoice": {}
  }
}
```

`data.invoice` uses the public invoice fields for real lifecycle events. Optional checkout URL fields can differ by event producer. Synthetic dashboard test deliveries can carry `data.message` instead; do not treat them as payment evidence.

## Verify the signature

Signature header format: `t=<unix_seconds>,v1=<hex>`.

Signed payload: `${timestamp}.${rawRequestBody}`

Algorithm: HMAC-SHA256 with your endpoint secret as the key.

**Node.js (standalone verifier using the built-in crypto module):**

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

function verifySatLaneSignature(rawBody, header, secret) {
  if (!Buffer.isBuffer(rawBody) || !secret || typeof header !== 'string') {
    throw new Error('Missing raw body, signature or webhook secret');
  }
  const parts = Object.fromEntries(
    header.split(',').map((part) => {
      const [key, value] = part.trim().split('=');
      return [key, value];
    }),
  );
  if (!/^\d+$/.test(parts.t ?? '') || !/^[a-f0-9]{64}$/i.test(parts.v1 ?? '')) {
    throw new Error('Malformed signature');
  }
  const timestamp = Number(parts.t);
  if (!Number.isSafeInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > 300) {
    throw new Error('Signature timestamp outside tolerance');
  }
  const expected = createHmac('sha256', secret).update(`${timestamp}.`).update(rawBody).digest();
  const supplied = Buffer.from(parts.v1, 'hex');
  if (!timingSafeEqual(expected, supplied)) throw new Error('Invalid signature');
}
```

**Express route example:** install Express separately. Register this route before any global JSON body parser so `req.body` is the original Buffer. Adapt the durable event storage and fulfillment queue to your application; the comments below are integration steps, not a complete order-processing implementation.

```js
app.post('/webhooks/satlane', express.raw({ type: 'application/json' }), async (req, res) => {
  try {
    verifySatLaneSignature(
      req.body,
      req.header('X-SatLane-Signature'),
      process.env.SATLANE_WEBHOOK_SECRET,
    );
  } catch {
    return res.status(400).end();
  }
  let event;
  try {
    event = JSON.parse(req.body.toString('utf8'));
    if (!event || typeof event.event_id !== 'string' || !event.event_id ||
        typeof event.event_type !== 'string') return res.status(400).end();
  } catch {
    return res.status(400).end();
  }
  try {
    // Implement this in your application. In one database transaction:
    // insert event_id with a unique constraint and save a processing job.
    // An already-saved event is a successful no-op, not a new fulfillment.
    await persistEventAndQueueAtomically(event);
    return res.status(200).end();
  } catch {
    return res.status(503).end();
  }
});
```

`persistEventAndQueueAtomically` is an application function you must implement; it is not a SatLane SDK function. Before fulfilling in its worker, validate the invoice, order, expected amount/currency and environment, then apply an idempotent order transition.

The repository's `@satlane/webhooks` package is an internal workspace package. This guide does not require installing it from the public npm registry.

**Python:**

```python
import hmac, hashlib, time

def verify(raw_body: bytes, header: str, secret: str, tolerance: int = 300):
    if not secret or not isinstance(raw_body, bytes):
        raise ValueError('missing secret or raw body')
    parts = dict(p.strip().split('=', 1) for p in header.split(','))
    t, v1 = int(parts['t']), parts['v1']
    if abs(time.time() - t) > tolerance:
        raise ValueError('timestamp out of tolerance')
    signed = str(t).encode('ascii') + b'.' + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, v1):
        raise ValueError('signature mismatch')
```

**PHP:**

```php
function verifySatlaneSignature(string $rawBody, string $header, string $secret, int $tolerance = 300): bool {
    $parts = [];
    foreach (explode(',', $header) as $p) {
        $pair = explode('=', trim($p), 2);
        if (count($pair) !== 2) return false;
        [$k, $v] = $pair;
        $parts[$k] = $v;
    }
    if ($secret === '' || !isset($parts['t'], $parts['v1']) ||
        !preg_match('/^[0-9]+$/D', $parts['t']) ||
        !preg_match('/^[a-f0-9]{64}$/iD', $parts['v1'])) return false;
    $t = (int) $parts['t']; $v1 = strtolower($parts['v1']);
    if (abs(time() - $t) > $tolerance) return false;
    $expected = hash_hmac('sha256', "{$t}.{$rawBody}", $secret);
    return hash_equals($expected, $v1);
}
```

Reject timestamps outside a five-minute tolerance in either direction. Verification errors, including malformed headers, must reject the request. Deduplicate valid event IDs durably; timestamp validation alone is not a replacement for duplicate detection. During secret rotation, accept signatures from either your current secret or your saved previous secret during the 24-hour transition. The standalone examples take one secret; extend your handler to try both during that window.

---