Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
355 changes: 355 additions & 0 deletions src/pages/docs/api/webhooks-guide.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,355 @@
---
title: "Tempo webhooks"
seoTitle: "Tempo Webhooks: Verification, Retries, and Replay | Tempo Docs"
description: "Receive signed Tempo webhook events for Routes and onchain activity, verify HMAC-SHA256 signatures, handle retries and auto-disable, and replay past deliveries."
---

import { Card, Cards } from 'vocs'

# Tempo webhooks

Receive signed HTTPS callbacks for [Tempo Routes](/docs/routes) lifecycle changes and onchain events instead of polling API endpoints.

## Subscribe to webhook events

Create a webhook subscription in [Tempo Console](https://tempo.com/console) or via `POST /v1/webhooks`. Authenticate every webhook management request with an API key in the `tempo-api-key` header; pay-per-request [MPP](/docs/api/authentication#mpp-paying-per-request) isn't supported for webhook management.

| Operation | Required scopes |
| --- | --- |
| Create, update, delete, ping, or replay deliveries | `webhooks:write` |
| List subscriptions or read delivery logs | `webhooks:read` |
| Subscribe to Routes events (`routes:transfer.updated`, `routes:deposit.updated`) | `webhooks:write` and `routes:read` |

Destination URLs must use `https://`, omit embedded credentials, and resolve to a public host. Tempo rejects loopback, private, link-local, and metadata addresses.

When you create a subscription, Tempo returns its signing secret (`whsec_…`) once in the response. Store it in your secret manager immediately; later reads never expose it.

### Supported event types

Each subscription listens to one event type and accepts an optional `filters` object to narrow matches (see the [Webhooks API reference](/docs/api/webhooks) for per-event filter schemas):

| Event type | Trigger |
| --- | --- |
| `routes:transfer.updated` | Emitted when a Routes transfer is created (`awaiting-source`, `version: 1`) and on each status or data change (incrementing `version`). Filterable by `id` or `status`. |
| `routes:deposit.updated` | Emitted when a Routes deposit changes state after initial detection (starting at the first transition after `detected`). Filterable by `depositAddressId` (the `rda_…` address ID), `recipient`, or `status`. |
| `token:transfer` | Emitted when a [TIP-20](/docs/protocol/tip20/overview) stablecoin transfer occurs onchain. |
| `transaction:included` | Emitted when a transaction is included in a block. |
| `log:emitted` | Emitted when a contract emits an event log matching your filter criteria. |
| `block:created` | Emitted when a new block is added to the chain. |
| `ping` | Synthetic test delivery triggered by `POST /v1/webhooks/{id}/ping`. |

Set `chainId` on the subscription to the EVM chain you want to monitor (such as `4217` for Tempo Mainnet). For `routes:transfer.updated`, `chainId` matches the transfer's EVM destination chain (transfers delivering to non-EVM chains don't emit transfer webhooks). For `routes:deposit.updated`, `chainId` matches either the deposit's EVM source or EVM destination chain.

## Webhook headers and payload

Tempo delivers each event as an HTTP `POST` with `content-type: application/json`, a JSON envelope body, and three headers:

| Header | Format | Purpose |
| --- | --- | --- |
| `tempo-event-id` | `evt_<64 hex>` | Event ID. For real events, stays identical across automatic retries and manual replays—use it for idempotency and deduplication. Each `ping` generates a fresh ID. |
| `tempo-event-type` | Event type string | Mirrors the envelope's `type` field (`routes:transfer.updated`, `routes:deposit.updated`, `ping`, or an onchain event type). |
| `tempo-signature` | `t=<unix>,v1=<hex>` | Unix seconds timestamp and lowercase hex HMAC-SHA256 signature of the raw body. |

The JSON envelope wraps the event payload in `data`. IDs carry type prefixes: `evt_` for events, `wh_` for subscriptions, `whd_` for delivery attempts, `rtr_` for Routes transfers, and `rdp_` for Routes deposits:

```json
{
"chainId": 4217,
"createdAt": "2026-10-14T00:00:00.000Z",
"data": {
"id": "rtr_001785729600000_2ZPE2gvateYEQ0dQslgvkhjx",
"status": "completed",
"updatedAt": "2026-10-14T00:00:00.000Z",
"version": 3
},
"id": "evt_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
"subscriptionId": "wh_001785729600000_2ZPE2gvateYEQ0dQslgvkhjx",
"type": "routes:transfer.updated"
}
```

`data` carries the same resource fields as the corresponding read endpoint, such as `GET /v1/routes/transfers/{id}` or `GET /v1/routes/deposits/{id}`. If you set optional `context` fields (`title`, `description`, or `metadata`) when creating or updating the subscription, Tempo echoes `context` on every envelope.

### Ordering and reconciliation

Webhook delivery is at-least-once and not strictly ordered. Build every handler to be idempotent:

- **Deduplicate on `tempo-event-id`.** Store processed event IDs so automatic retries and manual replays don't double-apply state changes.
- **Ignore stale Routes updates.** Treat each event as a state snapshot. For `routes:transfer.updated`, compare `data.version` and skip any event whose version isn't strictly greater than your stored version. For `routes:deposit.updated`, which has no `version` field, compare `data.updatedAt` and ignore older timestamps or any non-terminal update after a deposit reached a terminal state (`completed` or `refunded`).
- **Credit only on `completed`.** Routes transfers move through `awaiting-source` and `processing`, and deposits move through `detected`, `bridging`, and `settling`, before reaching terminal states (`completed`, `refunded`, or `expired` for transfers). Credit a customer balance only when `data.status` is `completed`, after reconciling the delivered `data.destinationAmount` and `data.destinationTransactionHashes` against your payment record.

## Verify webhook signatures

Always verify `tempo-signature` before trusting or processing a webhook body. Read the raw, unparsed HTTP request body bytes from your web framework before running any JSON parser, because re-serializing JSON can alter whitespace or key order.

1. Parse `t` (the Unix timestamp string in seconds) and `v1` (the 64-character lowercase hex digest) from `tempo-signature` (`t=<unix>,v1=<hex>`).
2. Check `t` against your server clock and reject deliveries outside a **±300-second (5-minute)** replay window.
3. Build the signed payload by concatenating the literal `t` string, a `.` separator, and the exact raw UTF-8 request body bytes: `<t>.<rawBody>`.
4. Compute HMAC-SHA256 over the signed payload using the **full `whsec_…` secret string as UTF-8 bytes**.
5. Compare the lowercase hex digest with `v1` in constant time.

:::warning
Use the full `whsec_…` secret string verbatim as UTF-8 bytes. Don't strip the `whsec_` prefix, and don't base64-decode the secret. Verify against the exact raw request bytes before parsing JSON.
:::

### Verification examples

::::code-group

```ts [TypeScript (Node)]
import { createHmac, timingSafeEqual } from 'node:crypto'

export function verifyTempoWebhook(
rawBody: Buffer | string,
signatureHeader: string,
secret: string,
toleranceSeconds = 300,
): boolean {
let rawTimestamp: string | undefined
let signature: string | undefined

for (const part of signatureHeader.split(',')) {
const separator = part.indexOf('=')
if (separator === -1) continue
const key = part.slice(0, separator).trim()
const value = part.slice(separator + 1).trim()
if (key === 't' && value) rawTimestamp = value
else if (key === 'v1' && value) signature = value
}

if (!rawTimestamp || !/^\d+$/.test(rawTimestamp) || !signature) return false

const timestamp = Number(rawTimestamp)
if (!Number.isSafeInteger(timestamp)) return false

const now = Math.floor(Date.now() / 1000)
if (Math.abs(now - timestamp) > toleranceSeconds) return false

const bodyBytes = typeof rawBody === 'string' ? Buffer.from(rawBody, 'utf8') : rawBody
const payload = Buffer.concat([Buffer.from(`${rawTimestamp}.`, 'utf8'), bodyBytes])
const expected = createHmac('sha256', Buffer.from(secret, 'utf8'))
.update(payload)
.digest('hex')

const received = Buffer.from(signature, 'utf8')
const wanted = Buffer.from(expected, 'utf8')
return received.length === wanted.length && timingSafeEqual(received, wanted)
}
```

```python [Python]
import hashlib
import hmac
import time


def verify_tempo_webhook(
raw_body: bytes,
signature_header: str,
secret: str,
tolerance_seconds: int = 300,
) -> bool:
raw_timestamp = None
signature = None

for part in signature_header.split(","):
if "=" not in part:
continue
key, value = part.split("=", 1)
key, value = key.strip(), value.strip()
if key == "t" and value:
raw_timestamp = value
elif key == "v1" and value:
signature = value

if (
not raw_timestamp
or not raw_timestamp.isascii()
or not raw_timestamp.isdigit()
or not signature
):
return False

if abs(int(time.time()) - int(raw_timestamp)) > tolerance_seconds:
return False

signed_payload = f"{raw_timestamp}.".encode("utf-8") + raw_body
expected = hmac.new(
secret.encode("utf-8"),
signed_payload,
hashlib.sha256,
).hexdigest()

return hmac.compare_digest(expected.encode("utf-8"), signature.encode("utf-8"))
```

```go [Go]
package webhooks

import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"strconv"
"strings"
"time"
)

func VerifyTempoWebhook(rawBody []byte, signatureHeader, secret string, toleranceSeconds int64) bool {
var rawTimestamp string
var signature string

for _, part := range strings.Split(signatureHeader, ",") {
key, value, ok := strings.Cut(part, "=")
if !ok {
continue
}
key, value = strings.TrimSpace(key), strings.TrimSpace(value)
switch key {
case "t":
rawTimestamp = value
case "v1":
signature = value
}
}

if rawTimestamp == "" || signature == "" {
return false
}

timestamp, err := strconv.ParseInt(rawTimestamp, 10, 64)
if err != nil {
return false
}

diff := time.Now().Unix() - timestamp
if diff < 0 {
diff = -diff
}
if diff > toleranceSeconds {
return false
}

mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(rawTimestamp))
mac.Write([]byte("."))
mac.Write(rawBody)
expected := hex.EncodeToString(mac.Sum(nil))

return hmac.Equal([]byte(expected), []byte(signature))
}
```

::::

### Canonical test vector

Use these inputs to unit-test your verifier (pinning the verifier clock within 300 seconds of `1767225600`):

| Field | Value |
| --- | --- |
| Secret | `whsec_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef` |
| Timestamp (`t`) | `1767225600` |
| Raw body | `{"chainId":4217,"createdAt":"2026-01-01T00:00:00.000Z","data":{"ping":true},"id":"evt_0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef","subscriptionId":"wh_001767225600000_example","type":"ping"}` |
| Expected `v1` | `6c193a322e1529f596e83e5fe255a34454f89165d874d099c25366fcc4b6032b` |
| `tempo-signature` | `t=1767225600,v1=6c193a322e1529f596e83e5fe255a34454f89165d874d099c25366fcc4b6032b` |

### Rotate signing secrets

Tempo emits a single `v1` signature per delivery and doesn't offer an in-place secret-rotation endpoint. For zero-downtime rotation:

1. Create a second overlapping webhook subscription for the same events and store its new `whsec_…` secret.
2. Update your handler to verify incoming `tempo-signature` headers against both the current and new secrets, accepting a request if either matches. Both subscriptions deliver matching events with the same `tempo-event-id`, so deduplicating on `tempo-event-id` prevents double processing during cutover.
3. Confirm deliveries succeed on the new subscription, then delete the old subscription with `DELETE /v1/webhooks/{id}`.

### Test an endpoint with ping

Send a synthetic signed event with `POST /v1/webhooks/{id}/ping` (requires `webhooks:write`):

```bash [Terminal]
curl -X POST 'https://api.tempo.xyz/v1/webhooks/<WEBHOOK_ID>/ping' \
-H "tempo-api-key: $TEMPO_API_KEY"
```

Tempo sends a signed `ping` event whose `data` is `{"ping":true}` and returns the HTTP status and timing immediately. Each ping creates a fresh random `evt_…` ID (so repeated pings aren't deduplicated), appears in your delivery log, and **never modifies the subscription's failure counter (`failureCount`) or `status`**.

## Retries and failure handling

Return any `2xx` HTTP status within **10 seconds** to acknowledge delivery. Enqueue heavy processing asynchronously so your endpoint responds quickly.

Tempo classifies failed attempts into retryable and non-retryable outcomes:

- **Retryable failures.** Network or transport errors, 10-second timeouts, HTTP `408`, HTTP `429`, and `5xx` responses.
- **Non-retryable failures (0 automatic retries).** All other `4xx` responses (including `400`, `401`, `403`, and `404`), `3xx` redirects (Tempo rejects redirects without following them for SSRF protection), and blocked-URL rejections.

### Retry backoff schedule

Retryable failures retry up to **30 total attempts** (1 initial attempt plus up to 29 retries over about 25 hours) using exponential backoff capped at one hour:

| Failed attempt | Delay before next attempt |
| --- | --- |
| 1 | `5s` |
| 2 | `25s` |
| 3 | `125s` (~2 minutes) |
| 4 | `625s` (~10 minutes) |
| 5 | `3125s` (~52 minutes) |
| 6 through 29 | `3600s` (1 hour) |
| 30 | None — delivery is marked failed and automatic retries stop |

## Auto-disable and recovery

A subscription's `status` is `active`, `paused`, or `disabled`. Tempo tracks net delivery failures in `failureCount`: each failed delivery attempt (whether retryable or non-retryable) adds `1`, and each successful delivery subtracts `1` (floored at `0`). Synthetic `ping` deliveries don't change `failureCount`.

When `failureCount` reaches **20**, Tempo automatically sets `status` to `disabled` and stops sending new deliveries.

After fixing your endpoint, re-enable the subscription in Tempo Console or via `PATCH /v1/webhooks/{id}` (`webhooks:write`):

```bash [Terminal]
curl -X PATCH 'https://api.tempo.xyz/v1/webhooks/<WEBHOOK_ID>' \
-H "tempo-api-key: $TEMPO_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"status":"active"}'
```

## Replay past deliveries

Tempo retains each delivery attempt row and its original signed envelope for **7 days** from when that attempt was recorded. You can replay any retained delivery (failed or succeeded):

1. List recent attempts with `GET /v1/webhooks/{id}/deliveries` (`webhooks:read`) or open the delivery log in Tempo Console, and copy the delivery's `id` (`whd_…`).
2. Replay that delivery inline with `POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry` (`webhooks:write`) or from Tempo Console:

```bash [Terminal]
curl -X POST 'https://api.tempo.xyz/v1/webhooks/<WEBHOOK_ID>/deliveries/<DELIVERY_ID>/retry' \
-H "tempo-api-key: $TEMPO_API_KEY"
```

Manual replay sends the exact original envelope with the same `tempo-event-id` and a fresh signature timestamp `t`. Replays execute once inline (they don't trigger automatic retry loops) and update `failureCount` like a normal delivery.

## Related

<Cards>
<Card
title="Webhooks API reference"
description="Covers endpoints for creating, managing, pinging, and replaying webhooks."
to="/docs/api/webhooks"
icon="lucide:webhook"
/>
<Card
title="Track delivery"
description="Covers Routes transfer and deposit lifecycle states and reconciliation."
to="/docs/routes/delivery"
icon="lucide:activity"
/>
<Card
title="Quotes and fees"
description="Covers dynamic Routes pricing, binding quotes, and 1:1 delivery subsidies."
to="/docs/routes/quotes"
icon="lucide:receipt"
/>
<Card
title="Authentication"
description="Covers API keys, environments, and scopes."
to="/docs/api/authentication"
icon="lucide:key-round"
/>
</Cards>
Loading
Loading