Developers

Search the docs

Search guides and headings.

Place a meal order

Build a small web app that places a meal order for a connected customer, lets the customer pay with Stripe.js, and reads the order back.

View as Markdown

You will build a small web app. A page sends a basket to your server. Your server places the order with Nurish'd. The customer pays on the page. Your server reads the order back and says where it stands.

Before you start#

  • You finished Set up your project. Your project has the nurishd client file and a Sandbox key in NURISHD_API_KEY.
  • You have a connected customer. You get one in Connect a customer from your own sign-in. You need the customer's id, which the create call answers as user.
  • You have a vendor, a delivery date and product ids. You get them in Show meals for an address and a date.
  • Your key has the scopes order:write and order:read. They are needed to place an order and to read it. 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.

How an order is paid#

You do not take the card on your server. The order answer carries what your page needs to take the payment:

  • stripe_payment_intent.stripe_payment_intent_client_secret is a secret for this one payment. A payment intent is Stripe's record of a payment that is being made.
  • stripe_publishable_key is the Stripe key your page uses. It is safe to put in a page.

Your page uses Stripe.js, Stripe's library for the browser. The customer types the card into Stripe's own form. The card number never reaches your server or Nurish'd. A customer who saved a card can pay without typing it again. See Saving a card.

1. Set up the server#

The server has two routes: POST /orders and GET /orders/<id>. It also serves the page public/pay.html, which you write in step 3.

REQUIRED lists the fields of a basket. ORDER_ID checks the shape of an order id, because the id goes into a URL path. refusal sends the browser the code and the message of an error from Nurish'd.

python
# Flask serves the files in public/ at the site root, so public/pay.html is /pay.html.
app = Flask(__name__, static_folder="public", static_url_path="")

REQUIRED = ["customer_id", "vendor_id", "delivery_date", "items", "address", "email", "phone", "reference"]

# An order id goes into a URL path, so check its shape before you use it.
ORDER_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}")


def refusal(error):
    return jsonify(code=error.code, message=str(error)), error.status

2. Place the order#

POST /orders takes a basket and calls POST /meals/v1/order/create/document. The basket has these fields.

Basket fieldBecomesWhat it is
customer_iduserThe id of the connected customer.
vendor_idorder_vendorThe id of the vendor.
delivery_dateorder_delivery_dateA day the zone offers, as YYYY-MM-DD.
itemsline_itemsProduct ids and quantities.
addressorder_shipping_addressWhere to deliver, with the limits in step 5.
emailorder_contact_emailHow the kitchen and the courier reach the customer.
phoneorder_contact_phoneThe phone number with its country code.
referencereferenceYour own order number.

The reference makes a retry safe. If you send the same reference again, Nurish'd returns the order it already placed and does not place a second one. When a call times out, send it again with the same reference.

The customer's id comes from the page in this tutorial, to keep it short. In a real app the server takes it from the signed-in session. Never let a browser choose whose orders it places.

The answer holds the whole order. The route sends the browser only three things: the order id, the client secret and the publishable key. An order that costs nothing is paid at once, and its stripe_payment_intent is null. Never log the client secret.

python
@app.post("/orders")
def place_order():
    basket = request.get_json()
    missing = [name for name in REQUIRED if name not in basket]
    if missing:
        return jsonify(code="bad_basket", message="Missing: " + ", ".join(missing)), 400

    try:
        order = call(
            "POST",
            "/meals/v1/order/create/document",
            body={
                "user": basket["customer_id"],
                "order_vendor": basket["vendor_id"],
                "order_delivery_date": basket["delivery_date"],
                "line_items": [
                    {
                        "line_item_product_id": item["product_id"],
                        "line_quantity": item["quantity"],
                    }
                    for item in basket["items"]
                ],
                "order_shipping_address": basket["address"],
                "order_contact_email": basket["email"],
                "order_contact_phone": basket["phone"],
                "reference": basket["reference"],
            },
        )
    except NurishdError as error:
        return refusal(error)

    # Send the browser only what it needs to pay.
    intent = order["stripe_payment_intent"]
    return (
        jsonify(
            order_id=order["order_id"],
            client_secret=intent["stripe_payment_intent_client_secret"] if intent else None,
            publishable_key=order["stripe_publishable_key"],
        ),
        201,
    )

3. Add the payment page#

The page lets you edit a basket and press Place order. It calls your route, then shows Stripe's card form and confirms the payment with stripe.confirmCardPayment. This code runs in the browser, never on your server.

Create a folder named public next to your program. Create public/pay.html in it. Change the basket to your customer, vendor, date and products. Change reference for every new order. The same reference returns the first order.

html
<!-- file: public/pay.html -->
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8" />
		<title>Place a meal order</title>
		<script src="https://js.stripe.com/v3/"></script>
	</head>
	<body>
		<h1>Place a meal order</h1>
		<p>Edit the basket, then press Place order.</p>
		<textarea id="basket" rows="24" cols="70">
{
  "customer_id": "6f1c0d2e-0000-4000-8000-000000000101",
  "vendor_id": "vendor-harbour-kitchen",
  "delivery_date": "2026-04-07",
  "items": [
    { "product_id": "product-salmon-bowl", "quantity": 4 },
    { "product_id": "product-chicken-wrap", "quantity": 2 }
  ],
  "address": {
    "line1": "10 Example Street",
    "city": "Toronto",
    "state": "ON",
    "postal_code": "M5V 2T6",
    "country": "CA"
  },
  "email": "ada.lovelace@example.com",
  "phone": "+14165550123",
  "reference": "web-order-1001"
}</textarea>
		<p><button id="place">Place order</button></p>

		<div id="payment" hidden>
			<div id="card"></div>
			<p><button id="pay">Pay</button></p>
		</div>
		<p id="message"></p>

		<script>
			const message = document.getElementById('message');
			let stripe, card, order;

			document
				.getElementById('place')
				.addEventListener('click', async () => {
					const res = await fetch('/orders', {
						method: 'POST',
						headers: { 'Content-Type': 'application/json' },
						body: document.getElementById('basket').value,
					});
					order = await res.json();
					if (!res.ok) {
						message.textContent = order.code + ': ' + order.message;
						return;
					}
					if (!order.client_secret || !order.publishable_key) {
						message.textContent =
							'Order ' +
							order.order_id +
							' needs no card payment.';
						return;
					}
					stripe = Stripe(order.publishable_key);
					card = stripe.elements().create('card');
					card.mount('#card');
					document.getElementById('payment').hidden = false;
					message.textContent =
						'Order ' +
						order.order_id +
						' placed. Enter the card and press Pay.';
				});

			document
				.getElementById('pay')
				.addEventListener('click', async () => {
					const { error } = await stripe.confirmCardPayment(
						order.client_secret,
						{
							payment_method: { card: card },
						},
					);
					message.textContent = error
						? error.message
						: 'Payment sent. Read /orders/' +
							order.order_id +
							' to see when it is paid.';
				});
		</script>
	</body>
</html>

The page does not tell you that the order is paid. Stripe says the card was accepted. Only the order says that it is paid. See step 4.

The publishable key shows which Stripe mode the form uses. A key that starts with pk_test_ takes Stripe's test cards. See Stripe's testing guide.

4. Read the order#

GET /orders/<id> calls GET /meals/v1/order/{order_id}/get/document. The answer has the order's three statuses. The route sends them on, with one sentence in plain words that say picks.

An order is confirmed when it is paid. Do not treat it as paid because your page says the card was accepted. The order is paid when order_financial_status is paid. Read the order again to see its present state. If the customer reloads before paying, this read returns the client secret again while the payment is pending.

The three statuses mean this for your customer.

FieldValueWhat it means for your customer
order_financial_statuspendingThe order waits for the payment.
order_financial_statuspaidThe payment went through. The order is confirmed.
order_financial_statusfailed paymentThe payment did not go through.
order_financial_statusrefundedThe money went back to the customer.
order_financial_statuscancelledThe order was cancelled.
order_fulfillment_statuspending paymentThe kitchen waits for the payment.
order_fulfillment_statusnot startedThe kitchen has not started yet.
order_fulfillment_statuspreparing mealsThe kitchen is cooking the meals.
order_fulfillment_statuscompletedThe meals are ready.
order_delivery_statuspending paymentNothing ships before the payment.
order_delivery_statusnot yet shippedThe order waits for the courier.
order_delivery_statusshippedThe order is on its way.
order_delivery_statusdeliveredThe order arrived.
order_delivery_statusdelivery failedThe courier could not deliver it.

The contract lists more values, such as partially refunded, chargeback and do not process. The last lines of the file start the server.

python
def say(order):
    payment = order["order_financial_status"]
    delivery = order["order_delivery_status"]
    if payment == "pending":
        return "Waiting for payment."
    if payment == "failed payment":
        return "The payment failed."
    if payment == "paid":
        if delivery == "delivered":
            return "Delivered."
        if delivery == "shipped":
            return "On its way."
        return "Paid. The kitchen is getting it ready."
    return f"Payment status: {payment}."


@app.get("/orders/<order_id>")
def read_order(order_id):
    if not ORDER_ID.fullmatch(order_id):
        return jsonify(code="bad_order_id", message="This order id is not valid."), 400
    try:
        order = call("GET", f"/meals/v1/order/{order_id}/get/document")
    except NurishdError as error:
        return refusal(error)
    return jsonify(
        order_id=order["order_id"],
        summary=say(order),
        payment=order["order_financial_status"],
        kitchen=order["order_fulfillment_status"],
        delivery=order["order_delivery_status"],
        total_cents=order["order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING"],
        currency=order["order_currency"],
    )


app.run(port=3000)

5. Know the rules that refuse an order#

Nurish'd checks the order before it places anything. A refusal creates nothing. Check these on your side too, so the customer sees a clear message before the call.

What you sendThe rule
delivery_dateYYYY-MM-DD, the date part of a delivery date the zone offers. No time of day.
items1 to 50 items. Each has a product id and a quantity of at least 1. A product appears only once.
Each productIt must be offered on that date. See Catalog.
The order as a wholeIt must meet the vendor's limits on items and value, such as the minimum order.
address.line1, line2, cityUp to 200, 200 and 100 characters. $, { and } are not accepted.
address.state, countryTwo capital letters, such as ON and CA.
address.postal_codeLetters, digits, spaces and hyphens, up to 20 characters.
phoneThe country code first, such as +14165550123. At most 20 characters.

The customer's connection must be active and must allow orders.

6. Run it#

Create the program file for your language and public/pay.html. Start the server.

LanguageCommand
Pythonpython orders.py
JavaScriptnode orders.js
TypeScriptnode orders.ts
Javamvn -q compile exec:java -Dexec.mainClass=tutorial.Orders

Post a basket with curl. Use the ids of your own customer, vendor and products.

bash
curl -X POST http://localhost:3000/orders \
  -H "Content-Type: application/json" \
  -d '{
    "customer_id": "6f1c0d2e-0000-4000-8000-000000000101",
    "vendor_id": "vendor-harbour-kitchen",
    "delivery_date": "2026-04-07",
    "items": [
      { "product_id": "product-salmon-bowl", "quantity": 4 },
      { "product_id": "product-chicken-wrap", "quantity": 2 }
    ],
    "address": {
      "line1": "10 Example Street",
      "city": "Toronto",
      "state": "ON",
      "postal_code": "M5V 2T6",
      "country": "CA"
    },
    "email": "ada.lovelace@example.com",
    "phone": "+14165550123",
    "reference": "web-order-1001"
  }'

The answer has the three things the page needs. Your values differ.

text
{"order_id":"ORD-ONE-OFF-4F7K2A9Q","client_secret":"pi_3QExample0001_secret_a1B2c3D4e5F6g7H8i9J0","publishable_key":"pk_test_51QExample0001abcdefghijklmnop"}

Read the order back with the order_id of the answer.

bash
curl http://localhost:3000/orders/ORD-ONE-OFF-4F7K2A9Q

The order waits for its payment. After the customer pays, the payment status changes to paid.

To pay, open http://localhost:3000/pay.html in a browser, press Place order, enter a card in the form and press Pay. Then read the order again. The page says the card was accepted. The order is paid when its payment status is paid.

When the order is confirmed#

The order is confirmed when it is paid. Your page cannot tell you that, and a customer may close the tab before the order changes. Nurish'd sends an order.paid event to your server when the payment is done. Use it to update your records. See Receive order webhooks.

The whole program#

python
# file: orders.py
import re

from flask import Flask, jsonify, request

from nurishd import NurishdError, call

# Flask serves the files in public/ at the site root, so public/pay.html is /pay.html.
app = Flask(__name__, static_folder="public", static_url_path="")

REQUIRED = ["customer_id", "vendor_id", "delivery_date", "items", "address", "email", "phone", "reference"]

# An order id goes into a URL path, so check its shape before you use it.
ORDER_ID = re.compile(r"[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}")


def refusal(error):
    return jsonify(code=error.code, message=str(error)), error.status


@app.post("/orders")
def place_order():
    basket = request.get_json()
    missing = [name for name in REQUIRED if name not in basket]
    if missing:
        return jsonify(code="bad_basket", message="Missing: " + ", ".join(missing)), 400

    try:
        order = call(
            "POST",
            "/meals/v1/order/create/document",
            body={
                "user": basket["customer_id"],
                "order_vendor": basket["vendor_id"],
                "order_delivery_date": basket["delivery_date"],
                "line_items": [
                    {
                        "line_item_product_id": item["product_id"],
                        "line_quantity": item["quantity"],
                    }
                    for item in basket["items"]
                ],
                "order_shipping_address": basket["address"],
                "order_contact_email": basket["email"],
                "order_contact_phone": basket["phone"],
                "reference": basket["reference"],
            },
        )
    except NurishdError as error:
        return refusal(error)

    # Send the browser only what it needs to pay.
    intent = order["stripe_payment_intent"]
    return (
        jsonify(
            order_id=order["order_id"],
            client_secret=intent["stripe_payment_intent_client_secret"] if intent else None,
            publishable_key=order["stripe_publishable_key"],
        ),
        201,
    )


def say(order):
    payment = order["order_financial_status"]
    delivery = order["order_delivery_status"]
    if payment == "pending":
        return "Waiting for payment."
    if payment == "failed payment":
        return "The payment failed."
    if payment == "paid":
        if delivery == "delivered":
            return "Delivered."
        if delivery == "shipped":
            return "On its way."
        return "Paid. The kitchen is getting it ready."
    return f"Payment status: {payment}."


@app.get("/orders/<order_id>")
def read_order(order_id):
    if not ORDER_ID.fullmatch(order_id):
        return jsonify(code="bad_order_id", message="This order id is not valid."), 400
    try:
        order = call("GET", f"/meals/v1/order/{order_id}/get/document")
    except NurishdError as error:
        return refusal(error)
    return jsonify(
        order_id=order["order_id"],
        summary=say(order),
        payment=order["order_financial_status"],
        kitchen=order["order_fulfillment_status"],
        delivery=order["order_delivery_status"],
        total_cents=order["order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING"],
        currency=order["order_currency"],
    )


app.run(port=3000)

If something goes wrong#

What you seeWhyWhat to do
409 connection_not_activeThe customer has not approved, or they revoked the link.Send the customer through Connect a customer again.
403 connection_scope_not_grantedThe customer did not allow orders.Ask the customer to approve again.
403 scope_not_grantedYour key lacks order:write or order:read.Create a key with both scopes.
404 not_found when you place an orderThe customer is unknown, or the vendor cannot be used.Check the customer id. In Production, ask Nurish'd to enable the vendor.
422 delivery_not_availableThe vendor does not deliver to the address or on that date.Check the zone and the dates again.
422 product_not_availableA product is not offered on that date.Read the date's product ids and choose again.
422 order_limits_not_metThe order is under or over the vendor's limits.Change the items.
422 vendor_not_allowed_for_customerThe customer can order only from some vendors.Offer another vendor.
422 validation_errorA field breaks a rule of step 5. The message names it.Fix the field. Do not send it again unchanged.
409 order_conflictThe order cannot be placed in its current state.Read the order, then decide. Do not retry unchanged.

Next#