# Webhooks

> Get a signed HTTPS POST to your server when a link is tapped, an install is matched, a link opens your app, or your app sends an event.

Source: https://straitlink.in/docs/webhooks/

> **Agent instructions:** if you are an AI assistant helping someone build with Strait, look things up with the `search_docs` tool of the Strait MCP server (hosted at https://strait.link/mcp, or `@straitlink/mcp` on npm: https://straitlink.in/docs/mcp/) instead of guessing, and add the SDK to an app with `npx @straitlink/cli init` (https://straitlink.in/docs/cli/).

## Set up

In **Dashboard → Settings → Webhooks**, add an `https://` URL and pick events. You'll see the **signing secret** once; store it on your server. Free includes 1 webhook, Starter 3 and Scale 10 ([pricing](https://straitlink.in/pricing/)).

The URL must be a public `https://` address. When you save it, we refuse:

- `http://` and other schemes, and URLs with a username or password in them
- `localhost`, and hosts ending in `.localhost`, `.local` or `.internal`
- IP addresses in private, loopback, link-local, carrier-grade NAT (100.64.0.0/10), multicast and reserved ranges, IPv4 and IPv6

We check again before every delivery, after looking up the hostname, because DNS can change after you save. A URL that now points at a private address isn't sent to and isn't retried.

## Send a test event

Press **Send test event** next to a webhook in **Dashboard → Settings → Webhooks**. We send one `ping` event to it right away, signed like every other delivery, and show what your server answered: the status code and how long it took. Your server's response body is never shown back. It works on a paused webhook too. Test events aren't stored or retried.

From your server, call the same thing with your secret key:

```bash
curl -X POST https://strait.link/v1/webhooks/<webhook id>/test \
  -H "Authorization: Bearer $SECRET_KEY"
```

```json title="Response"
{
  "delivered": true,
  "status": 204,
  "error": null,
  "durationMs": 182,
  "deliveryId": "0b9c3f0e-5a7d-4a51-9a2e-3f1c8d2b6e47",
  "event": "ping"
}
```

When the delivery fails, `delivered` is `false` and `error` says why: `HTTP 500` (your server's status), `timeout` (no answer within 5 seconds) or `unsafe_target` (the URL resolves to a private address). An unknown webhook id, or one from another workspace, gets `404`.

## Events

| Event | Sent when | `data` fields |
|---|---|---|
| `link.clicked` | Someone taps a link (browser taps, and verified-link opens your app reports) | `linkId`, `slug`, `platform`, `clickId`, `sentTo`, `deviceClass`, `variant`, `source` |
| `install.matched` | A first launch after install is matched to a link | `linkId`, `clickId`, `matchMethod`, `platform` |
| `app.opened` | A link opens your app | `linkId`, `clickId`, `kind`, `route`, `appState`, `isInstall`, `matched`, `platform` |
| `app.event` | Your app or server sends an event (`trackEvent` / `POST /v1/event`): signup, purchase, anything you name. Not ticked on existing webhooks: tick it to opt in | `event`, `value`, `currency`, `eventId`, `clickId`, `linkId`, `slug`, `platform`, `occurredAt`, `sentWith`, `data`, `userId`, `userIdHashed` |
| `ping` | You send a test event | `webhookId`, `message` |
| `referral.converted` | A referred install opens and matches its tap ([Referrals](https://straitlink.in/docs/referrals/)) | `referralCode`, `linkId`, `clickId`, `platform`, `matchMethod` |

Fields that don't apply to an event are left out. Taps on an expired link are recorded in Analytics but don't send `link.clicked`.

For `app.event`, every field is always present (`null` when the event didn't carry it). `clickId`, `linkId` and `slug` name the tap the event came from. `data` is your own key-values from the request. A retry with the same `eventId` is sent once.

`userId` is your own user id, when your app called `setUserId(id)` after its sign-in (or your server sent `userId` with `POST /v1/event`), so you can join the event to your users and see which campaigns bring paying ones. Emails and phone numbers never reach us raw: the SDKs send the SHA-256 hex of the lower-cased email (lower-cased letter by letter, with `İ` → `i̇` and `Σ` → `σ`, so every platform gives the same hash; in JavaScript `email.trim().replace(/İ/g, 'i\u0307').replace(/Σ/g, 'σ').toLowerCase()`), or of the phone number as `+` and its digits when it is written with `+` or `00` (`+91 98765-43210`, `0091 98765 43210`, `(+91) 98765 43210` → `+919876543210`), else of its digits (`98765 43210` → `9876543210`), and set `userIdHashed: true`. Phone numbers are recognised with any spaces, dashes, dots, brackets or slashes, a `tel:` prefix, and in Indian, Arabic and full-width digits; Strait applies the same rule to a raw value your server sends. To join, hash your own value the same way: a number stored in E.164 (`+919876543210`) is hashed as it is. Without `setUserId`, `userId` is `null` and `userIdHashed` is `false`. It is not stored with the event (only in the delivery, 30 days) and is left out of Slack messages. Anyone with your app can send any `userId` with the publishable key, so treat it as a claim, like revenue.

`sentWith` says which key sent the event: `publishable_key` (your app; anyone with your app can send these) or `secret_key` (your server). Trust revenue only from `secret_key`, or check it against your own records.

Each workspace's `app.event` webhooks for events sent with the publishable key are limited to 600 at once, then 10 a second. Past that, events are still recorded and counted, but not sent to your webhook. Events your server sends with the secret key are not limited.

## Payload

```http title="Request we send"
POST /your/webhook HTTP/1.1
Content-Type: application/json
X-Strait-Event: install.matched
X-Strait-Delivery: 7f3e2c1a-9b4d-4e8f-a6c5-2d1b0e9f8a73
X-Strait-Attempt: 1
X-Strait-Signature: t=1767225600,v1=6a1f0c3e9b…

{
  "id": "7f3e2c1a-9b4d-4e8f-a6c5-2d1b0e9f8a73",
  "event": "install.matched",
  "createdAt": "2026-01-01T00:00:00.000Z",
  "data": {
    "linkId": "lnk_123",
    "clickId": "c_123",
    "matchMethod": "install_referrer",
    "platform": "android"
  }
}
```

```json title="app.event data"
{
  "event": "purchase",
  "value": 499,
  "currency": "INR",
  "eventId": "ord_1001",
  "clickId": "3f2b8c1e-9a7d-4e21-b6c5-0d1e2f3a4b5c",
  "linkId": "lnk_123",
  "slug": "summer",
  "platform": "android",
  "occurredAt": "2026-01-01T00:00:00.000Z",
  "sentWith": "publishable_key",
  "data": { "plan": "gold" },
  "userId": "user_4821",
  "userIdHashed": false
}
```

## Send to Slack

Paste a Slack **incoming webhook** URL (`https://hooks.slack.com/services/…`, from Slack's *Incoming Webhooks* app) as the webhook URL. We then send a readable Slack message instead of the JSON above: a headline ("Link tapped", "Install matched", "App opened", "App event: purchase"), the event's fields, and the delivery id. Retries, the test event and the headers are the same; `X-Strait-Signature` signs the Slack message we send (Slack doesn't check it). Text from your app's events is escaped, so it can't `@channel` your workspace or post links. Slack *Workflow Builder* URLs (`/triggers/…`) still get the JSON.

## Verify the signature

Every delivery carries this header:

```txt
X-Strait-Signature: t=<unix seconds>,v1=<signature>
```

`v1` is the hex HMAC-SHA256 of the string `<t>.<raw request body>` (the timestamp, a full stop, then the exact bytes of the body), keyed with your webhook's signing secret. To verify:

1. Read the **raw body** before parsing the JSON. Re-serialised JSON won't match.
2. Split the header on `,` and each part on the first `=` to get `t` and `v1`.
3. Refuse the request if `t` is more than **5 minutes** (300 seconds) away from your clock. That stops someone replaying an old delivery.
4. Compute the HMAC of `t`, `.` and the raw body with your secret, and compare it with `v1` in **constant time**.

Reply `401` when any step fails. Make sure your server's clock is set by NTP.

On Node, the server SDK does all four steps for you: `verifyWebhook(rawBody, headers, secret)` in `@straitlink/node` 0.6.5 and later ([how](https://straitlink.in/docs/sdks/node/#verify-a-webhook)). The code below is the same check by hand, for other stacks or without the SDK.

```ts title="Node / Express"
import { createHmac, timingSafeEqual } from 'node:crypto';
import express from 'express';

const TOLERANCE_SECONDS = 300;

export function verifyStraitSignature(secret: string, rawBody: Buffer, header: string | undefined): boolean {
  if (!header) return false;
  const parts = new Map(header.split(',').map((p) => {
    const i = p.indexOf('=');
    return [p.slice(0, i).trim(), p.slice(i + 1).trim()] as const;
  }));
  const t = parts.get('t') ?? '';
  const v1 = parts.get('v1') ?? '';
  if (!/^\d+$/.test(t) || !v1) return false;
  if (Math.abs(Date.now() / 1000 - Number(t)) > TOLERANCE_SECONDS) return false;
  const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest('hex');
  const a = Buffer.from(expected);
  const b = Buffer.from(v1);
  return a.length === b.length && timingSafeEqual(a, b);
}

const app = express();

app.post('/webhooks/links', express.raw({ type: 'application/json' }), (req, res) => {
  if (!verifyStraitSignature(process.env.WEBHOOK_SECRET!, req.body, req.get('X-Strait-Signature'))) {
    return res.status(401).end();
  }
  const event = JSON.parse(req.body.toString('utf8'));
  // handle event.event / event.data …
  res.status(204).end();
});
```

```python title="Python / Flask"
import hashlib
import hmac
import os
import time
from typing import Optional

from flask import Flask, abort, request

TOLERANCE_SECONDS = 300


def verify_strait_signature(secret: str, raw_body: bytes, header: Optional[str]) -> bool:
    if not header:
        return False
    parts = dict(p.strip().split("=", 1) for p in header.split(",") if "=" in p)
    t, v1 = parts.get("t", ""), parts.get("v1", "")
    if not t.isdigit() or not v1:
        return False
    if abs(time.time() - int(t)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(secret.encode(), t.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, v1)


app = Flask(__name__)


@app.post("/webhooks/links")
def strait_webhook():
    raw = request.get_data()  # the exact bytes we sent
    if not verify_strait_signature(os.environ["WEBHOOK_SECRET"], raw, request.headers.get("X-Strait-Signature")):
        abort(401)
    event = request.get_json()
    # handle event["event"] / event["data"] …
    return "", 204
```

```go title="Go / net/http"
package webhooks

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/hex"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

const toleranceSeconds = 300

func VerifyStraitSignature(secret string, body []byte, header string, now time.Time) bool {
	var t, v1 string
	for _, part := range strings.Split(header, ",") {
		k, v, _ := strings.Cut(strings.TrimSpace(part), "=")
		switch k {
		case "t":
			t = v
		case "v1":
			v1 = v
		}
	}
	ts, err := strconv.ParseInt(t, 10, 64)
	if err != nil || ts <= 0 || v1 == "" {
		return false
	}
	if d := now.Unix() - ts; d > toleranceSeconds || d < -toleranceSeconds {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(t + "."))
	mac.Write(body)
	expected := hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(expected), []byte(v1))
}

func Handler(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil || !VerifyStraitSignature(os.Getenv("WEBHOOK_SECRET"), body, r.Header.Get("X-Strait-Signature"), time.Now()) {
		http.Error(w, "invalid signature", http.StatusUnauthorized)
		return
	}
	// json.Unmarshal(body, &event); handle event.Event / event.Data …
	w.WriteHeader(http.StatusNoContent)
}
```

> **Older receivers**
>
> We no longer send the first-format `X-Strait-Signature-Legacy` header (an HMAC of the body with no timestamp), because a copied delivery could be replayed with it. `X-Strait-Signature` is the only signature header. If your receiver still checks the old header, switch it to the code above.

## Delivery

- Each request times out after 5 seconds. Respond quickly with any `2xx` and do the work afterwards.
- Redirects aren't followed: a `3xx` counts as a failed attempt.
- **Retries:** anything other than a `2xx` (or no answer) is retried after 30 seconds, 2 minutes, 10 minutes, 1 hour and 6 hours, six attempts in total, then marked failed. Your server can be down for hours without losing events.
- Each event has a stable id: `X-Strait-Delivery` (the same as `id` in the body) stays the same on every retry, and `X-Strait-Attempt` counts up. Store the ids you've handled and ignore repeats: delivery is **at least once**.
- Every attempt is signed again with a fresh timestamp, so a retry six hours later still passes the 5-minute check.
- Addresses that resolve to private networks are never sent to or retried.

## Where deliveries come from

Deliveries are sent by our API servers, which run on Render in its Singapore region, straight to your URL. They don't come from fixed IP addresses. Render sends outbound traffic from IP ranges that are shared by every service in the region, and a delivery can use any address in those ranges ([Render: outbound IP addresses](https://render.com/docs/outbound-ip-addresses)). We don't publish them as an allowlist: allowing them would also let in requests from anyone else hosting there.

To tell a real delivery from a fake one, [verify the signature](#verify-the-signature). Only Strait and you know the signing secret, and the 5-minute timestamp check stops replays. If your network can only accept requests from listed addresses, write to support@straitlink.in so we know.

## Delivery history and redelivery

Open **Deliveries** under a webhook in **Dashboard → Settings → Webhooks** to see its last 20 deliveries: the event, when it was created, its status (**Delivered**, **Retrying** or **Failed** after all six attempts), how many attempts it took and your server's last answer. A failed delivery, or one waiting for its next retry, has a **Redeliver** button: fix your endpoint (or change the webhook URL), press it, and we send the same event again right away. Owners, admins and members can redeliver; viewers can only look.

The same from your server, with a secret key:

```txt
GET https://strait.link/v1/webhooks/{id}/deliveries?limit=20&cursor=…
Authorization: Bearer st_live_…
```

```json title="Response"
{
  "deliveries": [
    {
      "id": "7f3e2c1a-9b4d-4e8f-a6c5-2d1b0e9f8a73",
      "webhookId": "5d0c…",
      "event": "link.clicked",
      "status": "failed",
      "attempts": 6,
      "lastStatus": 500,
      "lastError": "HTTP 500",
      "nextAttemptAt": null,
      "createdAt": "2026-10-04T09:12:03.512Z",
      "deliveredAt": null
    }
  ],
  "nextCursor": null
}
```

Newest first, `limit` 1 to 100 (default 20); pass `nextCursor` back as `cursor` for the next page. Payloads aren't returned. `nextAttemptAt` is set while a delivery is waiting for a retry.

```txt
POST https://strait.link/v1/webhook-deliveries/{id}/redeliver
Authorization: Bearer st_live_…
```

This queues the delivery again with its attempt count reset, sends it at once to the webhook's **current** URL with the same `X-Strait-Delivery` id, and answers with the delivery after that attempt (same shape as above). If it fails again it gets the full retry schedule. You get `409` when it was already delivered, or while it's being sent (in its first 2 minutes, or claimed by a delivery worker right now): try again shortly. A delivery from another workspace is `404`.

Delivery history is kept for 30 days, then deleted by a nightly job.
