---
title: Place a meal order
description: 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.
section: Tutorials
order: 4
---

# Place a meal order

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](/docs/tutorials/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](/docs/tutorials/connect-a-customer). 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](/docs/tutorials/show-meals-for-an-address).
- 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.

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

## 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](https://docs.stripe.com/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](/docs/meals/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
```

```javascript
const app = express();
app.use(express.json());
// Express serves the files in public/ at the site root, so public/pay.html is /pay.html.
app.use(express.static('public'));

const 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.
const ORDER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/;

function refusal(res, error) {
	res.status(error.status).json({ code: error.code, message: error.message });
}
```

```typescript
interface Basket {
	customer_id: string;
	vendor_id: string;
	delivery_date: string;
	items: { product_id: string; quantity: number }[];
	address: Record<string, string>;
	email: string;
	phone: string;
	reference: string;
}

interface Order {
	order_id: string;
	order_financial_status: string;
	order_fulfillment_status: string;
	order_delivery_status: string;
	order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING: number;
	order_currency: string;
	stripe_payment_intent: {
		stripe_payment_intent_client_secret: string;
	} | null;
	stripe_publishable_key: string | null;
}

const app = express();
app.use(express.json());
// Express serves the files in public/ at the site root, so public/pay.html is /pay.html.
app.use(express.static('public'));

const 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.
const ORDER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/;

function refusal(res: Response, error: NurishdError) {
	res.status(error.status).json({ code: error.code, message: error.message });
}
```

```java
    static final List<String> REQUIRED =
            List.of("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.
    static final Pattern ORDER_ID = Pattern.compile("[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}");

    static void fail(Context ctx, int status, String code, String message) {
        ObjectNode body = Nurishd.JSON.createObjectNode();
        body.put("code", code);
        body.put("message", message);
        ctx.status(status).json(body);
    }
```

## 2. Place the order

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

| Basket field    | Becomes                  | What it is                                          |
| --------------- | ------------------------ | --------------------------------------------------- |
| `customer_id`   | `user`                   | The id of the connected customer.                   |
| `vendor_id`     | `order_vendor`           | The id of the vendor.                               |
| `delivery_date` | `order_delivery_date`    | A day the zone offers, as `YYYY-MM-DD`.             |
| `items`         | `line_items`             | Product ids and quantities.                         |
| `address`       | `order_shipping_address` | Where to deliver, with the limits in step 5.        |
| `email`         | `order_contact_email`    | How the kitchen and the courier reach the customer. |
| `phone`         | `order_contact_phone`    | The phone number with its country code.             |
| `reference`     | `reference`              | Your 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,
    )
```

```javascript
app.post('/orders', async (req, res) => {
	const basket = req.body;
	const missing = REQUIRED.filter((name) => !(name in basket));
	if (missing.length > 0) {
		return res.status(400).json({
			code: 'bad_basket',
			message: 'Missing: ' + missing.join(', '),
		});
	}

	let order;
	try {
		order = await 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: basket.items.map((item) => ({
					line_item_product_id: item.product_id,
					line_quantity: item.quantity,
				})),
				order_shipping_address: basket.address,
				order_contact_email: basket.email,
				order_contact_phone: basket.phone,
				reference: basket.reference,
			},
		});
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return refusal(res, error);
	}

	// Send the browser only what it needs to pay.
	res.status(201).json({
		order_id: order.order_id,
		client_secret:
			order.stripe_payment_intent?.stripe_payment_intent_client_secret ??
			null,
		publishable_key: order.stripe_publishable_key,
	});
});
```

```typescript
app.post('/orders', async (req, res) => {
	const basket = req.body as Basket;
	const missing = REQUIRED.filter((name) => !(name in basket));
	if (missing.length > 0) {
		return res.status(400).json({
			code: 'bad_basket',
			message: 'Missing: ' + missing.join(', '),
		});
	}

	let order: Order;
	try {
		order = await call<Order>('POST', '/meals/v1/order/create/document', {
			body: {
				user: basket.customer_id,
				order_vendor: basket.vendor_id,
				order_delivery_date: basket.delivery_date,
				line_items: basket.items.map((item) => ({
					line_item_product_id: item.product_id,
					line_quantity: item.quantity,
				})),
				order_shipping_address: basket.address,
				order_contact_email: basket.email,
				order_contact_phone: basket.phone,
				reference: basket.reference,
			},
		});
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return refusal(res, error);
	}

	// Send the browser only what it needs to pay.
	res.status(201).json({
		order_id: order.order_id,
		client_secret:
			order.stripe_payment_intent?.stripe_payment_intent_client_secret ??
			null,
		publishable_key: order.stripe_publishable_key,
	});
});
```

```java
    static void placeOrder(Context ctx) throws Exception {
        JsonNode basket = Nurishd.JSON.readTree(ctx.body());
        List<String> missing = new ArrayList<>();
        for (String name : REQUIRED) {
            if (!basket.has(name)) missing.add(name);
        }
        if (!missing.isEmpty()) {
            fail(ctx, 400, "bad_basket", "Missing: " + String.join(", ", missing));
            return;
        }

        ObjectNode body = Nurishd.JSON.createObjectNode();
        body.put("user", basket.path("customer_id").asText());
        body.put("order_vendor", basket.path("vendor_id").asText());
        body.put("order_delivery_date", basket.path("delivery_date").asText());
        ArrayNode lineItems = body.putArray("line_items");
        for (JsonNode item : basket.path("items")) {
            ObjectNode line = lineItems.addObject();
            line.put("line_item_product_id", item.path("product_id").asText());
            line.put("line_quantity", item.path("quantity").asInt());
        }
        body.set("order_shipping_address", basket.path("address"));
        body.put("order_contact_email", basket.path("email").asText());
        body.put("order_contact_phone", basket.path("phone").asText());
        body.put("reference", basket.path("reference").asText());

        JsonNode order;
        try {
            order = Nurishd.call("POST", "/meals/v1/order/create/document", Map.of(), body);
        } catch (NurishdException error) {
            fail(ctx, error.status, error.code, error.getMessage());
            return;
        }

        // Send the browser only what it needs to pay.
        ObjectNode answer = Nurishd.JSON.createObjectNode();
        answer.put("order_id", order.path("order_id").asText());
        JsonNode secret = order.path("stripe_payment_intent").path("stripe_payment_intent_client_secret");
        answer.set("client_secret", secret.isMissingNode() ? Nurishd.JSON.nullNode() : secret);
        answer.set("publishable_key", order.path("stripe_publishable_key"));
        ctx.status(201).json(answer);
    }
```

## 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](https://docs.stripe.com/testing).

## 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.

| Field                      | Value             | What it means for your customer                   |
| -------------------------- | ----------------- | ------------------------------------------------- |
| `order_financial_status`   | `pending`         | The order waits for the payment.                  |
| `order_financial_status`   | `paid`            | The payment went through. The order is confirmed. |
| `order_financial_status`   | `failed payment`  | The payment did not go through.                   |
| `order_financial_status`   | `refunded`        | The money went back to the customer.              |
| `order_financial_status`   | `cancelled`       | The order was cancelled.                          |
| `order_fulfillment_status` | `pending payment` | The kitchen waits for the payment.                |
| `order_fulfillment_status` | `not started`     | The kitchen has not started yet.                  |
| `order_fulfillment_status` | `preparing meals` | The kitchen is cooking the meals.                 |
| `order_fulfillment_status` | `completed`       | The meals are ready.                              |
| `order_delivery_status`    | `pending payment` | Nothing ships before the payment.                 |
| `order_delivery_status`    | `not yet shipped` | The order waits for the courier.                  |
| `order_delivery_status`    | `shipped`         | The order is on its way.                          |
| `order_delivery_status`    | `delivered`       | The order arrived.                                |
| `order_delivery_status`    | `delivery failed` | The 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)
```

```javascript
function say(order) {
	const payment = order.order_financial_status;
	const 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 `Payment status: ${payment}.`;
}

app.get('/orders/:orderId', async (req, res) => {
	const orderId = req.params.orderId;
	if (!ORDER_ID.test(orderId)) {
		return res.status(400).json({
			code: 'bad_order_id',
			message: 'This order id is not valid.',
		});
	}
	let order;
	try {
		order = await call('GET', `/meals/v1/order/${orderId}/get/document`);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return refusal(res, error);
	}
	res.json({
		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.listen(3000, () => console.log('Listening on http://localhost:3000'));
```

```typescript
function say(order: Order): string {
	const payment = order.order_financial_status;
	const 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 `Payment status: ${payment}.`;
}

app.get('/orders/:orderId', async (req, res) => {
	const orderId = req.params.orderId;
	if (!ORDER_ID.test(orderId)) {
		return res.status(400).json({
			code: 'bad_order_id',
			message: 'This order id is not valid.',
		});
	}
	let order: Order;
	try {
		order = await call<Order>(
			'GET',
			`/meals/v1/order/${orderId}/get/document`,
		);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return refusal(res, error);
	}
	res.json({
		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.listen(3000, () => console.log('Listening on http://localhost:3000'));
```

```java
    static String say(JsonNode order) {
        String payment = order.path("order_financial_status").asText();
        String delivery = order.path("order_delivery_status").asText();
        if (payment.equals("pending")) return "Waiting for payment.";
        if (payment.equals("failed payment")) return "The payment failed.";
        if (payment.equals("paid")) {
            if (delivery.equals("delivered")) return "Delivered.";
            if (delivery.equals("shipped")) return "On its way.";
            return "Paid. The kitchen is getting it ready.";
        }
        return "Payment status: " + payment + ".";
    }

    static void readOrder(Context ctx) {
        String orderId = ctx.pathParam("orderId");
        if (!ORDER_ID.matcher(orderId).matches()) {
            fail(ctx, 400, "bad_order_id", "This order id is not valid.");
            return;
        }
        JsonNode order;
        try {
            order = Nurishd.call("GET", "/meals/v1/order/%s/get/document".formatted(orderId));
        } catch (NurishdException error) {
            fail(ctx, error.status, error.code, error.getMessage());
            return;
        }
        ObjectNode answer = Nurishd.JSON.createObjectNode();
        answer.put("order_id", order.path("order_id").asText());
        answer.put("summary", say(order));
        answer.set("payment", order.path("order_financial_status"));
        answer.set("kitchen", order.path("order_fulfillment_status"));
        answer.set("delivery", order.path("order_delivery_status"));
        answer.set("total_cents", order.path("order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING"));
        answer.set("currency", order.path("order_currency"));
        ctx.json(answer);
    }

    public static void main(String[] args) {
        // Javalin serves the files in public/ at the site root, so public/pay.html is /pay.html.
        Javalin app = Javalin.create(config -> config.staticFiles.add("public", Location.EXTERNAL));
        app.post("/orders", Orders::placeOrder);
        app.get("/orders/{orderId}", Orders::readOrder);
        app.start(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 send                    | The rule                                                                                        |
| -------------------------------- | ----------------------------------------------------------------------------------------------- |
| `delivery_date`                  | `YYYY-MM-DD`, the date part of a delivery date the zone offers. No time of day.                 |
| `items`                          | 1 to 50 items. Each has a product id and a quantity of at least 1. A product appears only once. |
| Each product                     | It must be offered on that date. See [Catalog](/docs/meals/catalog).                            |
| The order as a whole             | It must meet the vendor's limits on items and value, such as the minimum order.                 |
| `address.line1`, `line2`, `city` | Up to 200, 200 and 100 characters. `$`, `{` and `}` are not accepted.                           |
| `address.state`, `country`       | Two capital letters, such as `ON` and `CA`.                                                     |
| `address.postal_code`            | Letters, digits, spaces and hyphens, up to 20 characters.                                       |
| `phone`                          | The 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.

| Language   | Command                                                     |
| ---------- | ----------------------------------------------------------- |
| Python     | `python orders.py`                                          |
| JavaScript | `node orders.js`                                            |
| TypeScript | `node orders.ts`                                            |
| Java       | `mvn -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
```

```text
{"order_id":"ORD-ONE-OFF-4F7K2A9Q","summary":"Waiting for payment.","payment":"pending","kitchen":"pending payment","delivery":"pending payment","total_cents":7874,"currency":"CAD"}
```

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](/docs/tutorials/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)
```

```javascript
// file: orders.js
import express from 'express';

import { NurishdError, call } from './nurishd.js';

const app = express();
app.use(express.json());
// Express serves the files in public/ at the site root, so public/pay.html is /pay.html.
app.use(express.static('public'));

const 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.
const ORDER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/;

function refusal(res, error) {
	res.status(error.status).json({ code: error.code, message: error.message });
}

app.post('/orders', async (req, res) => {
	const basket = req.body;
	const missing = REQUIRED.filter((name) => !(name in basket));
	if (missing.length > 0) {
		return res.status(400).json({
			code: 'bad_basket',
			message: 'Missing: ' + missing.join(', '),
		});
	}

	let order;
	try {
		order = await 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: basket.items.map((item) => ({
					line_item_product_id: item.product_id,
					line_quantity: item.quantity,
				})),
				order_shipping_address: basket.address,
				order_contact_email: basket.email,
				order_contact_phone: basket.phone,
				reference: basket.reference,
			},
		});
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return refusal(res, error);
	}

	// Send the browser only what it needs to pay.
	res.status(201).json({
		order_id: order.order_id,
		client_secret:
			order.stripe_payment_intent?.stripe_payment_intent_client_secret ??
			null,
		publishable_key: order.stripe_publishable_key,
	});
});

function say(order) {
	const payment = order.order_financial_status;
	const 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 `Payment status: ${payment}.`;
}

app.get('/orders/:orderId', async (req, res) => {
	const orderId = req.params.orderId;
	if (!ORDER_ID.test(orderId)) {
		return res.status(400).json({
			code: 'bad_order_id',
			message: 'This order id is not valid.',
		});
	}
	let order;
	try {
		order = await call('GET', `/meals/v1/order/${orderId}/get/document`);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return refusal(res, error);
	}
	res.json({
		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.listen(3000, () => console.log('Listening on http://localhost:3000'));
```

```typescript
// file: orders.ts
import express, { type Response } from 'express';

import { NurishdError, call } from './nurishd.ts';

interface Basket {
	customer_id: string;
	vendor_id: string;
	delivery_date: string;
	items: { product_id: string; quantity: number }[];
	address: Record<string, string>;
	email: string;
	phone: string;
	reference: string;
}

interface Order {
	order_id: string;
	order_financial_status: string;
	order_fulfillment_status: string;
	order_delivery_status: string;
	order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING: number;
	order_currency: string;
	stripe_payment_intent: {
		stripe_payment_intent_client_secret: string;
	} | null;
	stripe_publishable_key: string | null;
}

const app = express();
app.use(express.json());
// Express serves the files in public/ at the site root, so public/pay.html is /pay.html.
app.use(express.static('public'));

const 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.
const ORDER_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/;

function refusal(res: Response, error: NurishdError) {
	res.status(error.status).json({ code: error.code, message: error.message });
}

app.post('/orders', async (req, res) => {
	const basket = req.body as Basket;
	const missing = REQUIRED.filter((name) => !(name in basket));
	if (missing.length > 0) {
		return res.status(400).json({
			code: 'bad_basket',
			message: 'Missing: ' + missing.join(', '),
		});
	}

	let order: Order;
	try {
		order = await call<Order>('POST', '/meals/v1/order/create/document', {
			body: {
				user: basket.customer_id,
				order_vendor: basket.vendor_id,
				order_delivery_date: basket.delivery_date,
				line_items: basket.items.map((item) => ({
					line_item_product_id: item.product_id,
					line_quantity: item.quantity,
				})),
				order_shipping_address: basket.address,
				order_contact_email: basket.email,
				order_contact_phone: basket.phone,
				reference: basket.reference,
			},
		});
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return refusal(res, error);
	}

	// Send the browser only what it needs to pay.
	res.status(201).json({
		order_id: order.order_id,
		client_secret:
			order.stripe_payment_intent?.stripe_payment_intent_client_secret ??
			null,
		publishable_key: order.stripe_publishable_key,
	});
});

function say(order: Order): string {
	const payment = order.order_financial_status;
	const 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 `Payment status: ${payment}.`;
}

app.get('/orders/:orderId', async (req, res) => {
	const orderId = req.params.orderId;
	if (!ORDER_ID.test(orderId)) {
		return res.status(400).json({
			code: 'bad_order_id',
			message: 'This order id is not valid.',
		});
	}
	let order: Order;
	try {
		order = await call<Order>(
			'GET',
			`/meals/v1/order/${orderId}/get/document`,
		);
	} catch (error) {
		if (!(error instanceof NurishdError)) throw error;
		return refusal(res, error);
	}
	res.json({
		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.listen(3000, () => console.log('Listening on http://localhost:3000'));
```

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

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.javalin.Javalin;
import io.javalin.http.Context;
import io.javalin.http.staticfiles.Location;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import tutorial.Nurishd.NurishdException;

public class Orders {
    static final List<String> REQUIRED =
            List.of("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.
    static final Pattern ORDER_ID = Pattern.compile("[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}");

    static void fail(Context ctx, int status, String code, String message) {
        ObjectNode body = Nurishd.JSON.createObjectNode();
        body.put("code", code);
        body.put("message", message);
        ctx.status(status).json(body);
    }

    static void placeOrder(Context ctx) throws Exception {
        JsonNode basket = Nurishd.JSON.readTree(ctx.body());
        List<String> missing = new ArrayList<>();
        for (String name : REQUIRED) {
            if (!basket.has(name)) missing.add(name);
        }
        if (!missing.isEmpty()) {
            fail(ctx, 400, "bad_basket", "Missing: " + String.join(", ", missing));
            return;
        }

        ObjectNode body = Nurishd.JSON.createObjectNode();
        body.put("user", basket.path("customer_id").asText());
        body.put("order_vendor", basket.path("vendor_id").asText());
        body.put("order_delivery_date", basket.path("delivery_date").asText());
        ArrayNode lineItems = body.putArray("line_items");
        for (JsonNode item : basket.path("items")) {
            ObjectNode line = lineItems.addObject();
            line.put("line_item_product_id", item.path("product_id").asText());
            line.put("line_quantity", item.path("quantity").asInt());
        }
        body.set("order_shipping_address", basket.path("address"));
        body.put("order_contact_email", basket.path("email").asText());
        body.put("order_contact_phone", basket.path("phone").asText());
        body.put("reference", basket.path("reference").asText());

        JsonNode order;
        try {
            order = Nurishd.call("POST", "/meals/v1/order/create/document", Map.of(), body);
        } catch (NurishdException error) {
            fail(ctx, error.status, error.code, error.getMessage());
            return;
        }

        // Send the browser only what it needs to pay.
        ObjectNode answer = Nurishd.JSON.createObjectNode();
        answer.put("order_id", order.path("order_id").asText());
        JsonNode secret = order.path("stripe_payment_intent").path("stripe_payment_intent_client_secret");
        answer.set("client_secret", secret.isMissingNode() ? Nurishd.JSON.nullNode() : secret);
        answer.set("publishable_key", order.path("stripe_publishable_key"));
        ctx.status(201).json(answer);
    }

    static String say(JsonNode order) {
        String payment = order.path("order_financial_status").asText();
        String delivery = order.path("order_delivery_status").asText();
        if (payment.equals("pending")) return "Waiting for payment.";
        if (payment.equals("failed payment")) return "The payment failed.";
        if (payment.equals("paid")) {
            if (delivery.equals("delivered")) return "Delivered.";
            if (delivery.equals("shipped")) return "On its way.";
            return "Paid. The kitchen is getting it ready.";
        }
        return "Payment status: " + payment + ".";
    }

    static void readOrder(Context ctx) {
        String orderId = ctx.pathParam("orderId");
        if (!ORDER_ID.matcher(orderId).matches()) {
            fail(ctx, 400, "bad_order_id", "This order id is not valid.");
            return;
        }
        JsonNode order;
        try {
            order = Nurishd.call("GET", "/meals/v1/order/%s/get/document".formatted(orderId));
        } catch (NurishdException error) {
            fail(ctx, error.status, error.code, error.getMessage());
            return;
        }
        ObjectNode answer = Nurishd.JSON.createObjectNode();
        answer.put("order_id", order.path("order_id").asText());
        answer.put("summary", say(order));
        answer.set("payment", order.path("order_financial_status"));
        answer.set("kitchen", order.path("order_fulfillment_status"));
        answer.set("delivery", order.path("order_delivery_status"));
        answer.set("total_cents", order.path("order_total_price__AFTER_TAX_DISCOUNT_AND_SHIPPING"));
        answer.set("currency", order.path("order_currency"));
        ctx.json(answer);
    }

    public static void main(String[] args) {
        // Javalin serves the files in public/ at the site root, so public/pay.html is /pay.html.
        Javalin app = Javalin.create(config -> config.staticFiles.add("public", Location.EXTERNAL));
        app.post("/orders", Orders::placeOrder);
        app.get("/orders/{orderId}", Orders::readOrder);
        app.start(3000);
    }
}
```

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

## If something goes wrong

| What you see                            | Why                                                         | What to do                                                                                |
| --------------------------------------- | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
| `409 connection_not_active`             | The customer has not approved, or they revoked the link.    | Send the customer through [Connect a customer](/docs/tutorials/connect-a-customer) again. |
| `403 connection_scope_not_granted`      | The customer did not allow orders.                          | Ask the customer to approve again.                                                        |
| `403 scope_not_granted`                 | Your key lacks `order:write` or `order:read`.               | Create a key with both scopes.                                                            |
| `404 not_found` when you place an order | The 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_available`            | The vendor does not deliver to the address or on that date. | Check the zone and the dates again.                                                       |
| `422 product_not_available`             | A product is not offered on that date.                      | Read the date's product ids and choose again.                                             |
| `422 order_limits_not_met`              | The order is under or over the vendor's limits.             | Change the items.                                                                         |
| `422 vendor_not_allowed_for_customer`   | The customer can order only from some vendors.              | Offer another vendor.                                                                     |
| `422 validation_error`                  | A field breaks a rule of step 5. The message names it.      | Fix the field. Do not send it again unchanged.                                            |
| `409 order_conflict`                    | The order cannot be placed in its current state.            | Read the order, then decide. Do not retry unchanged.                                      |

## Next

- [Orders](/docs/meals/orders): every order route, the list and the events.
- [Saving a card](/docs/meals/saving-a-card): let a customer pay with a saved card.
- [Receive order webhooks](/docs/tutorials/receive-order-webhooks): learn when an order is paid.
- [Errors](/docs/concepts/errors): every error code.
