---
title: Receive order webhooks
description: Build a small web server that Nurish'd calls when an order changes, check that each call is genuine, and update your own records.
section: Tutorials
order: 5
---

# Receive order webhooks

You will build a small web server. Nurish'd calls it when an order is created, paid, fulfilled, shipped, delivered, refunded or canceled. The server checks that the call really came from Nurish'd, reads the order, and updates its own records.

A webhook is an HTTP request that Nurish'd sends to your server when something happens. The request body is a thin event. It names the order but does not contain it. Your server then reads the order with the API. See [Events](/docs/events/events) for the event object.

## Before you start

- You finished [Set up your project](/docs/tutorials/set-up-your-project). Your project has the `nurishd` client file and a Sandbox key in `NURISHD_API_KEY`.
- Your key has the scope `order:read`. It is needed to read orders and to choose order events. Run `check_key` from the setup tutorial to see your scopes.
- Install the web server package for your language.

| Language   | Command                                                                  |
| ---------- | ------------------------------------------------------------------------ |
| Python     | `pip install flask`                                                      |
| JavaScript | `npm install express`                                                    |
| TypeScript | `npm install express` and `npm install --save-dev @types/express`        |
| Java       | Replace `pom.xml` with the one below. It adds Javalin and a log package. |

Java only. This `pom.xml` is the one from the setup tutorial plus two dependencies. Javalin is the web server and `slf4j-simple` prints its logs.

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- file: pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>nurishd-tutorial</artifactId>
  <version>1.0.0</version>

  <properties>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.17.2</version>
    </dependency>
    <dependency>
      <groupId>io.javalin</groupId>
      <artifactId>javalin</artifactId>
      <version>6.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>2.0.16</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>3.4.1</version>
      </plugin>
    </plugins>
  </build>
</project>
```

## 1. Settings and records

Steps 1 to 3 build one server file, piece by piece. The complete file is in "The whole program" at the end.

The server needs the signing secret, a table that says what each event means, and two places to keep state. A signing secret is a value that only you and Nurish'd know. Nurish'd uses it to sign every call. You get it in step 5.

`orders` holds your records. `handled` holds the ids of events you already handled. Both live in memory here. A real app keeps them in its database, so they survive a restart.

```python
SECRET = os.environ["NURISHD_WEBHOOK_SECRET"]
TOLERANCE_SECONDS = 300

# What each order event means in your own records.
STATUS = {
    "order.created": "received",
    "order.paid": "confirmed",
    "order.fulfilled": "fulfilled",
    "order.shipped": "shipped",
    "order.delivered": "delivered",
    "order.refunded": "refunded",
    "order.canceled": "canceled",
}

orders = {}  # order id -> {"status": ..., "delivery_date": ...}
handled = set()  # ids of events you already handled
```

```javascript
const SECRET = process.env.NURISHD_WEBHOOK_SECRET;
if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.');
const TOLERANCE_SECONDS = 300;

// What each order event means in your own records.
const STATUS = {
	'order.created': 'received',
	'order.paid': 'confirmed',
	'order.fulfilled': 'fulfilled',
	'order.shipped': 'shipped',
	'order.delivered': 'delivered',
	'order.refunded': 'refunded',
	'order.canceled': 'canceled',
};

const orders = new Map(); // order id -> { status, deliveryDate }
const handled = new Set(); // ids of events you already handled
```

```typescript
const SECRET = process.env.NURISHD_WEBHOOK_SECRET;
if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.');
const TOLERANCE_SECONDS = 300;

interface WebhookEvent {
	id: string;
	type: string;
	data: { id: string };
}

interface Order {
	order_delivery_date: string;
}

// What each order event means in your own records.
const STATUS: Record<string, string> = {
	'order.created': 'received',
	'order.paid': 'confirmed',
	'order.fulfilled': 'fulfilled',
	'order.shipped': 'shipped',
	'order.delivered': 'delivered',
	'order.refunded': 'refunded',
	'order.canceled': 'canceled',
};

const orders = new Map<string, { status: string; deliveryDate: string }>(); // order id -> your record
const handled = new Set<string>(); // ids of events you already handled
```

```java
    private static final String SECRET = System.getenv("NURISHD_WEBHOOK_SECRET");
    private static final long TOLERANCE_SECONDS = 300;

    // What each order event means in your own records.
    private static final Map<String, String> STATUS = Map.of(
            "order.created", "received",
            "order.paid", "confirmed",
            "order.fulfilled", "fulfilled",
            "order.shipped", "shipped",
            "order.delivered", "delivered",
            "order.refunded", "refunded",
            "order.canceled", "canceled");

    // order id -> status and delivery date
    private static final Map<String, Map<String, String>> orders = new ConcurrentHashMap<>();
    // ids of events you already handled
    private static final Set<String> handled = ConcurrentHashMap.newKeySet();
```

## 2. Check the signature

Anyone can send a request to your address. The signature is how you know Nurish'd sent it. Each call has a `Nurishd-Signature` header. The header holds a time `t` and a signature `v1`. The signature is an HMAC-SHA256 of the text `t`, a dot, and the body. HMAC is a way to sign text with a secret.

To check it, you build the same signature with your secret and compare. The function below also refuses a call that is more than five minutes old, so nobody can replay an old call. The comparison takes the same time whatever the input, which stops timing attacks. The [Verifying signatures](/docs/events/verifying-signatures) guide explains each step.

The signature covers the exact bytes of the body. If you parse the JSON first and write it out again, the bytes can change and the check fails. So the server must read the raw body. Each framework gives it to you in a different way.

- Flask: `request.get_data()`
- Express: `express.raw({ type: 'application/json' })` in front of the route
- Javalin: `ctx.bodyAsBytes()`

```python
def verify_signature(raw_body, header, secret):
    """Returns True if the request came from Nurish'd and is fresh."""
    if not header:
        return False

    timestamp = None
    signatures = []
    for part in header.split(","):
        key, found, value = part.partition("=")
        if not found:
            continue
        key, value = key.strip(), value.strip()
        if key == "t":
            timestamp = value
        elif key == "v1":
            signatures.append(value)
    if timestamp is None or not timestamp.isdigit() or not signatures:
        return False

    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(
        secret.encode("utf-8"),
        timestamp.encode("utf-8") + b"." + raw_body,
        hashlib.sha256,
    ).hexdigest()
    return any(hmac.compare_digest(expected, s.lower()) for s in signatures)
```

```javascript
/** Returns true if the request came from Nurish'd and is fresh. */
function verifySignature(rawBody, header, secret) {
	if (!header) return false;

	let timestamp = null;
	const signatures = [];
	for (const part of header.split(',')) {
		const index = part.indexOf('=');
		if (index === -1) continue;
		const key = part.slice(0, index).trim();
		const value = part.slice(index + 1).trim();
		if (key === 't') timestamp = value;
		if (key === 'v1') signatures.push(value);
	}
	if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0)
		return false;

	const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
	if (age > TOLERANCE_SECONDS) return false;

	const expected = crypto
		.createHmac('sha256', secret)
		.update(Buffer.concat([Buffer.from(`${timestamp}.`), rawBody]))
		.digest();
	return signatures.some((signature) => {
		if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
		return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected);
	});
}
```

```typescript
/** Returns true if the request came from Nurish'd and is fresh. */
function verifySignature(
	rawBody: Buffer,
	header: string | undefined,
	secret: string,
): boolean {
	if (!header) return false;

	let timestamp: string | null = null;
	const signatures: string[] = [];
	for (const part of header.split(',')) {
		const index = part.indexOf('=');
		if (index === -1) continue;
		const key = part.slice(0, index).trim();
		const value = part.slice(index + 1).trim();
		if (key === 't') timestamp = value;
		if (key === 'v1') signatures.push(value);
	}
	if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0)
		return false;

	const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
	if (age > TOLERANCE_SECONDS) return false;

	const expected = crypto
		.createHmac('sha256', secret)
		.update(Buffer.concat([Buffer.from(`${timestamp}.`), rawBody]))
		.digest();
	return signatures.some((signature) => {
		if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
		return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected);
	});
}
```

```java
    /** Returns true if the request came from Nurish'd and is fresh. */
    static boolean verifySignature(byte[] rawBody, String header, String secret)
            throws GeneralSecurityException {
        if (header == null) return false;

        String timestamp = null;
        List<String> signatures = new ArrayList<>();
        for (String part : header.split(",")) {
            int index = part.indexOf('=');
            if (index == -1) continue;
            String key = part.substring(0, index).trim();
            String value = part.substring(index + 1).trim();
            if (key.equals("t")) timestamp = value;
            if (key.equals("v1")) signatures.add(value);
        }
        if (timestamp == null || !timestamp.matches("\\d{1,12}") || signatures.isEmpty()) {
            return false;
        }

        long age = Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(timestamp));
        if (age > TOLERANCE_SECONDS) return false;

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
        byte[] expected = mac.doFinal(rawBody);

        for (String signature : signatures) {
            if (!signature.matches("[0-9a-fA-F]{64}")) continue;
            if (MessageDigest.isEqual(HexFormat.of().parseHex(signature), expected)) return true;
        }
        return false;
    }
```

## 3. The route

The route answers `POST /webhooks/nurishd`. It does five things in order.

1. Read the raw body and check the signature. Answer `400` if the check fails, and do nothing else.
2. Ignore an event whose id is in `handled`. Nurish'd can send the same event more than once, and a repeat must do no harm.
3. For an order event, read the order with `GET /meals/v1/order/{order_id}/get/document`. Save the new status and the delivery date in `orders`. The event carries the order id in `data.id`.
4. Add the event id to `handled`.
5. Answer `200`.

An event of another type, such as `ping`, is ignored and answered with `200`. If the order read fails with a `429` or a `5xx`, the route answers `500` so that Nurish'd sends the event again. Other errors, such as a `404` for an order your key cannot read, cannot be fixed by a retry. The route prints them and answers `200`.

A `2xx` answer means success. Any other answer, a timeout or a connection error is a failure, and Nurish'd sends the event again with growing waits for up to three days. Nurish'd does not follow redirects. Answer fast. Here the route reads one order before it answers. A larger app answers first and does the work after, from a queue.

```python
@app.post("/webhooks/nurishd")
def receive():
    # 1. Read the raw bytes and check the signature before anything else.
    raw_body = request.get_data()
    if not verify_signature(raw_body, request.headers.get("Nurishd-Signature"), SECRET):
        print("refused: bad signature")
        return "", 400

    # 2. Ignore an event you already handled.
    event = json.loads(raw_body)
    if event["id"] in handled:
        print("ignored: already handled", event["id"])
        return "", 200

    # 3. For an order event, read the order and update your records.
    if event["type"] in STATUS:
        order_id = event["data"]["id"]
        try:
            order = call("GET", f"/meals/v1/order/{order_id}/get/document")
            orders[order_id] = {
                "status": STATUS[event["type"]],
                "delivery_date": order["order_delivery_date"],
            }
            print(event["type"], order_id, "->", orders[order_id]["status"])
        except NurishdError as error:
            if error.status == 429 or error.status >= 500:
                return "", 500  # Nurish'd sends the event again later.
            print("cannot read order:", order_id, error.code)
    else:
        print("ignored type:", event["type"])

    # 4. Remember the event and answer.
    handled.add(event["id"])
    return "", 200
```

```javascript
const app = express();

app.post(
	'/webhooks/nurishd',
	// 1. Keep the body as raw bytes.
	express.raw({ type: 'application/json' }),
	async (req, res) => {
		// 2. Check the signature before anything else.
		if (!verifySignature(req.body, req.get('Nurishd-Signature'), SECRET)) {
			console.log('refused: bad signature');
			return res.sendStatus(400);
		}

		// 3. Ignore an event you already handled.
		const event = JSON.parse(req.body.toString('utf8'));
		if (handled.has(event.id)) {
			console.log('ignored: already handled', event.id);
			return res.sendStatus(200);
		}

		// 4. For an order event, read the order and update your records.
		if (event.type in STATUS) {
			const orderId = event.data.id;
			try {
				const order = await call(
					'GET',
					`/meals/v1/order/${orderId}/get/document`,
				);
				orders.set(orderId, {
					status: STATUS[event.type],
					deliveryDate: order.order_delivery_date,
				});
				console.log(
					event.type,
					orderId,
					'->',
					orders.get(orderId).status,
				);
			} catch (error) {
				if (!(error instanceof NurishdError)) throw error;
				if (error.status === 429 || error.status >= 500) {
					return res.sendStatus(500); // Nurish'd sends the event again later.
				}
				console.log('cannot read order:', orderId, error.code);
			}
		} else {
			console.log('ignored type:', event.type);
		}

		// 5. Remember the event and answer.
		handled.add(event.id);
		res.sendStatus(200);
	},
);
```

```typescript
const app = express();

app.post(
	'/webhooks/nurishd',
	// 1. Keep the body as raw bytes.
	express.raw({ type: 'application/json' }),
	async (req, res) => {
		// 2. Check the signature before anything else.
		if (!verifySignature(req.body, req.get('Nurishd-Signature'), SECRET)) {
			console.log('refused: bad signature');
			return res.sendStatus(400);
		}

		// 3. Ignore an event you already handled.
		const event = JSON.parse(req.body.toString('utf8')) as WebhookEvent;
		if (handled.has(event.id)) {
			console.log('ignored: already handled', event.id);
			return res.sendStatus(200);
		}

		// 4. For an order event, read the order and update your records.
		if (event.type in STATUS) {
			const orderId = event.data.id;
			try {
				const order = await call<Order>(
					'GET',
					`/meals/v1/order/${orderId}/get/document`,
				);
				orders.set(orderId, {
					status: STATUS[event.type],
					deliveryDate: order.order_delivery_date,
				});
				console.log(
					event.type,
					orderId,
					'->',
					orders.get(orderId)?.status,
				);
			} catch (error) {
				if (!(error instanceof NurishdError)) throw error;
				if (error.status === 429 || error.status >= 500) {
					return res.sendStatus(500); // Nurish'd sends the event again later.
				}
				console.log('cannot read order:', orderId, error.code);
			}
		} else {
			console.log('ignored type:', event.type);
		}

		// 5. Remember the event and answer.
		handled.add(event.id);
		res.sendStatus(200);
	},
);
```

```java
        app.post("/webhooks/nurishd", ctx -> {
            // 1. Read the raw bytes and check the signature before anything else.
            byte[] rawBody = ctx.bodyAsBytes();
            if (!verifySignature(rawBody, ctx.header("Nurishd-Signature"), SECRET)) {
                System.out.println("refused: bad signature");
                ctx.status(400);
                return;
            }

            // 2. Ignore an event you already handled.
            JsonNode event = Nurishd.JSON.readTree(rawBody);
            String eventId = event.path("id").asText();
            String type = event.path("type").asText();
            if (handled.contains(eventId)) {
                System.out.println("ignored: already handled " + eventId);
                ctx.status(200);
                return;
            }

            // 3. For an order event, read the order and update your records.
            if (STATUS.containsKey(type)) {
                String orderId = event.path("data").path("id").asText();
                try {
                    JsonNode order = Nurishd.call(
                            "GET", "/meals/v1/order/%s/get/document".formatted(orderId));
                    orders.put(orderId, Map.of(
                            "status", STATUS.get(type),
                            "deliveryDate", order.path("order_delivery_date").asText()));
                    System.out.println(type + " " + orderId + " -> " + STATUS.get(type));
                } catch (Nurishd.NurishdException error) {
                    if (error.status == 429 || error.status >= 500) {
                        ctx.status(500); // Nurish'd sends the event again later.
                        return;
                    }
                    System.out.println("cannot read order: " + orderId + " " + error.code);
                }
            } else {
                System.out.println("ignored type: " + type);
            }

            // 4. Remember the event and answer.
            handled.add(eventId);
            ctx.status(200);
        });
```

## 4. Get a public address

Nurish'd cannot call `localhost`. While you build, a tunnel tool gives your computer a public HTTPS address that forwards to your server. Two common ones are ngrok and Cloudflare Tunnel. Follow their own setup guides, then start a tunnel to port 3000.

- ngrok: `ngrok http 3000`
- Cloudflare Tunnel: `cloudflared tunnel --url http://localhost:3000`

The tool prints an address such as `https://example-name.trycloudflare.com`. Your webhook URL is that address plus `/webhooks/nurishd`. The URL must use `https`, have no user name or password and no fragment, and must not be `localhost` or a private IP address. See [Webhooks](/docs/events/webhooks).

## 5. Register the endpoint

An endpoint tells Nurish'd where to send events. You can add one in the console, on the **Webhooks** page. This script does the same with `POST /developer/v1/webhook-endpoint/create/document`. It asks for the seven order events and prints the signing secret.

Save the file for your language. For Java, save it as `src/main/java/tutorial/RegisterEndpoint.java`.

```python
# file: register_endpoint.py
import sys

from nurishd import call

# Run: python register_endpoint.py https://your-address.example.com/webhooks/nurishd
url = sys.argv[1]

created = call(
    "POST",
    "/developer/v1/webhook-endpoint/create/document",
    body={
        "url": url,
        "events": [
            "order.created",
            "order.paid",
            "order.fulfilled",
            "order.shipped",
            "order.delivered",
            "order.refunded",
            "order.canceled",
        ],
        "description": "Order updates",
    },
)
print("endpoint:", created["endpoint"]["endpoint_id"])
print("secret:", created["secret"])
```

```javascript
// file: register-endpoint.js
import { call } from './nurishd.js';

// Run: node register-endpoint.js https://your-address.example.com/webhooks/nurishd
const url = process.argv[2];

const created = await call(
	'POST',
	'/developer/v1/webhook-endpoint/create/document',
	{
		body: {
			url,
			events: [
				'order.created',
				'order.paid',
				'order.fulfilled',
				'order.shipped',
				'order.delivered',
				'order.refunded',
				'order.canceled',
			],
			description: 'Order updates',
		},
	},
);
console.log('endpoint:', created.endpoint.endpoint_id);
console.log('secret:', created.secret);
```

```typescript
// file: register-endpoint.ts
import { call } from './nurishd.ts';

interface Created {
	endpoint: { endpoint_id: string };
	secret: string;
}

// Run: node register-endpoint.ts https://your-address.example.com/webhooks/nurishd
const url = process.argv[2];

const created = await call<Created>(
	'POST',
	'/developer/v1/webhook-endpoint/create/document',
	{
		body: {
			url,
			events: [
				'order.created',
				'order.paid',
				'order.fulfilled',
				'order.shipped',
				'order.delivered',
				'order.refunded',
				'order.canceled',
			],
			description: 'Order updates',
		},
	},
);
console.log('endpoint:', created.endpoint.endpoint_id);
console.log('secret:', created.secret);
```

```java
// file: src/main/java/tutorial/RegisterEndpoint.java
package tutorial;

import com.fasterxml.jackson.databind.JsonNode;
import java.util.List;
import java.util.Map;

public class RegisterEndpoint {
    // Run with -Dexec.args="https://your-address.example.com/webhooks/nurishd"
    public static void main(String[] args) {
        Map<String, Object> body = Map.of(
                "url", args[0],
                "events", List.of(
                        "order.created",
                        "order.paid",
                        "order.fulfilled",
                        "order.shipped",
                        "order.delivered",
                        "order.refunded",
                        "order.canceled"),
                "description", "Order updates");

        JsonNode created =
                Nurishd.call("POST", "/developer/v1/webhook-endpoint/create/document", Map.of(), body);
        System.out.println("endpoint: " + created.path("endpoint").path("endpoint_id").asText());
        System.out.println("secret: " + created.path("secret").asText());
    }
}
```

Run it with your webhook URL.

- Python: `python register_endpoint.py https://example-name.trycloudflare.com/webhooks/nurishd`
- JavaScript: `node register-endpoint.js https://example-name.trycloudflare.com/webhooks/nurishd`
- TypeScript: `node register-endpoint.ts https://example-name.trycloudflare.com/webhooks/nurishd`
- Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.RegisterEndpoint -Dexec.args="https://example-name.trycloudflare.com/webhooks/nurishd"`

It prints this. The ids and the secret differ.

```text
endpoint: endpoint-d223baf1
secret: nk-whsec-08812f306d0f7cfd84a4bc495b94c19b625f72ab381cb96ff3e915cb0838a1c5
```

The secret is in the answer of the create call. Copy it now and keep it private like an API key. You can read it again in the console. Put it in a variable.

macOS and Linux:

```bash
export NURISHD_WEBHOOK_SECRET="nk-whsec-your-secret-here"
```

Windows PowerShell:

```powershell
$env:NURISHD_WEBHOOK_SECRET = "nk-whsec-your-secret-here"
```

## 6. Run the server

Save the server for your language as `webhook.py`, `webhook.js`, `webhook.ts` or `src/main/java/tutorial/Webhook.java`. The complete files are in "The whole program". Start it in a terminal where `NURISHD_API_KEY` and `NURISHD_WEBHOOK_SECRET` are set.

- Python: `python webhook.py`
- JavaScript: `node webhook.js`
- TypeScript: `node webhook.ts`, or `npx tsx webhook.ts` on Node older than 22.18
- Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.Webhook`

The server listens on port 3000. To use another port, set the `PORT` variable and start the tunnel on that port. Leave the server running. Stop it with Ctrl+C.

## 7. Test it with Nurish'd

In the console, open **Webhooks**, select your endpoint and select **Send test event**. Nurish'd sends a signed `ping` event. It is not an order event, so your server checks the signature and ignores it. The server prints this.

```text
ignored type: ping
```

If the console shows the delivery as failed, see "If something goes wrong".

## 8. Test it without Nurish'd

You can test the server without Nurish'd. This script builds a signed event the same way Nurish'd does and sends it to `localhost`. It sends four requests: a correct one, the same event again, one whose body was changed after signing, and one signed ten minutes ago.

Save the file for your language. For Java, save it as `src/main/java/tutorial/SendTest.java`.

```python
# file: send_test.py
import hashlib
import hmac
import json
import os
import sys
import time

import requests

SECRET = os.environ["NURISHD_WEBHOOK_SECRET"]
URL = f"http://localhost:{os.environ.get('PORT', '3000')}/webhooks/nurishd"

# Run: python send_test.py ORDER_ID
order_id = sys.argv[1] if len(sys.argv) > 1 else "ORD-EXAMPLE-0001"


def sign(timestamp, body):
    """Builds a Nurishd-Signature value the way Nurish'd does."""
    message = str(timestamp).encode("utf-8") + b"." + body
    digest = hmac.new(SECRET.encode("utf-8"), message, hashlib.sha256).hexdigest()
    return f"t={timestamp},v1={digest}"


def send(label, body, signature):
    res = requests.post(
        URL,
        data=body,
        headers={"Content-Type": "application/json", "Nurishd-Signature": signature},
        timeout=10,
    )
    print(label, res.status_code)


now = int(time.time())
event = {
    "id": f"evt_test_{now}",
    "type": "order.paid",
    "created": "2026-04-01T15:06:30Z",
    "mode": "test",
    "data": {"object": "order", "id": order_id, "order": order_id, "customer": "customer-0001"},
}
body = json.dumps(event, separators=(",", ":")).encode("utf-8")

send("signed event:", body, sign(now, body))
send("same event again:", body, sign(now, body))
send("changed body:", body.replace(b"order.paid", b"order.canceled"), sign(now, body))
send("old timestamp:", body, sign(now - 600, body))
```

```javascript
// file: send-test.js
import crypto from 'node:crypto';

const SECRET = process.env.NURISHD_WEBHOOK_SECRET;
if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.');
const URL = `http://localhost:${process.env.PORT ?? 3000}/webhooks/nurishd`;

// Run: node send-test.js ORDER_ID
const orderId = process.argv[2] ?? 'ORD-EXAMPLE-0001';

/** Builds a Nurishd-Signature value the way Nurish'd does. */
function sign(timestamp, body) {
	const digest = crypto
		.createHmac('sha256', SECRET)
		.update(`${timestamp}.${body}`)
		.digest('hex');
	return `t=${timestamp},v1=${digest}`;
}

async function send(label, body, signature) {
	const res = await fetch(URL, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			'Nurishd-Signature': signature,
		},
		body,
	});
	console.log(label, res.status);
}

const now = Math.floor(Date.now() / 1000);
const body = JSON.stringify({
	id: `evt_test_${now}`,
	type: 'order.paid',
	created: '2026-04-01T15:06:30Z',
	mode: 'test',
	data: {
		object: 'order',
		id: orderId,
		order: orderId,
		customer: 'customer-0001',
	},
});

await send('signed event:', body, sign(now, body));
await send('same event again:', body, sign(now, body));
await send(
	'changed body:',
	body.replace('order.paid', 'order.canceled'),
	sign(now, body),
);
await send('old timestamp:', body, sign(now - 600, body));
```

```typescript
// file: send-test.ts
import crypto from 'node:crypto';

const SECRET = process.env.NURISHD_WEBHOOK_SECRET;
if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.');
const URL = `http://localhost:${process.env.PORT ?? 3000}/webhooks/nurishd`;

// Run: node send-test.ts ORDER_ID
const orderId = process.argv[2] ?? 'ORD-EXAMPLE-0001';

/** Builds a Nurishd-Signature value the way Nurish'd does. */
function sign(timestamp: number, body: string): string {
	const digest = crypto
		.createHmac('sha256', SECRET as string)
		.update(`${timestamp}.${body}`)
		.digest('hex');
	return `t=${timestamp},v1=${digest}`;
}

async function send(label: string, body: string, signature: string) {
	const res = await fetch(URL, {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json',
			'Nurishd-Signature': signature,
		},
		body,
	});
	console.log(label, res.status);
}

const now = Math.floor(Date.now() / 1000);
const body = JSON.stringify({
	id: `evt_test_${now}`,
	type: 'order.paid',
	created: '2026-04-01T15:06:30Z',
	mode: 'test',
	data: {
		object: 'order',
		id: orderId,
		order: orderId,
		customer: 'customer-0001',
	},
});

await send('signed event:', body, sign(now, body));
await send('same event again:', body, sign(now, body));
await send(
	'changed body:',
	body.replace('order.paid', 'order.canceled'),
	sign(now, body),
);
await send('old timestamp:', body, sign(now - 600, body));
```

```java
// file: src/main/java/tutorial/SendTest.java
package tutorial;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.HexFormat;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class SendTest {
    static final String SECRET = System.getenv("NURISHD_WEBHOOK_SECRET");
    static final String URL =
            "http://localhost:" + System.getenv().getOrDefault("PORT", "3000") + "/webhooks/nurishd";

    /** Builds a Nurishd-Signature value the way Nurish'd does. */
    static String sign(long timestamp, String body) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] digest = mac.doFinal((timestamp + "." + body).getBytes(StandardCharsets.UTF_8));
        return "t=" + timestamp + ",v1=" + HexFormat.of().formatHex(digest);
    }

    static void send(String label, String body, String signature) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create(URL))
                .header("Content-Type", "application/json")
                .header("Nurishd-Signature", signature)
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();
        HttpResponse<String> res =
                HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(label + " " + res.statusCode());
    }

    // Run with -Dexec.args="ORDER_ID"
    public static void main(String[] args) throws Exception {
        String orderId = args.length > 0 ? args[0] : "ORD-EXAMPLE-0001";
        long now = System.currentTimeMillis() / 1000;
        String body = Nurishd.JSON.writeValueAsString(Map.of(
                "id", "evt_test_" + now,
                "type", "order.paid",
                "created", "2026-04-01T15:06:30Z",
                "mode", "test",
                "data", Map.of("object", "order", "id", orderId, "order", orderId,
                        "customer", "customer-0001")));

        send("signed event:", body, sign(now, body));
        send("same event again:", body, sign(now, body));
        send("changed body:", body.replace("order.paid", "order.canceled"), sign(now, body));
        send("old timestamp:", body, sign(now - 600, body));
    }
}
```

Run it in a second terminal where `NURISHD_WEBHOOK_SECRET` is set. Pass the id of one of your orders as the argument. Without an argument it uses `ORD-EXAMPLE-0001`, which the real Sandbox does not know.

- Python: `python send_test.py ORDER_ID`
- JavaScript: `node send-test.js ORDER_ID`
- TypeScript: `node send-test.ts ORDER_ID`
- Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.SendTest -Dexec.args="ORDER_ID"`

The script prints the answer of each request.

```text
signed event: 200
same event again: 200
changed body: 400
old timestamp: 400
```

The server terminal prints what it did with each one.

```text
order.paid ORD-EXAMPLE-0001 -> confirmed
ignored: already handled evt_test_1795112345
refused: bad signature
refused: bad signature
```

The signed event is accepted and the order is marked `confirmed`. The repeat is ignored. The changed body and the old timestamp are refused with `400`.

## 9. If you miss an event

If your server is down or answers with an error, Nurish'd sends the event again for up to three days. You can also read what you missed. `GET /developer/v1/event/query/documents` lists events from the last 30 days. Ask only for events at or after the time of the last one you handled, and skip ids you already handled. The [Events](/docs/events/events) guide shows this pattern.

## The whole program

Each language has one server file. The registration script and the test script are shown in full in steps 5 and 8.

```python
# file: webhook.py
import hashlib
import hmac
import json
import os
import time

from flask import Flask, request

from nurishd import NurishdError, call

SECRET = os.environ["NURISHD_WEBHOOK_SECRET"]
TOLERANCE_SECONDS = 300

# What each order event means in your own records.
STATUS = {
    "order.created": "received",
    "order.paid": "confirmed",
    "order.fulfilled": "fulfilled",
    "order.shipped": "shipped",
    "order.delivered": "delivered",
    "order.refunded": "refunded",
    "order.canceled": "canceled",
}

orders = {}  # order id -> {"status": ..., "delivery_date": ...}
handled = set()  # ids of events you already handled

app = Flask(__name__)


def verify_signature(raw_body, header, secret):
    """Returns True if the request came from Nurish'd and is fresh."""
    if not header:
        return False

    timestamp = None
    signatures = []
    for part in header.split(","):
        key, found, value = part.partition("=")
        if not found:
            continue
        key, value = key.strip(), value.strip()
        if key == "t":
            timestamp = value
        elif key == "v1":
            signatures.append(value)
    if timestamp is None or not timestamp.isdigit() or not signatures:
        return False

    if abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False

    expected = hmac.new(
        secret.encode("utf-8"),
        timestamp.encode("utf-8") + b"." + raw_body,
        hashlib.sha256,
    ).hexdigest()
    return any(hmac.compare_digest(expected, s.lower()) for s in signatures)


@app.post("/webhooks/nurishd")
def receive():
    # 1. Read the raw bytes and check the signature before anything else.
    raw_body = request.get_data()
    if not verify_signature(raw_body, request.headers.get("Nurishd-Signature"), SECRET):
        print("refused: bad signature")
        return "", 400

    # 2. Ignore an event you already handled.
    event = json.loads(raw_body)
    if event["id"] in handled:
        print("ignored: already handled", event["id"])
        return "", 200

    # 3. For an order event, read the order and update your records.
    if event["type"] in STATUS:
        order_id = event["data"]["id"]
        try:
            order = call("GET", f"/meals/v1/order/{order_id}/get/document")
            orders[order_id] = {
                "status": STATUS[event["type"]],
                "delivery_date": order["order_delivery_date"],
            }
            print(event["type"], order_id, "->", orders[order_id]["status"])
        except NurishdError as error:
            if error.status == 429 or error.status >= 500:
                return "", 500  # Nurish'd sends the event again later.
            print("cannot read order:", order_id, error.code)
    else:
        print("ignored type:", event["type"])

    # 4. Remember the event and answer.
    handled.add(event["id"])
    return "", 200


if __name__ == "__main__":
    app.run(port=int(os.environ.get("PORT", "3000")))
```

```javascript
// file: webhook.js
import crypto from 'node:crypto';
import express from 'express';
import { NurishdError, call } from './nurishd.js';

const SECRET = process.env.NURISHD_WEBHOOK_SECRET;
if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.');
const TOLERANCE_SECONDS = 300;

// What each order event means in your own records.
const STATUS = {
	'order.created': 'received',
	'order.paid': 'confirmed',
	'order.fulfilled': 'fulfilled',
	'order.shipped': 'shipped',
	'order.delivered': 'delivered',
	'order.refunded': 'refunded',
	'order.canceled': 'canceled',
};

const orders = new Map(); // order id -> { status, deliveryDate }
const handled = new Set(); // ids of events you already handled

/** Returns true if the request came from Nurish'd and is fresh. */
function verifySignature(rawBody, header, secret) {
	if (!header) return false;

	let timestamp = null;
	const signatures = [];
	for (const part of header.split(',')) {
		const index = part.indexOf('=');
		if (index === -1) continue;
		const key = part.slice(0, index).trim();
		const value = part.slice(index + 1).trim();
		if (key === 't') timestamp = value;
		if (key === 'v1') signatures.push(value);
	}
	if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0)
		return false;

	const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
	if (age > TOLERANCE_SECONDS) return false;

	const expected = crypto
		.createHmac('sha256', secret)
		.update(Buffer.concat([Buffer.from(`${timestamp}.`), rawBody]))
		.digest();
	return signatures.some((signature) => {
		if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
		return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected);
	});
}

const app = express();

app.post(
	'/webhooks/nurishd',
	// 1. Keep the body as raw bytes.
	express.raw({ type: 'application/json' }),
	async (req, res) => {
		// 2. Check the signature before anything else.
		if (!verifySignature(req.body, req.get('Nurishd-Signature'), SECRET)) {
			console.log('refused: bad signature');
			return res.sendStatus(400);
		}

		// 3. Ignore an event you already handled.
		const event = JSON.parse(req.body.toString('utf8'));
		if (handled.has(event.id)) {
			console.log('ignored: already handled', event.id);
			return res.sendStatus(200);
		}

		// 4. For an order event, read the order and update your records.
		if (event.type in STATUS) {
			const orderId = event.data.id;
			try {
				const order = await call(
					'GET',
					`/meals/v1/order/${orderId}/get/document`,
				);
				orders.set(orderId, {
					status: STATUS[event.type],
					deliveryDate: order.order_delivery_date,
				});
				console.log(
					event.type,
					orderId,
					'->',
					orders.get(orderId).status,
				);
			} catch (error) {
				if (!(error instanceof NurishdError)) throw error;
				if (error.status === 429 || error.status >= 500) {
					return res.sendStatus(500); // Nurish'd sends the event again later.
				}
				console.log('cannot read order:', orderId, error.code);
			}
		} else {
			console.log('ignored type:', event.type);
		}

		// 5. Remember the event and answer.
		handled.add(event.id);
		res.sendStatus(200);
	},
);

app.listen(Number(process.env.PORT ?? 3000), () => {
	console.log('Listening for webhooks');
});
```

```typescript
// file: webhook.ts
import crypto from 'node:crypto';
import express from 'express';
import { NurishdError, call } from './nurishd.ts';

const SECRET = process.env.NURISHD_WEBHOOK_SECRET;
if (!SECRET) throw new Error('Set NURISHD_WEBHOOK_SECRET first.');
const TOLERANCE_SECONDS = 300;

interface WebhookEvent {
	id: string;
	type: string;
	data: { id: string };
}

interface Order {
	order_delivery_date: string;
}

// What each order event means in your own records.
const STATUS: Record<string, string> = {
	'order.created': 'received',
	'order.paid': 'confirmed',
	'order.fulfilled': 'fulfilled',
	'order.shipped': 'shipped',
	'order.delivered': 'delivered',
	'order.refunded': 'refunded',
	'order.canceled': 'canceled',
};

const orders = new Map<string, { status: string; deliveryDate: string }>(); // order id -> your record
const handled = new Set<string>(); // ids of events you already handled

/** Returns true if the request came from Nurish'd and is fresh. */
function verifySignature(
	rawBody: Buffer,
	header: string | undefined,
	secret: string,
): boolean {
	if (!header) return false;

	let timestamp: string | null = null;
	const signatures: string[] = [];
	for (const part of header.split(',')) {
		const index = part.indexOf('=');
		if (index === -1) continue;
		const key = part.slice(0, index).trim();
		const value = part.slice(index + 1).trim();
		if (key === 't') timestamp = value;
		if (key === 'v1') signatures.push(value);
	}
	if (!timestamp || !/^\d+$/.test(timestamp) || signatures.length === 0)
		return false;

	const age = Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp));
	if (age > TOLERANCE_SECONDS) return false;

	const expected = crypto
		.createHmac('sha256', secret)
		.update(Buffer.concat([Buffer.from(`${timestamp}.`), rawBody]))
		.digest();
	return signatures.some((signature) => {
		if (!/^[0-9a-f]{64}$/i.test(signature)) return false;
		return crypto.timingSafeEqual(Buffer.from(signature, 'hex'), expected);
	});
}

const app = express();

app.post(
	'/webhooks/nurishd',
	// 1. Keep the body as raw bytes.
	express.raw({ type: 'application/json' }),
	async (req, res) => {
		// 2. Check the signature before anything else.
		if (!verifySignature(req.body, req.get('Nurishd-Signature'), SECRET)) {
			console.log('refused: bad signature');
			return res.sendStatus(400);
		}

		// 3. Ignore an event you already handled.
		const event = JSON.parse(req.body.toString('utf8')) as WebhookEvent;
		if (handled.has(event.id)) {
			console.log('ignored: already handled', event.id);
			return res.sendStatus(200);
		}

		// 4. For an order event, read the order and update your records.
		if (event.type in STATUS) {
			const orderId = event.data.id;
			try {
				const order = await call<Order>(
					'GET',
					`/meals/v1/order/${orderId}/get/document`,
				);
				orders.set(orderId, {
					status: STATUS[event.type],
					deliveryDate: order.order_delivery_date,
				});
				console.log(
					event.type,
					orderId,
					'->',
					orders.get(orderId)?.status,
				);
			} catch (error) {
				if (!(error instanceof NurishdError)) throw error;
				if (error.status === 429 || error.status >= 500) {
					return res.sendStatus(500); // Nurish'd sends the event again later.
				}
				console.log('cannot read order:', orderId, error.code);
			}
		} else {
			console.log('ignored type:', event.type);
		}

		// 5. Remember the event and answer.
		handled.add(event.id);
		res.sendStatus(200);
	},
);

app.listen(Number(process.env.PORT ?? 3000), () => {
	console.log('Listening for webhooks');
});
```

```java
// file: src/main/java/tutorial/Webhook.java
package tutorial;

import com.fasterxml.jackson.databind.JsonNode;
import io.javalin.Javalin;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Webhook {
    private static final String SECRET = System.getenv("NURISHD_WEBHOOK_SECRET");
    private static final long TOLERANCE_SECONDS = 300;

    // What each order event means in your own records.
    private static final Map<String, String> STATUS = Map.of(
            "order.created", "received",
            "order.paid", "confirmed",
            "order.fulfilled", "fulfilled",
            "order.shipped", "shipped",
            "order.delivered", "delivered",
            "order.refunded", "refunded",
            "order.canceled", "canceled");

    // order id -> status and delivery date
    private static final Map<String, Map<String, String>> orders = new ConcurrentHashMap<>();
    // ids of events you already handled
    private static final Set<String> handled = ConcurrentHashMap.newKeySet();

    /** Returns true if the request came from Nurish'd and is fresh. */
    static boolean verifySignature(byte[] rawBody, String header, String secret)
            throws GeneralSecurityException {
        if (header == null) return false;

        String timestamp = null;
        List<String> signatures = new ArrayList<>();
        for (String part : header.split(",")) {
            int index = part.indexOf('=');
            if (index == -1) continue;
            String key = part.substring(0, index).trim();
            String value = part.substring(index + 1).trim();
            if (key.equals("t")) timestamp = value;
            if (key.equals("v1")) signatures.add(value);
        }
        if (timestamp == null || !timestamp.matches("\\d{1,12}") || signatures.isEmpty()) {
            return false;
        }

        long age = Math.abs(System.currentTimeMillis() / 1000 - Long.parseLong(timestamp));
        if (age > TOLERANCE_SECONDS) return false;

        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        mac.update((timestamp + ".").getBytes(StandardCharsets.UTF_8));
        byte[] expected = mac.doFinal(rawBody);

        for (String signature : signatures) {
            if (!signature.matches("[0-9a-fA-F]{64}")) continue;
            if (MessageDigest.isEqual(HexFormat.of().parseHex(signature), expected)) return true;
        }
        return false;
    }

    public static void main(String[] args) {
        if (SECRET == null || SECRET.isBlank()) {
            throw new IllegalStateException("Set NURISHD_WEBHOOK_SECRET first.");
        }
        int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "3000"));

        Javalin app = Javalin.create();
        app.post("/webhooks/nurishd", ctx -> {
            // 1. Read the raw bytes and check the signature before anything else.
            byte[] rawBody = ctx.bodyAsBytes();
            if (!verifySignature(rawBody, ctx.header("Nurishd-Signature"), SECRET)) {
                System.out.println("refused: bad signature");
                ctx.status(400);
                return;
            }

            // 2. Ignore an event you already handled.
            JsonNode event = Nurishd.JSON.readTree(rawBody);
            String eventId = event.path("id").asText();
            String type = event.path("type").asText();
            if (handled.contains(eventId)) {
                System.out.println("ignored: already handled " + eventId);
                ctx.status(200);
                return;
            }

            // 3. For an order event, read the order and update your records.
            if (STATUS.containsKey(type)) {
                String orderId = event.path("data").path("id").asText();
                try {
                    JsonNode order = Nurishd.call(
                            "GET", "/meals/v1/order/%s/get/document".formatted(orderId));
                    orders.put(orderId, Map.of(
                            "status", STATUS.get(type),
                            "deliveryDate", order.path("order_delivery_date").asText()));
                    System.out.println(type + " " + orderId + " -> " + STATUS.get(type));
                } catch (Nurishd.NurishdException error) {
                    if (error.status == 429 || error.status >= 500) {
                        ctx.status(500); // Nurish'd sends the event again later.
                        return;
                    }
                    System.out.println("cannot read order: " + orderId + " " + error.code);
                }
            } else {
                System.out.println("ignored type: " + type);
            }

            // 4. Remember the event and answer.
            handled.add(eventId);
            ctx.status(200);
        });
        app.start(port);
    }
}
```

## If something goes wrong

| What you see                                                      | Why                                                                                                          | What to do                                                                                                   |
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| The server prints `refused: bad signature` for a real delivery    | The secret is wrong, the body was changed before the check, or your computer clock is off by over 5 minutes. | Copy the secret from the console. Make sure nothing parses the body before the check. Fix the clock.         |
| The console shows a failed delivery and the server prints nothing | The address does not reach your server.                                                                      | Check that the tunnel runs, that the URL ends with `/webhooks/nurishd` and that the port matches.            |
| `403 scope_not_granted` when you register                         | The key cannot see one of the order events.                                                                  | Use a key with the `order:read` scope. See [Scopes](/docs/concepts/scopes).                                  |
| `422 validation_error` when you register                          | The URL is not a public `https` address.                                                                     | Use the tunnel address. It cannot be `http`, `localhost` or a private IP.                                    |
| `409 webhook_endpoint_limit_reached` when you register            | The company has 10 endpoints in this environment.                                                            | Delete an endpoint you do not use, in the console.                                                           |
| The server prints `cannot read order: ... not_found`              | The order does not exist, or it belongs to another company or environment.                                   | Use an order your Sandbox key placed. A sample id such as `ORD-EXAMPLE-0001` is unknown to the real Sandbox. |
| The server prints `cannot read order: ... connection_not_active`  | The customer ended the connection, so you can no longer read their orders.                                   | Nothing to fix. The route skips the order.                                                                   |
| `Set NURISHD_WEBHOOK_SECRET first.` or `KeyError`                 | The variable is not set in this terminal.                                                                    | Set it again as in step 5, then start the server.                                                            |
| `EADDRINUSE` or `Address already in use`                          | Something else uses port 3000.                                                                               | Set `PORT` to a free port and start the tunnel on it.                                                        |

## Next

- [Webhooks](/docs/events/webhooks): endpoints, pausing and retries.
- [Verifying signatures](/docs/events/verifying-signatures): roll a signing secret without missing events.
- [Orders](/docs/meals/orders): order fields and statuses.
- [Place a meal order](/docs/tutorials/place-a-meal-order): create the orders this server hears about.
