# Webhooks (/docs/swivy/webhooks)

<Callout type="warn" title="Preview: Swivy is not generally available">
Swivy is a **staging/testnet preview using software custody**, not a production custody service. All six public SDK packages are available at **1.0.1**. Use test assets only. [Set up the preview](/docs/swivy/preview-setup) or [request project access](/docs/swivy/request-access).
</Callout>

**In plain words:** instead of polling an intent until it's done, give Swivy a URL. When the intent finishes, Swivy `POST`s a small JSON message there, signed with a secret only you and Swivy know.

## Register an endpoint [#register-an-endpoint]

Server only, with an organization admin credential:

```bash
curl -X POST "$SWIVY_BASE_URL/v1/control/environments/env_.../webhooks" \
  -H "content-type: application/json" \
  -H "x-swivy-admin-key: $SWIVY_ADMIN_KEY" \
  -d '{ "url": "https://example.com/swivy/webhooks" }'
```

The response reveals the signing **secret once**. Store it like a password. You can list endpoints, rotate a secret (`POST .../webhooks/{webhookId}/rotate-secret`) and revoke an endpoint (`DELETE .../webhooks/{webhookId}`).

Endpoints must be public HTTPS-reachable hosts. Swivy refuses private or local addresses, URLs with credentials and redirects.

## Events [#events]

| Event `type` | When | Body |
|---|---|---|
| `swivy.intent.completed` | A signing or transaction intent finished successfully. | `{ "type", "intentId", "environmentId", "result" }` |

```json
{
  "type": "swivy.intent.completed",
  "intentId": "int_...",
  "environmentId": "env_...",
  "result": { "transactionHash": "0x..." }
}
```

{/* TODO(review): result fields differ by intent kind (signature vs transaction hash); document per kind once stable. */}

## Verify the signature [#verify-the-signature]

Each delivery carries an `x-swivy-signature` header: the **hex HMAC-SHA256 of the raw JSON body**, keyed with your endpoint's secret. Compute it over the exact bytes you received and compare in constant time.

<CodeTabs items={['Node', 'Python']}>
<Tab value="Node">

```js
import crypto from 'node:crypto';
import express from 'express';

const app = express();

app.post('/swivy/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  const expected = crypto
    .createHmac('sha256', process.env.SWIVY_WEBHOOK_SECRET)
    .update(req.body) // raw bytes
    .digest('hex');
  const got = req.get('x-swivy-signature') ?? '';
  const ok = got.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(got), Buffer.from(expected));
  if (!ok) return res.status(400).send('bad signature');

  const event = JSON.parse(req.body);
  if (event.type === 'swivy.intent.completed') {
    // mark event.intentId done in your database (idempotently)
  }
  res.sendStatus(200);
});
```

</Tab>
<Tab value="Python">

```python
import hashlib, hmac, json, os
from flask import Flask, request, abort

app = Flask(__name__)

@app.post("/swivy/webhooks")
def swivy_webhook():
    raw = request.get_data()
    expected = hmac.new(os.environ["SWIVY_WEBHOOK_SECRET"].encode(), raw, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(request.headers.get("x-swivy-signature", ""), expected):
        abort(400)
    event = json.loads(raw)
    if event["type"] == "swivy.intent.completed":
        pass  # mark event["intentId"] done (idempotently)
    return "", 200
```

</Tab>
</CodeTabs>

## Delivery and retries [#delivery-and-retries]

The current preview retries deliveries immediately, then after 5s, 5m, 30m, 2h, 5h, 10h and 10h. After the last attempt the delivery is marked failed. Your backend can list deliveries and replay them through the [server API](/docs/swivy/api-reference/server).

Supported events include `swivy.intent.completed`, `swivy.intent.failed`, `swivy.identity.created`, `swivy.identity.authenticated` and `swivy.wallet.created`.

Bodies include an event `id` and `createdAt`; deliveries also carry `x-swivy-event-id` and `x-swivy-delivery-attempt`. Verify the HMAC over the raw body, de-duplicate on the signed body’s `id`, and apply an event-age policy that allows expected retries and deliberate replays. Process each event idempotently. The earlier example shows the intent-specific fields; these delivery fields are also present.

Incoming-transfer (deposit) events and confirmation tracking are not provided by this event list.
