# Webhooks

> Hear about asks, yeses, drafts, deals and posts the moment they happen, instead of polling. Every delivery is signed, so you know it came from us.

## Set up an endpoint

1. Open **Settings → Webhooks** on yapfactory.com.
2. Add an `https` URL and pick the events you want, or all of them (`*`).
3. Copy the signing secret. It starts with `whsec_` and is shown once.
4. Press **Send test event** to get a `ping` and check your code.

You can have up to 5 endpoints. An event goes to the endpoints of everyone on the deal or campaign it's about: the brand and the creator.

- The URL must be public `https`. Addresses on private networks are refused.
- We don't follow redirects: a `3xx` answer counts as a failed try. Give the final URL.
- Endpoints are set up in Settings for now; there's no API for them yet.

## Events

| Type | Sent to | When |
| --- | --- | --- |
| `deal.updated` | Both sides | Every deal status change (`status`, `previousStatus`) |
| `deal.invited` | Creator | A brand invited you |
| `invite.accepted` | Brand | A creator said yes |
| `invite.declined` | Brand | A creator said no |
| `invite.expired` | Both sides | An invite ran out |
| `deal.started` | Both sides | The brand started the deal and payment is secured |
| `draft.submitted` | Brand | A draft or a new version is ready to review |
| `revision.requested` | Creator | The brand sent the draft back |
| `draft.approved` | Both sides | Approved, or approved automatically when the review window ran out |
| `deal.completed` | Both sides | The deal is done |
| `deal.cancelled` | Both sides | The deal was cancelled |
| `ask.received` | Brand | A creator asked to join a campaign |
| `message.received` | The other side | A new message on a deal |
| `campaign.published` | Brand | A campaign went live |
| `post.published` | Brand | A scheduled post went live (`data.postId`, `data.postUrl`) |
| `post.failed` | Brand | A scheduled post stopped and needs the person (`data.postId`, `data.reason`) |
| `ping` | The endpoint | A test event from Settings |

## The payload

Payloads are thin. An event says what changed and carries ids; call the API for the details. A payload never contains a creator's handle or contact details.

```json
{
  "id": "evt_…",
  "type": "deal.updated",
  "createdAt": "2026-12-03T10:00:00.000Z",
  "livemode": true,
  "data": {
    "dealId": "…",
    "campaignId": "…",
    "status": "funded",
    "previousStatus": "accepted",
    "url": "https://yapfactory.com/deals/…"
  }
}
```

- `id` stays the same across retries and replays. Use it to dedupe.
- `livemode` is `false` for events from test sites.
- `data.url` is the page on yapfactory.com for the deal, campaign or post.

### What `data` carries

| Events | `data` |
| --- | --- |
| `deal.updated`, `invite.accepted`, `invite.declined`, `invite.expired`, `deal.started`, `revision.requested`, `draft.approved`, `deal.completed`, `deal.cancelled` | `dealId`, `campaignId`, `status`, `previousStatus`, `url` |
| `deal.invited` | `dealId`, `campaignId`, `status` (`invited`), `url` |
| `draft.submitted` | `dealId`, `campaignId`, `status` (`draft_submitted`), `version` (1 for the first draft), `url` |
| `message.received` | `dealId`, `campaignId`, `status`, `messageId`, `from` (`brand` or `creator`), `url`. The words aren't in the event: read them with [`get_deal`](https://yapfactory.com/developers/api/get_deal.md). |
| `ask.received` | `campaignId`, `status`, `creatorId`, `url` |
| `campaign.published` | `campaignId`, `status` (`live`), `url` |
| `post.published` | `postId`, `postUrl` (the post on TikTok or Instagram, or `null`), `url` |
| `post.failed` | `postId`, `reason` (a sentence for the person), `url` |
| `ping` | `endpointId`, `message` |

One change often sends two events: `deal.updated` for the status change, and the named one (`invite.accepted`, `deal.started`…) for what it means. Subscribe to `deal.updated` alone to follow every status, or to the named ones to act on moments. The statuses are in [Deals and statuses](https://yapfactory.com/developers/statuses.md). New fields and event types can be added at any time: ignore what you don't know.

## Headers

Each delivery is a `POST` with `Content-Type: application/json` and these headers:

| Header | Value |
| --- | --- |
| `Yap-Event-Id` | The event's `id`, such as `evt_…`. |
| `Yap-Event-Type` | The event's `type`, such as `draft.submitted`. |
| `Yap-Signature` | `t=<unix seconds>,v1=<hex HMAC-SHA256>` |

## Check the signature

1. Read `t` and `v1` from `Yap-Signature`.
2. Reject it if `t` is more than 5 minutes from now. That stops replays.
3. Compute HMAC-SHA256 of `"<t>.<raw body>"` with your secret, as hex.
4. Compare it with `v1` in constant time.

> Use the raw body, byte for byte. Parsing the JSON and writing it out again changes it, and the check fails.

Node:

```js
import crypto from "node:crypto";

const TOLERANCE_S = 5 * 60;

/** rawBody: the request body exactly as it arrived, before any JSON parsing. */
export function verifyYapSignature(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=", 2)));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > TOLERANCE_S) return false;
  const expected = crypto.createHmac("sha256", secret).update(`${t}.${rawBody}`).digest("hex");
  const given = Buffer.from(parts.v1 ?? "", "utf8");
  const want = Buffer.from(expected, "utf8");
  return given.length === want.length && crypto.timingSafeEqual(given, want);
}

// Express: keep the raw body for this route.
app.post("/webhooks/yap", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body.toString("utf8");
  if (!verifyYapSignature(raw, req.get("Yap-Signature") ?? "", process.env.YAP_WEBHOOK_SECRET)) {
    return res.status(400).end();
  }
  const event = JSON.parse(raw);
  // Seen event.id before? Answer 200 and stop.
  res.status(200).end();
  queueWork(event); // do the slow part after answering
});
```

Python:

```python
import hashlib, hmac, json, os, time

TOLERANCE_S = 5 * 60

def verify_yap_signature(raw_body: bytes, header: str, secret: str) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    try:
        t = int(parts.get("t", ""))
    except ValueError:
        return False
    if abs(time.time() - t) > TOLERANCE_S:
        return False
    signed = f"{t}.".encode() + raw_body
    expected = hmac.new(secret.encode(), signed, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts.get("v1", ""))

# Flask
@app.post("/webhooks/yap")
def yap_webhook():
    raw = request.get_data()  # the raw bytes, before parsing
    if not verify_yap_signature(raw, request.headers.get("Yap-Signature", ""), os.environ["YAP_WEBHOOK_SECRET"]):
        return "", 400
    event = json.loads(raw)
    # Seen event["id"] before? Answer 200 and stop.
    return "", 200
```

Go:

```go
package webhooks

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

const tolerance = 5 * time.Minute

// VerifyYapSignature checks the Yap-Signature header against the raw request body.
func VerifyYapSignature(rawBody []byte, header, secret string) bool {
	var ts, sig string
	for _, part := range strings.Split(header, ",") {
		k, v, ok := strings.Cut(part, "=")
		if !ok {
			continue
		}
		switch k {
		case "t":
			ts = v
		case "v1":
			sig = v
		}
	}
	t, err := strconv.ParseInt(ts, 10, 64)
	if err != nil || math.Abs(float64(time.Now().Unix()-t)) > tolerance.Seconds() {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(ts + "."))
	mac.Write(rawBody)
	expected := hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(expected), []byte(sig))
}
```

## Answer fast

Any `2xx` within 10 seconds counts as delivered. Answer first, then do the slow work in the background. Anything else, or no answer, is a failed try.

## Retries

A failed delivery is tried again after 1 minute, 5 minutes, 30 minutes, 2 hours, 6 hours and 12 hours: 7 tries in about 21 hours. After that it's marked `failed`.

After 20 deliveries fail in a row, we turn the endpoint off and email you.

Retries can arrive out of order, and the same event can arrive twice. Dedupe on `Yap-Event-Id`, and read the current state from the API when order matters.

## Delivery log, replay and test events

- **Settings → Webhooks** shows the last 50 deliveries for each endpoint: status, tries and the response code you sent.
- **Replay** any delivery. It's signed again with a fresh `t`, and keeps the same event id.
- **Send test event** sends a `ping`, to check your endpoint and your signature code.

---

HTML version: https://yapfactory.com/developers/webhooks
