Developers

Search the docs

Search guides and headings.

Receive order webhooks

Build a small web server that Nurish'd calls when an order changes, check that each call is genuine, and update your own records.

View as Markdown

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 for the event object.

Before you start#

  • You finished 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.
LanguageCommand
Pythonpip install flask
JavaScriptnpm install express
TypeScriptnpm install express and npm install --save-dev @types/express
JavaReplace 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

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 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)

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

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.

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"])

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))

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 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")))

If something goes wrong#

What you seeWhyWhat to do
The server prints refused: bad signature for a real deliveryThe 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 nothingThe 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 registerThe key cannot see one of the order events.Use a key with the order:read scope. See Scopes.
422 validation_error when you registerThe 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 registerThe company has 10 endpoints in this environment.Delete an endpoint you do not use, in the console.
The server prints cannot read order: ... not_foundThe 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_activeThe 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 KeyErrorThe variable is not set in this terminal.Set it again as in step 5, then start the server.
EADDRINUSE or Address already in useSomething else uses port 3000.Set PORT to a free port and start the tunnel on it.

Next#