# React to orders on your servers

anyshop tells your servers when something happens in your store: a payment confirmed, an order delivered, a refund, a dispute, low stock, a license activated. Every event is signed, sent again until your server takes it, and kept for 30 days.

- 6 event types
- Standard Webhooks
- Retries for 3 days

API key scopes used: `webhooks:write` (live key), `webhooks:read` (live key).

## Events

Each event is one JSON body, `{ "type", "timestamp", "data" }`, where `data` is the object it is about. Subscribe an endpoint to a list of types, or to `"all"` for these and any added later.

| type | When | data |
| --- | --- | --- |
| `order.paid` | The payment is confirmed (for a bank debit, once the money clears) | The order: number, total, buyer's email, items (each with `answers`, the buyer's answers to the product's questions), what paid it, `terms_agreement` (when and where the buyer agreed to the terms of sale), and `withdrawal_consent` when the buyer asked for it right away, with the sentence that confirms it (`confirmation_text`) for a store that emails its buyers itself |
| `order.fulfilled` | Everything in the order is delivered | The order, with each item's delivery state and `answers` |
| `order.refunded` | A refund, full or partial | The order, the refund's amount, the refunded total |
| `dispute.created` | A buyer disputed a payment | The dispute: order, reason, amount, respond by |
| `stock.low` | A product's stock drops below your alert level, once a day at most (per option, for stock per option) | The product, what is available, the level, the option (`variant`, or null) |
| `license.activated` | A device activated a license | The license, its product, devices used and allowed, the activation |

Amounts are integers in minor units, and times ISO 8601 in UTC, as everywhere in the API.

An order item's `answers` are the buyer's answers to the product's questions for the buyer at checkout, as the [order](https://docs.anyshop.io/reference.md#questions-for-the-buyer) has them: `[{ "question_id", "question", "kind", "answer" }]`, empty when the product asks nothing. They are in the event's body like the buyer's email, kept by anyshop with the event for 30 days so a failed send can be retried, and emptied from those records when the buyer's data is deleted. They never go in an email.

## Add an endpoint (live key)

The address must be public https: anyshop never follows redirects or calls private networks, and waits 15 seconds for an answer. The secret in the answer is shown once; keep it with your server's other secrets. You can also add endpoints in the dashboard, under Developers, Webhooks, where **Send a sample event** on an endpoint's page sends it one signed event to check your code against.

curl:

```bash
curl https://api.anyshop.io/v1/webhook_endpoints \
  -H "Authorization: Bearer $ANYSHOP_LIVE_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://example.com/anyshop",
    "events": ["order.paid", "order.refunded", "dispute.created"]
  }'
```

Node:

```js
const response = await fetch("https://api.anyshop.io/v1/webhook_endpoints", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.ANYSHOP_LIVE_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    url: "https://example.com/anyshop",
    events: ["order.paid", "order.refunded", "dispute.created"],
  }),
});
const endpoint = await response.json(); // endpoint.secret.value, shown once
```

Python:

```python
import os
import requests

response = requests.post(
    "https://api.anyshop.io/v1/webhook_endpoints",
    headers={"Authorization": f"Bearer {os.environ['ANYSHOP_LIVE_KEY']}"},
    json={
        "url": "https://example.com/anyshop",
        "events": ["order.paid", "order.refunded", "dispute.created"],
    },
)
endpoint = response.json()  # endpoint["secret"]["value"], shown once
```

## Verify signatures

Deliveries follow [Standard Webhooks](https://www.standardwebhooks.com), so its libraries for most languages verify them. Every request carries three headers:

| Header | What it holds |
| --- | --- |
| `webhook-id` | The event's ID, the same on every retry: do the work once per ID |
| `webhook-timestamp` | When this attempt was signed, in Unix seconds |
| `webhook-signature` | `v1,` and the signature; during a secret rotation, two of them separated by a space |

The signed content is the ID, the timestamp and the raw body joined by dots. Verify against the body exactly as it arrived, before any JSON parsing, and refuse timestamps more than 5 minutes away from your clock: the libraries do both.

Node (server.js):

```js
import express from "express";
import { Webhook } from "standardwebhooks";

const webhook = new Webhook(process.env.ANYSHOP_WEBHOOK_SECRET); // whsec_...
const app = express();

app.post("/anyshop", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = webhook.verify(req.body, req.headers);
  } catch {
    return res.sendStatus(400);
  }
  res.sendStatus(204); // answer first, then work
  await queue.add(req.headers["webhook-id"], event);
});
```

Python (server.py):

```python
import os
from flask import Flask, request
from standardwebhooks.webhooks import Webhook

webhook = Webhook(os.environ["ANYSHOP_WEBHOOK_SECRET"])  # whsec_...
app = Flask(__name__)

@app.post("/anyshop")
def anyshop():
    try:
        event = webhook.verify(request.get_data(), dict(request.headers))
    except Exception:
        return "", 400
    queue.add(request.headers["webhook-id"], event)  # the work happens elsewhere
    return "", 204
```

> **No library for your language?** Compute HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{body}` with the secret's bytes (the part after `whsec_`, base64 decoded), base64 encode it, and compare it in constant time with each `v1,` signature in the header.

## Answer quickly

Any 2xx within 15 seconds marks the delivery done; anything else, a timeout or no connection is a failure, tried again later. Put the event on a queue and answer, then do the work. Because a retry can arrive after your server did the work but before its answer got through, handle each `webhook-id` once.

## Retries

A failed delivery is tried again 5 seconds later, then after 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours, 10 hours, 24 hours and 24 hours: 10 attempts over about 3 days, each wait up to 20% shorter or longer at random so a recovering server is not hit all at once. A `Retry-After` header in your answer is honored, up to 24 hours. Every attempt has the same `webhook-id` and a fresh timestamp and signature.

- An endpoint failing for 24 hours: you get one email.
- Failing for 5 days: the endpoint is disabled, and you get another.
- Answering `410 Gone`: the endpoint is disabled at once, as asked.

Pause an endpoint while you deploy with `PATCH /v1/webhook_endpoints/{id}` and `"status": "paused"`: events wait for it, and go out when you set it back to `enabled`. The same call enables a disabled endpoint again.

## Replays

Nothing is lost while your server is down. In the dashboard, under Developers, Webhooks, each endpoint has its delivery log and three ways back:

- **Replay now** sends one delivery again, whatever its state.
- **Recover since** starts the schedule again for every failed delivery since a time you choose.
- **Replay missing** sends the events of the endpoint's types that it never got, such as those from while it was disabled or before you added a type to it.

Your server can also catch up on its own: `GET /v1/events` lists everything that happened in your store in the last 30 days, newest first, whether or not an endpoint received it, and `GET /v1/events/{id}` fetches one by its `webhook-id`.

curl:

```bash
curl "https://api.anyshop.io/v1/events?type=order.paid&limit=100" \
  -H "Authorization: Bearer $ANYSHOP_LIVE_KEY"
```

## Rotate the secret

`POST /v1/webhook_endpoints/{id}/rotate_secret` returns a new secret, once. For the next 24 hours every delivery is signed with both, so deploy the new secret whenever it suits you within the day; a server with either one keeps accepting deliveries.

curl:

```bash
curl -X POST \
  https://api.anyshop.io/v1/webhook_endpoints/whe_01m3rs9d2f4k6m8p0r2t4v6x8z/rotate_secret \
  -H "Authorization: Bearer $ANYSHOP_LIVE_KEY"
```

## Ed25519 signatures

Create an endpoint with `"signing": "ed25519"` when the servers that verify should not hold a secret that can also sign. anyshop keeps the private key; your server gets the public key, `whpk_...`, and signatures start with `v1a,`. Standard Webhooks libraries that support asymmetric signatures verify them the same way.

## See it work

Send a sample event from the endpoint's page in Developers, Webhooks to check your signature code. Once anyshop has approved your store, buy once with your own email and refund it: your server hears order.paid, then order.refunded.

[Next: check licenses in your app](https://docs.anyshop.io/guides/licenses.md)
