---
title: Use Nurish'd with a Shopify store
description: Build a small server that your Shopify store reaches through an app proxy, to connect shoppers to Nurish'd, list meals for their address and place meal orders.
section: Tutorials
order: 9
---

# Use Nurish'd with a Shopify store

Nurish'd has no Shopify app or plugin. You build the bridge yourself: one small server of your own that calls the Nurish'd API, reached from your store through a Shopify app proxy. When it runs, a shopper who is signed in to your store connects their Nurish'd account, sees the meals that can be delivered to their address, and places a meal order.

## What this does and does not do

- It connects a shopper of your store to Nurish'd, lists meals for the shopper's default Shopify address, and places Nurish'd meal orders for them.
- A Nurish'd meal order is not a Shopify order. It does not go through Shopify checkout, and Shopify takes no payment for it.
- The shopper pays Nurish'd for the meals in the browser with Stripe.js, using the payment intent that the order answer carries. See [Orders](/docs/meals/orders). The Nurish'd API has no way to take the payment through Shopify checkout.
- Your Nurish'd API key stays on your server. It never goes into theme code, a Liquid template or the browser.

## How the pieces fit

An app proxy is a Shopify feature. Shopify takes requests for one path on your store's domain and forwards them to your server. See [About app proxies](https://shopify.dev/docs/apps/build/online-store/app-proxies). The Admin API is Shopify's API for reading store data, such as a customer.

```text
Shopper's browser
  GET https://shop.example.com/apps/nurishd/meals
        |
Shopify app proxy: adds who the shopper is, then signs the request
  GET https://your-server.example.com/proxy/meals?logged_in_customer_id=...&signature=...
        |
Your server: checks the signature, reads the customer from the Shopify Admin API,
             calls the Nurish'd API with your key
```

The shopper only ever talks to your store's domain. Your server is the only place that holds your Nurish'd key and your Shopify secrets.

## 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 scopes `catalog:read`, `order:read` and `order:write`. Run `check_key` from the setup tutorial to see your scopes.
- You know the connect flow from [Connect a customer](/docs/tutorials/connect-a-customer). This tutorial uses it without explaining it again.
- You have a Shopify store and you can create apps in the [Dev Dashboard](https://shopify.dev/docs/apps/build/dev-dashboard/create-apps-using-dev-dashboard). The app and the store must be in the same Shopify organization. Step 1 says why.
- Your server needs a public HTTPS address, because Shopify must reach it. While you build, use a tunnel tool, as in [Receive order webhooks](/docs/tutorials/receive-order-webhooks).
- 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. Create the Shopify app

Your server talks to Shopify as an app. Create it in the Dev Dashboard. These steps follow [Create apps using the Dev Dashboard](https://shopify.dev/docs/apps/build/dev-dashboard/create-apps-using-dev-dashboard) and [About app proxies](https://shopify.dev/docs/apps/build/online-store/app-proxies).

1. In the [Dev Dashboard](https://dev.shopify.com/dashboard/), open **Apps**, select **Create app**, then **Start from Dev Dashboard**. Name the app and select **Create**.
2. Open **Versions** and create a version. For **App URL**, keep `https://shopify.dev/apps/default-app-home`: this app has no page inside the Shopify admin.
3. Under **Scopes**, add `read_customers` and `write_app_proxy`. `read_customers` lets your server read a customer. `write_app_proxy` is needed to set up an app proxy.
4. Under **App proxy**, set the prefix to `apps`, the subpath to `nurishd`, and the proxy URL to `https://your-server.example.com/proxy`. Then select **Release**.
5. Select **Install app** and install the app on your store.
6. Open **Settings** and copy the **Client ID** and the **Client secret**.

With this proxy, `https://shop.example.com/apps/nurishd/connect` goes to `https://your-server.example.com/proxy/connect`. A store owner can change the prefix and subpath in the Shopify admin. If they do, the store URLs in this tutorial change too, and you register the new return URL.

Your server reads a customer's name, email and address. Shopify calls this protected customer data and has rules for it. In development, you select the data and the fields you use. In the Dev Dashboard, open your app's **Settings**, then **Access requests**, and next to **Protected customer data** select **Manage**. Select **Customer data** and the fields **Name**, **Email** and **Address**, give your reasons, and save. The steps and Shopify's rules for this data are in [Protected customer data](https://shopify.dev/docs/apps/launch/protected-customer-data). A field your app may not read comes back empty, with an error that names it.

Your server gets its Admin API access token from the Client ID and the Client secret. Shopify calls this the client credentials grant. It works only when the app and the store are in the same Shopify organization, and each token lasts 24 hours. See [Authenticate an app for stores in your organization](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant). For a store of another organization, Shopify has other ways to get a token, listed in [About app authentication](https://shopify.dev/docs/apps/build/authentication-authorization).

Last, register the return URL in the Nurish'd console. A return URL is where Nurish'd sends the shopper after they approve. Open **Settings**, find **Return URLs**, and add `https://shop.example.com/apps/nurishd/return` with your store's own domain. See [Company settings](/docs/console/company-settings).

Put the Shopify values and the return URL in variables, next to `NURISHD_API_KEY`. `SHOPIFY_SHOP` is your store's `myshopify.com` domain.

macOS and Linux:

```bash
export SHOPIFY_SHOP="your-store.myshopify.com"
export SHOPIFY_CLIENT_ID="your-client-id"
export SHOPIFY_CLIENT_SECRET="your-client-secret"
export RETURN_URL="https://shop.example.com/apps/nurishd/return"
```

Windows PowerShell:

```powershell
$env:SHOPIFY_SHOP = "your-store.myshopify.com"
$env:SHOPIFY_CLIENT_ID = "your-client-id"
$env:SHOPIFY_CLIENT_SECRET = "your-client-secret"
$env:RETURN_URL = "https://shop.example.com/apps/nurishd/return"
```

The client secret is a password for your app. Keep it on your server, like your Nurish'd key.

## 2. Check the proxy signature

Shopify adds these query parameters to every request it forwards. See [Authenticate app proxies](https://shopify.dev/docs/apps/build/online-store/app-proxies/authenticate-app-proxies).

| Parameter               | What it holds                                                         |
| ----------------------- | --------------------------------------------------------------------- |
| `shop`                  | The store's `myshopify.com` domain.                                   |
| `path_prefix`           | The store path that was forwarded, such as `/apps/nurishd`.           |
| `timestamp`             | A time in seconds since 1 January 1970, UTC.                          |
| `logged_in_customer_id` | The id of the shopper who is signed in to the store. Empty when none. |
| `signature`             | A signature of all the other parameters, made with your app's secret. |

Your server must refuse a request whose signature does not verify. Your server's address is public, so anyone can call it. Without the check, anyone could add `logged_in_customer_id` to the address and act as any customer of your store.

Shopify makes the signature like this, and your server does the same and compares:

1. Read the query string as it arrived and decode each value. Take out `signature`.
2. Write each parameter as `name=value`. A parameter that appears more than once is written once, with its values joined by commas: `extra=1&extra=2` becomes `extra=1,2`.
3. Sort these pieces and join them with nothing between them.
4. Compute the HMAC-SHA256 of that text with your app's client secret as the key, written as hex.
5. Compare it with `signature`. Use a constant-time comparison, which takes the same time whether the values match or not, so an attacker learns nothing from the timing.

The code reads the raw query string itself. A framework's own query parser can drop empty values or merge repeated ones, and then the signature no longer matches. The check runs before every route.

```python
def proxy_signature_ok(query_string):
    """Checks the signature Shopify adds to every app proxy request."""
    values = {}
    signature = ""
    for name, value in parse_qsl(query_string, keep_blank_values=True):
        if name == "signature":
            signature = value
        else:
            values.setdefault(name, []).append(value)
    message = "".join(
        sorted(f"{name}={','.join(items)}" for name, items in values.items())
    )
    expected = hmac.new(
        SHOPIFY_CLIENT_SECRET.encode(), message.encode(), hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, signature)


@app.before_request
def check_signature():
    if not proxy_signature_ok(request.query_string.decode()):
        abort(401)
```

```javascript
/** Checks the signature Shopify adds to every app proxy request. */
function proxySignatureOk(queryString) {
	const values = new Map();
	let signature = '';
	for (const [name, value] of new URLSearchParams(queryString)) {
		if (name === 'signature') signature = value;
		else values.set(name, [...(values.get(name) ?? []), value]);
	}
	const message = [...values]
		.map(([name, items]) => `${name}=${items.join(',')}`)
		.sort()
		.join('');
	const expected = crypto
		.createHmac('sha256', SHOPIFY_CLIENT_SECRET)
		.update(message)
		.digest('hex');
	return (
		signature.length === expected.length &&
		crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
	);
}

app.use((req, res, next) => {
	const queryString = req.originalUrl.split('?')[1] ?? '';
	if (!proxySignatureOk(queryString)) return res.sendStatus(401);
	next();
});
```

```typescript
/** Checks the signature Shopify adds to every app proxy request. */
function proxySignatureOk(queryString: string): boolean {
	const values = new Map<string, string[]>();
	let signature = '';
	for (const [name, value] of new URLSearchParams(queryString)) {
		if (name === 'signature') signature = value;
		else values.set(name, [...(values.get(name) ?? []), value]);
	}
	const message = [...values]
		.map(([name, items]) => `${name}=${items.join(',')}`)
		.sort()
		.join('');
	const expected = crypto
		.createHmac('sha256', SHOPIFY_CLIENT_SECRET)
		.update(message)
		.digest('hex');
	return (
		signature.length === expected.length &&
		crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
	);
}

app.use((req, res, next) => {
	const queryString = req.originalUrl.split('?')[1] ?? '';
	if (!proxySignatureOk(queryString)) return res.sendStatus(401);
	next();
});
```

```java
/** Checks the signature Shopify adds to every app proxy request. */
static boolean proxySignatureOk(String queryString) throws Exception {
    Map<String, List<String>> values = new HashMap<>();
    String signature = "";
    for (String pair : (queryString == null ? "" : queryString).split("&")) {
        if (pair.isEmpty()) continue;
        String[] parts = pair.split("=", 2);
        String name = URLDecoder.decode(parts[0], StandardCharsets.UTF_8);
        String value = parts.length > 1 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : "";
        if (name.equals("signature")) signature = value;
        else values.computeIfAbsent(name, key -> new ArrayList<>()).add(value);
    }
    List<String> pieces = new ArrayList<>();
    values.forEach((name, items) -> pieces.add(name + "=" + String.join(",", items)));
    pieces.sort(null);
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(SHOPIFY_CLIENT_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
    String expected = HexFormat.of()
            .formatHex(mac.doFinal(String.join("", pieces).getBytes(StandardCharsets.UTF_8)));
    return MessageDigest.isEqual(
            expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8));
}

app.before(ctx -> {
    if (!proxySignatureOk(ctx.queryString())) throw new UnauthorizedResponse();
});
```

A valid signature proves the request came through Shopify unchanged. It does not prove the shopper may see the data they ask for. Shopify's doc asks you to check that too. This server only ever reads data of the shopper in `logged_in_customer_id`.

## 3. Know who the shopper is

`logged_in_customer_id` is the Shopify id of the signed-in shopper. When it is empty, the shopper is not signed in to the store, and your server answers with a short page that links to the store's sign-in.

A proxy answer with the content type `application/liquid` is shown inside your store's theme. Shopify also fills in any Liquid in it. Liquid is Shopify's template language, and `{{ routes.account_login_url }}` is the store's sign-in address. See [App proxies: Liquid response](https://shopify.dev/docs/apps/build/online-store/app-proxies#liquid-response) and [routes](https://shopify.dev/docs/api/liquid/objects/routes).

```python
def page(html):
    """A page Shopify shows inside the store's theme."""
    return Response(html, content_type="application/liquid")


def sign_in_page():
    """Asks the shopper to sign in. Shopify fills in the sign-in link."""
    return page(
        "<p>Sign in to the store first.</p>"
        '<p><a href="{{ routes.account_login_url }}">Sign in</a></p>'
    )
```

```javascript
/** A page Shopify shows inside the store's theme. */
function page(res, html) {
	res.type('application/liquid').end(html);
}

/** Asks the shopper to sign in. Shopify fills in the sign-in link. */
function signInPage(res) {
	page(
		res,
		'<p>Sign in to the store first.</p><p><a href="{{ routes.account_login_url }}">Sign in</a></p>',
	);
}
```

```typescript
/** A page Shopify shows inside the store's theme. */
function page(res: Response, html: string) {
	res.type('application/liquid').end(html);
}

/** Asks the shopper to sign in. Shopify fills in the sign-in link. */
function signInPage(res: Response) {
	page(
		res,
		'<p>Sign in to the store first.</p><p><a href="{{ routes.account_login_url }}">Sign in</a></p>',
	);
}
```

```java
/** A page Shopify shows inside the store's theme. */
static void page(Context ctx, String html) {
    ctx.contentType("application/liquid").result(html);
}

/** Asks the shopper to sign in. Shopify fills in the sign-in link. */
static void signInPage(Context ctx) {
    page(ctx, "<p>Sign in to the store first.</p>"
            + "<p><a href=\"{{ routes.account_login_url }}\">Sign in</a></p>");
}
```

Nurish'd knows each customer by an `external_id`, an id of your own. Here it is `shopify-` followed by the Shopify customer id, for example `shopify-1001`. The Shopify id never changes for that shopper, so the same person always gets the same `external_id`. That matters: Nurish'd accepts one `external_id` per person and refuses a second one for the same email. See [Connections](/docs/concepts/connections#one-external-id-per-person).

## 4. Read the customer from Shopify

Two small functions talk to Shopify. `shopify_token` gets an Admin API access token and keeps it until shortly before it expires. `shopify_customer` asks the GraphQL Admin API for the customer's name, email and default address. GraphQL is a query language: you list the fields you want and get only those.

The Admin API has dated versions, such as `2026-10`, and a new one comes out every three months. Put the version you use in `SHOPIFY_API_VERSION`. See [API versioning](https://shopify.dev/docs/api/usage/versioning). The query uses the [customer](https://shopify.dev/docs/api/admin-graphql/latest/queries/customer) query, which needs the `read_customers` scope.

`SHOPIFY_URL` is for local tests only. Leave it unset and the code calls your store.

```python
SHOPIFY_SHOP = os.environ["SHOPIFY_SHOP"]
SHOPIFY_CLIENT_ID = os.environ["SHOPIFY_CLIENT_ID"]
SHOPIFY_CLIENT_SECRET = os.environ["SHOPIFY_CLIENT_SECRET"]
SHOPIFY_API_VERSION = "2026-10"
# For local tests only: send the Shopify calls to a fake server.
SHOPIFY_URL = os.environ.get("SHOPIFY_URL", f"https://{SHOPIFY_SHOP}")
RETURN_URL = os.environ["RETURN_URL"]


def shopify_token():
    """Gets an Admin API access token. Shopify's tokens last 24 hours."""
    if time.time() < token["expires_at"] - 60:
        return token["value"]
    res = requests.post(
        f"{SHOPIFY_URL}/admin/oauth/access_token",
        data={
            "grant_type": "client_credentials",
            "client_id": SHOPIFY_CLIENT_ID,
            "client_secret": SHOPIFY_CLIENT_SECRET,
        },
        timeout=30,
    )
    res.raise_for_status()
    answer = res.json()
    token["value"] = answer["access_token"]
    token["expires_at"] = time.time() + answer["expires_in"]
    return token["value"]


def shopify_customer(customer_id):
    """Reads a customer's name, email and default address from Shopify."""
    query = """
    query ($id: ID!) {
      customer(id: $id) {
        firstName
        lastName
        defaultEmailAddress { emailAddress }
        defaultAddress { address1 address2 city provinceCode countryCodeV2 zip }
      }
    }"""
    res = requests.post(
        f"{SHOPIFY_URL}/admin/api/{SHOPIFY_API_VERSION}/graphql.json",
        headers={"X-Shopify-Access-Token": shopify_token()},
        json={
            "query": query,
            "variables": {"id": f"gid://shopify/Customer/{customer_id}"},
        },
        timeout=30,
    )
    res.raise_for_status()
    answer = res.json()
    if answer.get("errors"):
        raise RuntimeError(f"Shopify said: {answer['errors']}")
    return answer["data"]["customer"]
```

```javascript
const SHOPIFY_SHOP = process.env.SHOPIFY_SHOP;
const SHOPIFY_CLIENT_ID = process.env.SHOPIFY_CLIENT_ID;
const SHOPIFY_CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET;
const SHOPIFY_API_VERSION = '2026-10';
// For local tests only: send the Shopify calls to a fake server.
const SHOPIFY_URL = process.env.SHOPIFY_URL ?? `https://${SHOPIFY_SHOP}`;
const RETURN_URL = process.env.RETURN_URL;

/** Gets an Admin API access token. Shopify's tokens last 24 hours. */
async function shopifyToken() {
	if (Date.now() < token.expiresAt - 60_000) return token.value;
	const res = await fetch(`${SHOPIFY_URL}/admin/oauth/access_token`, {
		method: 'POST',
		body: new URLSearchParams({
			grant_type: 'client_credentials',
			client_id: SHOPIFY_CLIENT_ID,
			client_secret: SHOPIFY_CLIENT_SECRET,
		}),
	});
	if (!res.ok) throw new Error(`Shopify token: ${res.status}`);
	const answer = await res.json();
	token.value = answer.access_token;
	token.expiresAt = Date.now() + answer.expires_in * 1000;
	return token.value;
}

/** Reads a customer's name, email and default address from Shopify. */
async function shopifyCustomer(customerId) {
	const query = `
	query ($id: ID!) {
	  customer(id: $id) {
	    firstName
	    lastName
	    defaultEmailAddress { emailAddress }
	    defaultAddress { address1 address2 city provinceCode countryCodeV2 zip }
	  }
	}`;
	const res = await fetch(
		`${SHOPIFY_URL}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`,
		{
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'X-Shopify-Access-Token': await shopifyToken(),
			},
			body: JSON.stringify({
				query,
				variables: { id: `gid://shopify/Customer/${customerId}` },
			}),
		},
	);
	if (!res.ok) throw new Error(`Shopify customer: ${res.status}`);
	const answer = await res.json();
	if (answer.errors)
		throw new Error(`Shopify said: ${JSON.stringify(answer.errors)}`);
	return answer.data.customer;
}
```

```typescript
const SHOPIFY_SHOP = process.env.SHOPIFY_SHOP ?? '';
const SHOPIFY_CLIENT_ID = process.env.SHOPIFY_CLIENT_ID ?? '';
const SHOPIFY_CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET ?? '';
const SHOPIFY_API_VERSION = '2026-10';
// For local tests only: send the Shopify calls to a fake server.
const SHOPIFY_URL = process.env.SHOPIFY_URL ?? `https://${SHOPIFY_SHOP}`;
const RETURN_URL = process.env.RETURN_URL ?? '';

/** Gets an Admin API access token. Shopify's tokens last 24 hours. */
async function shopifyToken(): Promise<string> {
	if (Date.now() < token.expiresAt - 60_000) return token.value;
	const res = await fetch(`${SHOPIFY_URL}/admin/oauth/access_token`, {
		method: 'POST',
		body: new URLSearchParams({
			grant_type: 'client_credentials',
			client_id: SHOPIFY_CLIENT_ID,
			client_secret: SHOPIFY_CLIENT_SECRET,
		}),
	});
	if (!res.ok) throw new Error(`Shopify token: ${res.status}`);
	const answer = (await res.json()) as {
		access_token: string;
		expires_in: number;
	};
	token.value = answer.access_token;
	token.expiresAt = Date.now() + answer.expires_in * 1000;
	return token.value;
}

/** Reads a customer's name, email and default address from Shopify. */
async function shopifyCustomer(customerId: string): Promise<ShopifyCustomer> {
	const query = `
	query ($id: ID!) {
	  customer(id: $id) {
	    firstName
	    lastName
	    defaultEmailAddress { emailAddress }
	    defaultAddress { address1 address2 city provinceCode countryCodeV2 zip }
	  }
	}`;
	const res = await fetch(
		`${SHOPIFY_URL}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`,
		{
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'X-Shopify-Access-Token': await shopifyToken(),
			},
			body: JSON.stringify({
				query,
				variables: { id: `gid://shopify/Customer/${customerId}` },
			}),
		},
	);
	if (!res.ok) throw new Error(`Shopify customer: ${res.status}`);
	const answer = (await res.json()) as {
		data: { customer: ShopifyCustomer };
		errors?: unknown;
	};
	if (answer.errors)
		throw new Error(`Shopify said: ${JSON.stringify(answer.errors)}`);
	return answer.data.customer;
}
```

```java
static final String SHOPIFY_SHOP = System.getenv("SHOPIFY_SHOP");
static final String SHOPIFY_CLIENT_ID = System.getenv("SHOPIFY_CLIENT_ID");
static final String SHOPIFY_CLIENT_SECRET = System.getenv("SHOPIFY_CLIENT_SECRET");
static final String SHOPIFY_API_VERSION = "2026-10";
// For local tests only: send the Shopify calls to a fake server.
static final String SHOPIFY_URL =
        System.getenv().getOrDefault("SHOPIFY_URL", "https://" + SHOPIFY_SHOP);
static final String RETURN_URL = System.getenv("RETURN_URL");
static final HttpClient HTTP = HttpClient.newHttpClient();

/** Gets an Admin API access token. Shopify's tokens last 24 hours. */
static synchronized String shopifyToken() throws Exception {
    if (System.currentTimeMillis() < tokenExpiresAt - 60_000) return token;
    String form = "grant_type=client_credentials"
            + "&client_id=" + URLEncoder.encode(SHOPIFY_CLIENT_ID, StandardCharsets.UTF_8)
            + "&client_secret=" + URLEncoder.encode(SHOPIFY_CLIENT_SECRET, StandardCharsets.UTF_8);
    HttpRequest request = HttpRequest.newBuilder(URI.create(SHOPIFY_URL + "/admin/oauth/access_token"))
            .header("Content-Type", "application/x-www-form-urlencoded")
            .POST(HttpRequest.BodyPublishers.ofString(form))
            .build();
    HttpResponse<String> res = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
    if (res.statusCode() != 200) throw new IllegalStateException("Shopify token: " + res.statusCode());
    JsonNode answer = Nurishd.JSON.readTree(res.body());
    token = answer.path("access_token").asText();
    tokenExpiresAt = System.currentTimeMillis() + answer.path("expires_in").asLong() * 1000;
    return token;
}

/** Reads a customer's name, email and default address from Shopify. */
static JsonNode shopifyCustomer(String customerId) throws Exception {
    String query = """
            query ($id: ID!) {
              customer(id: $id) {
                firstName
                lastName
                defaultEmailAddress { emailAddress }
                defaultAddress { address1 address2 city provinceCode countryCodeV2 zip }
              }
            }""";
    String body = Nurishd.JSON.writeValueAsString(Map.of(
            "query", query,
            "variables", Map.of("id", "gid://shopify/Customer/" + customerId)));
    HttpRequest request = HttpRequest.newBuilder(
                    URI.create(SHOPIFY_URL + "/admin/api/" + SHOPIFY_API_VERSION + "/graphql.json"))
            .header("Content-Type", "application/json")
            .header("X-Shopify-Access-Token", shopifyToken())
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
    HttpResponse<String> res = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
    if (res.statusCode() != 200) throw new IllegalStateException("Shopify customer: " + res.statusCode());
    JsonNode answer = Nurishd.JSON.readTree(res.body());
    if (answer.has("errors")) throw new IllegalStateException("Shopify said: " + answer.get("errors"));
    return answer.path("data").path("customer");
}
```

## 5. Connect the shopper

`GET /apps/nurishd/connect` reads the shopper from Shopify and creates the Nurish'd customer with `POST /meals/v1/customer/create/document`. The `return_url` is your store's return route. The answer holds the `connect_url`, the Nurish'd page where the shopper approves.

The shopper must open the Nurish'd page as a full page, never in a frame. Shopify's doc says it follows 30x redirects in a proxy answer, so a redirect may not reach the browser as a redirect. The route answers with a short page and a link instead. The shopper selects the link and the browser opens the Nurish'd page itself.

```python
@app.get("/proxy/connect")
def connect():
    customer_id = request.args.get("logged_in_customer_id", "")
    if not customer_id:
        return sign_in_page()
    shopper = shopify_customer(customer_id)
    try:
        created = call(
            "POST",
            "/meals/v1/customer/create/document",
            body={
                "external_id": f"shopify-{customer_id}",
                "email": shopper["defaultEmailAddress"]["emailAddress"],
                "first_name": shopper["firstName"],
                "last_name": shopper["lastName"],
                "return_url": RETURN_URL,
            },
        )
    except NurishdError as error:
        if error.code == "person_already_connected":
            return page("<p>This email is already connected under another store account.</p>")
        raise
    if created["connection"]["status"] == "active":
        connected[customer_id] = created["user"]
        return page("<p>Your Nurish'd account is already connected.</p>")
    return page(
        "<p>Nurish'd asks you to approve the connection on its own page.</p>"
        f'<p><a href="{created["connect_url"]}">Continue to Nurish\'d</a></p>'
    )
```

```javascript
app.get('/proxy/connect', async (req, res) => {
	const customerId = req.query.logged_in_customer_id ?? '';
	if (!customerId) return signInPage(res);
	const shopper = await shopifyCustomer(customerId);
	let created;
	try {
		created = await call('POST', '/meals/v1/customer/create/document', {
			body: {
				external_id: `shopify-${customerId}`,
				email: shopper.defaultEmailAddress.emailAddress,
				first_name: shopper.firstName,
				last_name: shopper.lastName,
				return_url: RETURN_URL,
			},
		});
	} catch (error) {
		if (
			error instanceof NurishdError &&
			error.code === 'person_already_connected'
		) {
			return page(
				res,
				'<p>This email is already connected under another store account.</p>',
			);
		}
		throw error;
	}
	if (created.connection.status === 'active') {
		connected.set(customerId, created.user);
		return page(res, "<p>Your Nurish'd account is already connected.</p>");
	}
	page(
		res,
		"<p>Nurish'd asks you to approve the connection on its own page.</p>" +
			`<p><a href="${created.connect_url}">Continue to Nurish'd</a></p>`,
	);
});
```

```typescript
app.get('/proxy/connect', async (req, res) => {
	const customerId = String(req.query.logged_in_customer_id ?? '');
	if (!customerId) return signInPage(res);
	const shopper = await shopifyCustomer(customerId);
	let created: CreatedCustomer;
	try {
		created = await call<CreatedCustomer>(
			'POST',
			'/meals/v1/customer/create/document',
			{
				body: {
					external_id: `shopify-${customerId}`,
					email: shopper.defaultEmailAddress.emailAddress,
					first_name: shopper.firstName,
					last_name: shopper.lastName,
					return_url: RETURN_URL,
				},
			},
		);
	} catch (error) {
		if (
			error instanceof NurishdError &&
			error.code === 'person_already_connected'
		) {
			return page(
				res,
				'<p>This email is already connected under another store account.</p>',
			);
		}
		throw error;
	}
	if (created.connection.status === 'active') {
		connected.set(customerId, created.user);
		return page(res, "<p>Your Nurish'd account is already connected.</p>");
	}
	page(
		res,
		"<p>Nurish'd asks you to approve the connection on its own page.</p>" +
			`<p><a href="${created.connect_url}">Continue to Nurish'd</a></p>`,
	);
});
```

```java
static void connect(Context ctx) throws Exception {
    String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault("");
    if (customerId.isEmpty()) {
        signInPage(ctx);
        return;
    }
    JsonNode shopper = shopifyCustomer(customerId);
    JsonNode created;
    try {
        created = Nurishd.call("POST", "/meals/v1/customer/create/document", Map.of(), Map.of(
                "external_id", "shopify-" + customerId,
                "email", shopper.path("defaultEmailAddress").path("emailAddress").asText(),
                "first_name", shopper.path("firstName").asText(),
                "last_name", shopper.path("lastName").asText(),
                "return_url", RETURN_URL));
    } catch (Nurishd.NurishdException error) {
        if (!error.code.equals("person_already_connected")) throw error;
        page(ctx, "<p>This email is already connected under another store account.</p>");
        return;
    }
    if (created.path("connection").path("status").asText().equals("active")) {
        connected.put(customerId, created.path("user").asText());
        page(ctx, "<p>Your Nurish'd account is already connected.</p>");
        return;
    }
    page(ctx, "<p>Nurish'd asks you to approve the connection on its own page.</p>"
            + "<p><a href=\"" + created.path("connect_url").asText() + "\">Continue to Nurish'd</a></p>");
}
```

When the email is already connected under another `external_id`, create answers `409 person_already_connected` and the route says so. When the connection is already `active`, there is nothing to approve and the route says the account is connected.

## 6. Handle the return

After the shopper decides, Nurish'd sends them to your return URL with `connection_id` and `status` in the query. The shopper lands on your store, so the request comes through the proxy and is signed like any other.

Never trust the `status` in the address: anyone can edit it. The route reads the connection with `GET /meals/v1/connection/{connection_id}/get/document`, checks that its `external_id` belongs to this shopper, and checks that it is `active`. Then it remembers the Nurish'd customer id for the Shopify customer.

This tutorial keeps that in memory, so a restart forgets it. A real app keeps it in its own database.

```python
# Shopify customer id -> Nurish'd customer id. A real app keeps this in its database.
connected = {}
```

```javascript
// Shopify customer id -> Nurish'd customer id. A real app keeps this in its database.
const connected = new Map();
```

```typescript
// Shopify customer id -> Nurish'd customer id. A real app keeps this in its database.
const connected = new Map<string, string>();
```

```java
// Shopify customer id -> Nurish'd customer id. A real app keeps this in its database.
static final Map<String, String> connected = new HashMap<>();
```

The return route:

```python
@app.get("/proxy/return")
def returned():
    customer_id = request.args.get("logged_in_customer_id", "")
    if not customer_id:
        return sign_in_page()
    connection_id = request.args.get("connection_id", "")
    connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document")
    if connection["external_id"] != f"shopify-{customer_id}":
        abort(403)
    if connection["status"] != "active":
        return page("<p>The connection was not approved.</p>")
    connected[customer_id] = connection["user"]
    return page("<p>Your Nurish'd account is connected.</p>")
```

```javascript
app.get('/proxy/return', async (req, res) => {
	const customerId = req.query.logged_in_customer_id ?? '';
	if (!customerId) return signInPage(res);
	const connectionId = req.query.connection_id ?? '';
	const connection = await call(
		'GET',
		`/meals/v1/connection/${connectionId}/get/document`,
	);
	if (connection.external_id !== `shopify-${customerId}`)
		return res.sendStatus(403);
	if (connection.status !== 'active')
		return page(res, '<p>The connection was not approved.</p>');
	connected.set(customerId, connection.user);
	page(res, "<p>Your Nurish'd account is connected.</p>");
});
```

```typescript
app.get('/proxy/return', async (req, res) => {
	const customerId = String(req.query.logged_in_customer_id ?? '');
	if (!customerId) return signInPage(res);
	const connectionId = String(req.query.connection_id ?? '');
	const connection = await call<Connection>(
		'GET',
		`/meals/v1/connection/${connectionId}/get/document`,
	);
	if (connection.external_id !== `shopify-${customerId}`)
		return res.sendStatus(403);
	if (connection.status !== 'active')
		return page(res, '<p>The connection was not approved.</p>');
	connected.set(customerId, connection.user);
	page(res, "<p>Your Nurish'd account is connected.</p>");
});
```

```java
static void returned(Context ctx) {
    String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault("");
    if (customerId.isEmpty()) {
        signInPage(ctx);
        return;
    }
    String connectionId = ctx.queryParamAsClass("connection_id", String.class).getOrDefault("");
    JsonNode connection =
            Nurishd.call("GET", "/meals/v1/connection/%s/get/document".formatted(connectionId));
    if (!connection.path("external_id").asText().equals("shopify-" + customerId)) {
        throw new ForbiddenResponse();
    }
    if (!connection.path("status").asText().equals("active")) {
        page(ctx, "<p>The connection was not approved.</p>");
        return;
    }
    connected.put(customerId, connection.path("user").asText());
    page(ctx, "<p>Your Nurish'd account is connected.</p>");
}
```

A connection whose `external_id` is not this shopper's answers `403`. That stops a shopper from claiming someone else's connection by pasting its id.

## 7. Show meals for the shopper's address

`GET /apps/nurishd/meals` answers JSON for your storefront: the meals that can be delivered to the shopper's default Shopify address on the next delivery date. It makes the same chain of calls as [Show meals for an address](/docs/tutorials/show-meals-for-an-address), which explains each one:

1. `GET /meals/v1/zone/query/documents` with the address's city, province code and country code. The first zone found is used.
2. `GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents` for the next 30 days. The first date is the next delivery date.
3. `GET /meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{date}/get/document` for the products offered on that date.
4. `GET /meals/v1/vendor/{vendor_id}/product/query/documents` for the names and prices, keeping only the products offered.

The zone lookup takes the province and the country as two capital letters, such as `ON` and `CA`. Shopify's `countryCodeV2` is the two-letter country code. `provinceCode` is the code of the region, and the lookup needs it to be two letters too.

```python
@app.get("/proxy/meals")
def meals():
    customer_id = request.args.get("logged_in_customer_id", "")
    if not customer_id:
        return jsonify(error="not_signed_in"), 401
    address = shopify_customer(customer_id)["defaultAddress"]
    if not address:
        return jsonify(error="no_default_address"), 400
    zones = call(
        "GET",
        "/meals/v1/zone/query/documents",
        {
            "city": address["city"],
            "state": address["provinceCode"],
            "country": address["countryCodeV2"],
        },
    )["data"]
    if not zones:
        return jsonify(meals=[])
    zone = zones[0]
    vendor_id = zone["vendor"]
    zone_id = zone["zone_id"]
    today = date.today()
    dates = call(
        "GET",
        f"/meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents",
        {"from": today.isoformat(), "to": (today + timedelta(days=30)).isoformat()},
    )["valid_delivery_dates"]
    if not dates:
        return jsonify(meals=[])
    day = dates[0][:10]
    offer = call(
        "GET", f"/meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{day}/get/document"
    )
    offered = set(offer["all_unique_product_ids"])
    found = [
        {"product_id": p["product_id"], "name": p["product_name"], "price": p["product_price"]}
        for p in pages(f"/meals/v1/vendor/{vendor_id}/product/query/documents", {"size": 50})
        if p["product_id"] in offered
    ]
    return jsonify(
        vendor=vendor_id, delivery_date=day, currency=zone["zone_currency"], meals=found
    )
```

```javascript
app.get('/proxy/meals', async (req, res) => {
	const customerId = req.query.logged_in_customer_id ?? '';
	if (!customerId) return res.status(401).json({ error: 'not_signed_in' });
	const address = (await shopifyCustomer(customerId)).defaultAddress;
	if (!address) return res.status(400).json({ error: 'no_default_address' });
	const zones = (
		await call('GET', '/meals/v1/zone/query/documents', {
			params: {
				city: address.city,
				state: address.provinceCode,
				country: address.countryCodeV2,
			},
		})
	).data;
	if (zones.length === 0) return res.json({ meals: [] });
	const zone = zones[0];
	const vendorId = zone.vendor;
	const zoneId = zone.zone_id;
	const today = new Date();
	const later = new Date(today.getTime() + 30 * 24 * 3600 * 1000);
	const dates = (
		await call(
			'GET',
			`/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/query/documents`,
			{
				params: {
					from: today.toISOString().slice(0, 10),
					to: later.toISOString().slice(0, 10),
				},
			},
		)
	).valid_delivery_dates;
	if (dates.length === 0) return res.json({ meals: [] });
	const day = dates[0].slice(0, 10);
	const offer = await call(
		'GET',
		`/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/${day}/get/document`,
	);
	const offered = new Set(offer.all_unique_product_ids);
	const found = [];
	for await (const p of pages(
		`/meals/v1/vendor/${vendorId}/product/query/documents`,
		{ size: 50 },
	)) {
		if (offered.has(p.product_id)) {
			found.push({
				product_id: p.product_id,
				name: p.product_name,
				price: p.product_price,
			});
		}
	}
	res.json({
		vendor: vendorId,
		delivery_date: day,
		currency: zone.zone_currency,
		meals: found,
	});
});
```

```typescript
app.get('/proxy/meals', async (req, res) => {
	const customerId = String(req.query.logged_in_customer_id ?? '');
	if (!customerId) return res.status(401).json({ error: 'not_signed_in' });
	const address = (await shopifyCustomer(customerId)).defaultAddress;
	if (!address) return res.status(400).json({ error: 'no_default_address' });
	const zones = (
		await call<Page<Zone>>('GET', '/meals/v1/zone/query/documents', {
			params: {
				city: address.city,
				state: address.provinceCode,
				country: address.countryCodeV2,
			},
		})
	).data;
	if (zones.length === 0) return res.json({ meals: [] });
	const zone = zones[0];
	const vendorId = zone.vendor;
	const zoneId = zone.zone_id;
	const today = new Date();
	const later = new Date(today.getTime() + 30 * 24 * 3600 * 1000);
	const dates = (
		await call<{ valid_delivery_dates: string[] }>(
			'GET',
			`/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/query/documents`,
			{
				params: {
					from: today.toISOString().slice(0, 10),
					to: later.toISOString().slice(0, 10),
				},
			},
		)
	).valid_delivery_dates;
	if (dates.length === 0) return res.json({ meals: [] });
	const day = dates[0].slice(0, 10);
	const offer = await call<{ all_unique_product_ids: string[] }>(
		'GET',
		`/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/${day}/get/document`,
	);
	const offered = new Set(offer.all_unique_product_ids);
	const found = [];
	for await (const p of pages<Product>(
		`/meals/v1/vendor/${vendorId}/product/query/documents`,
		{ size: 50 },
	)) {
		if (offered.has(p.product_id)) {
			found.push({
				product_id: p.product_id,
				name: p.product_name,
				price: p.product_price,
			});
		}
	}
	res.json({
		vendor: vendorId,
		delivery_date: day,
		currency: zone.zone_currency,
		meals: found,
	});
});
```

```java
static void meals(Context ctx) throws Exception {
    String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault("");
    if (customerId.isEmpty()) {
        ctx.status(401).json(Map.of("error", "not_signed_in"));
        return;
    }
    JsonNode address = shopifyCustomer(customerId).path("defaultAddress");
    if (address.isMissingNode() || address.isNull()) {
        ctx.status(400).json(Map.of("error", "no_default_address"));
        return;
    }
    JsonNode zones = Nurishd.call("GET", "/meals/v1/zone/query/documents", Map.of(
            "city", address.path("city").asText(),
            "state", address.path("provinceCode").asText(),
            "country", address.path("countryCodeV2").asText()), null).path("data");
    if (zones.isEmpty()) {
        ctx.json(Map.of("meals", List.of()));
        return;
    }
    JsonNode zone = zones.get(0);
    String vendorId = zone.path("vendor").asText();
    String zoneId = zone.path("zone_id").asText();
    LocalDate today = LocalDate.now();
    JsonNode dates = Nurishd.call("GET",
            "/meals/v1/vendor/%s/zone/%s/delivery-date/query/documents".formatted(vendorId, zoneId),
            Map.of("from", today.toString(), "to", today.plusDays(30).toString()), null)
            .path("valid_delivery_dates");
    if (dates.isEmpty()) {
        ctx.json(Map.of("meals", List.of()));
        return;
    }
    String day = dates.get(0).asText().substring(0, 10);
    JsonNode offer = Nurishd.call("GET",
            "/meals/v1/vendor/%s/zone/%s/delivery-date/%s/get/document".formatted(vendorId, zoneId, day));
    Set<String> offered = new HashSet<>();
    offer.path("all_unique_product_ids").forEach(id -> offered.add(id.asText()));
    List<Map<String, Object>> found = new ArrayList<>();
    for (JsonNode p : Nurishd.pages(
            "/meals/v1/vendor/%s/product/query/documents".formatted(vendorId), Map.of("size", 50))) {
        if (offered.contains(p.path("product_id").asText())) {
            found.add(Map.of(
                    "product_id", p.path("product_id").asText(),
                    "name", p.path("product_name").asText(),
                    "price", p.path("product_price").asInt()));
        }
    }
    ctx.json(Map.of(
            "vendor", vendorId,
            "delivery_date", day,
            "currency", zone.path("zone_currency").asText(),
            "meals", found));
}
```

Your theme calls the route with a relative address. The request goes to your store's domain, Shopify forwards it to your server, and your key never reaches the browser.

```javascript
// In your theme's JavaScript. Shopify forwards the request to your server.
const res = await fetch('/apps/nurishd/meals');
const answer = await res.json();
for (const meal of answer.meals) {
	console.log(meal.name, meal.price);
}
```

Prices are in cents, in the zone's currency.

## 8. Place an order and take the payment

`POST /apps/nurishd/orders` places the order for the connected shopper with `POST /meals/v1/order/create/document`, the same call as in [Place a meal order](/docs/tutorials/place-a-meal-order). The storefront sends the `vendor`, the `delivery_date` and the `line_items` from the meals answer, and a `phone` in international format. The server adds the Nurish'd customer id, and the email and address from Shopify. Shopify forwards the method and the body of a `POST`, so the route reads the JSON body as usual.

```python
@app.post("/proxy/orders")
def orders():
    customer_id = request.args.get("logged_in_customer_id", "")
    user = connected.get(customer_id)
    if not user:
        return jsonify(error="not_connected"), 409
    shopper = shopify_customer(customer_id)
    address = shopper["defaultAddress"]
    if not address:
        return jsonify(error="no_default_address"), 400
    choice = request.get_json()
    order = call(
        "POST",
        "/meals/v1/order/create/document",
        body={
            "user": user,
            "order_vendor": choice["vendor"],
            "order_delivery_date": choice["delivery_date"],
            "order_shipping_address": {
                "line1": address["address1"],
                "line2": address["address2"],
                "city": address["city"],
                "state": address["provinceCode"],
                "postal_code": address["zip"],
                "country": address["countryCodeV2"],
            },
            "line_items": choice["line_items"],
            "order_contact_email": shopper["defaultEmailAddress"]["emailAddress"],
            "order_contact_phone": choice["phone"],
        },
    )
    return jsonify(
        order_id=order["order_id"],
        stripe_payment_intent=order["stripe_payment_intent"],
        stripe_publishable_key=order["stripe_publishable_key"],
    )
```

```javascript
app.post('/proxy/orders', express.json(), async (req, res) => {
	const customerId = req.query.logged_in_customer_id ?? '';
	const user = connected.get(customerId);
	if (!user) return res.status(409).json({ error: 'not_connected' });
	const shopper = await shopifyCustomer(customerId);
	const address = shopper.defaultAddress;
	if (!address) return res.status(400).json({ error: 'no_default_address' });
	const choice = req.body;
	const order = await call('POST', '/meals/v1/order/create/document', {
		body: {
			user,
			order_vendor: choice.vendor,
			order_delivery_date: choice.delivery_date,
			order_shipping_address: {
				line1: address.address1,
				line2: address.address2,
				city: address.city,
				state: address.provinceCode,
				postal_code: address.zip,
				country: address.countryCodeV2,
			},
			line_items: choice.line_items,
			order_contact_email: shopper.defaultEmailAddress.emailAddress,
			order_contact_phone: choice.phone,
		},
	});
	res.json({
		order_id: order.order_id,
		stripe_payment_intent: order.stripe_payment_intent,
		stripe_publishable_key: order.stripe_publishable_key,
	});
});
```

```typescript
app.post('/proxy/orders', express.json(), async (req, res) => {
	const customerId = String(req.query.logged_in_customer_id ?? '');
	const user = connected.get(customerId);
	if (!user) return res.status(409).json({ error: 'not_connected' });
	const shopper = await shopifyCustomer(customerId);
	const address = shopper.defaultAddress;
	if (!address) return res.status(400).json({ error: 'no_default_address' });
	const choice = req.body as OrderChoice;
	const order = await call<Order>('POST', '/meals/v1/order/create/document', {
		body: {
			user,
			order_vendor: choice.vendor,
			order_delivery_date: choice.delivery_date,
			order_shipping_address: {
				line1: address.address1,
				line2: address.address2,
				city: address.city,
				state: address.provinceCode,
				postal_code: address.zip,
				country: address.countryCodeV2,
			},
			line_items: choice.line_items,
			order_contact_email: shopper.defaultEmailAddress.emailAddress,
			order_contact_phone: choice.phone,
		},
	});
	res.json({
		order_id: order.order_id,
		stripe_payment_intent: order.stripe_payment_intent,
		stripe_publishable_key: order.stripe_publishable_key,
	});
});
```

```java
static void orders(Context ctx) throws Exception {
    String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault("");
    String user = connected.get(customerId);
    if (user == null) {
        ctx.status(409).json(Map.of("error", "not_connected"));
        return;
    }
    JsonNode shopper = shopifyCustomer(customerId);
    JsonNode address = shopper.path("defaultAddress");
    if (address.isMissingNode() || address.isNull()) {
        ctx.status(400).json(Map.of("error", "no_default_address"));
        return;
    }
    JsonNode choice = Nurishd.JSON.readTree(ctx.body());
    Map<String, Object> shippingAddress = new HashMap<>();
    shippingAddress.put("line1", address.path("address1").asText());
    shippingAddress.put("line2", address.path("address2").isNull() ? null : address.path("address2").asText());
    shippingAddress.put("city", address.path("city").asText());
    shippingAddress.put("state", address.path("provinceCode").asText());
    shippingAddress.put("postal_code", address.path("zip").asText());
    shippingAddress.put("country", address.path("countryCodeV2").asText());
    JsonNode order = Nurishd.call("POST", "/meals/v1/order/create/document", Map.of(), Map.of(
            "user", user,
            "order_vendor", choice.path("vendor").asText(),
            "order_delivery_date", choice.path("delivery_date").asText(),
            "order_shipping_address", shippingAddress,
            "line_items", choice.path("line_items"),
            "order_contact_email", shopper.path("defaultEmailAddress").path("emailAddress").asText(),
            "order_contact_phone", choice.path("phone").asText()));
    Map<String, Object> answer = new HashMap<>();
    answer.put("order_id", order.path("order_id").asText());
    answer.put("stripe_payment_intent", order.path("stripe_payment_intent"));
    answer.put("stripe_publishable_key", order.path("stripe_publishable_key"));
    ctx.json(answer);
}
```

The route answers the Stripe client secret and publishable key from the order. Your payment page takes them and confirms the payment with Stripe.js, in the browser. Serve that page through the proxy too, for example at `/apps/nurishd/pay`. [Place a meal order](/docs/tutorials/place-a-meal-order) has the page.

The order is paid when Nurish'd sends the `order.paid` webhook. Nurish'd sends webhooks straight to your server's own public address, such as `https://your-server.example.com/webhooks/nurishd`, not through the app proxy. [Receive order webhooks](/docs/tutorials/receive-order-webhooks) builds that receiver.

## 9. Run it

Start the server. It listens on port 3000. To use another port, set the `PORT` variable.

- Python: `python shop.py`
- JavaScript: `node shop.js`
- TypeScript: `node shop.ts`
- Java: `mvn -q compile exec:java -Dexec.mainClass=tutorial.Shop`

### Check the signature code without Shopify

Shopify's doc has a worked example: the secret `hush` and a query string with its signature. Your code must accept it. Stop the server, start it again with `SHOPIFY_CLIENT_SECRET` set to `hush`, and in a second terminal run:

```bash
curl "http://localhost:3000/proxy/connect?extra=1&extra=2&shop=shop-name.myshopify.com&logged_in_customer_id=&path_prefix=%2Fapps%2Fawesome_reviews&timestamp=1317327555&signature=e072b6d7e6622d85912a5214b860d3100dc1e73d9bc29f43796ac8c9ff8093cb"
```

The example has no signed-in shopper, so you see the sign-in page:

```text
<p>Sign in to the store first.</p><p><a href="{{ routes.account_login_url }}">Sign in</a></p>
```

Change one character of the query, for example `extra=2` to `extra=3`, and run it again. Now the server answers `401 Unauthorized`. Set `SHOPIFY_CLIENT_SECRET` back to your client secret and restart the server.

### Try it on your store

1. Start your tunnel to port 3000. The proxy URL you set in step 1 must be the tunnel's public address followed by `/proxy`.
2. Sign in to your store as a test customer who has a default address.
3. Open `https://shop.example.com/apps/nurishd/connect` with your store's domain. You see a page with the link **Continue to Nurish'd**.
4. Select the link and approve. In the Sandbox, the approval page accepts the code `424242`.
5. Nurish'd sends you back to `/apps/nurishd/return`, which says:

```text
Your Nurish'd account is connected.
```

6. Open `https://shop.example.com/apps/nurishd/meals`. You see the meals for your address, for example:

```text
{"vendor":"vendor-harbour-kitchen","delivery_date":"2026-04-07","currency":"CAD","meals":[{"product_id":"product-salmon-bowl","name":"Salmon Bowl","price":1495}]}
```

Your vendor, date and meals will differ.

## The whole program

Each file is complete. Next to it you need the `nurishd` client from the setup tutorial.

```python
# file: shop.py
import hashlib
import hmac
import os
import time
from datetime import date, timedelta
from urllib.parse import parse_qsl

import requests
from flask import Flask, Response, abort, jsonify, request

from nurishd import NurishdError, call, pages

SHOPIFY_SHOP = os.environ["SHOPIFY_SHOP"]
SHOPIFY_CLIENT_ID = os.environ["SHOPIFY_CLIENT_ID"]
SHOPIFY_CLIENT_SECRET = os.environ["SHOPIFY_CLIENT_SECRET"]
SHOPIFY_API_VERSION = "2026-10"
# For local tests only: send the Shopify calls to a fake server.
SHOPIFY_URL = os.environ.get("SHOPIFY_URL", f"https://{SHOPIFY_SHOP}")
RETURN_URL = os.environ["RETURN_URL"]

app = Flask(__name__)
# Shopify customer id -> Nurish'd customer id. A real app keeps this in its database.
connected = {}
token = {"value": "", "expires_at": 0}


def proxy_signature_ok(query_string):
    """Checks the signature Shopify adds to every app proxy request."""
    values = {}
    signature = ""
    for name, value in parse_qsl(query_string, keep_blank_values=True):
        if name == "signature":
            signature = value
        else:
            values.setdefault(name, []).append(value)
    message = "".join(
        sorted(f"{name}={','.join(items)}" for name, items in values.items())
    )
    expected = hmac.new(
        SHOPIFY_CLIENT_SECRET.encode(), message.encode(), hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, signature)


@app.before_request
def check_signature():
    if not proxy_signature_ok(request.query_string.decode()):
        abort(401)


def page(html):
    """A page Shopify shows inside the store's theme."""
    return Response(html, content_type="application/liquid")


def sign_in_page():
    """Asks the shopper to sign in. Shopify fills in the sign-in link."""
    return page(
        "<p>Sign in to the store first.</p>"
        '<p><a href="{{ routes.account_login_url }}">Sign in</a></p>'
    )


def shopify_token():
    """Gets an Admin API access token. Shopify's tokens last 24 hours."""
    if time.time() < token["expires_at"] - 60:
        return token["value"]
    res = requests.post(
        f"{SHOPIFY_URL}/admin/oauth/access_token",
        data={
            "grant_type": "client_credentials",
            "client_id": SHOPIFY_CLIENT_ID,
            "client_secret": SHOPIFY_CLIENT_SECRET,
        },
        timeout=30,
    )
    res.raise_for_status()
    answer = res.json()
    token["value"] = answer["access_token"]
    token["expires_at"] = time.time() + answer["expires_in"]
    return token["value"]


def shopify_customer(customer_id):
    """Reads a customer's name, email and default address from Shopify."""
    query = """
    query ($id: ID!) {
      customer(id: $id) {
        firstName
        lastName
        defaultEmailAddress { emailAddress }
        defaultAddress { address1 address2 city provinceCode countryCodeV2 zip }
      }
    }"""
    res = requests.post(
        f"{SHOPIFY_URL}/admin/api/{SHOPIFY_API_VERSION}/graphql.json",
        headers={"X-Shopify-Access-Token": shopify_token()},
        json={
            "query": query,
            "variables": {"id": f"gid://shopify/Customer/{customer_id}"},
        },
        timeout=30,
    )
    res.raise_for_status()
    answer = res.json()
    if answer.get("errors"):
        raise RuntimeError(f"Shopify said: {answer['errors']}")
    return answer["data"]["customer"]


@app.get("/proxy/connect")
def connect():
    customer_id = request.args.get("logged_in_customer_id", "")
    if not customer_id:
        return sign_in_page()
    shopper = shopify_customer(customer_id)
    try:
        created = call(
            "POST",
            "/meals/v1/customer/create/document",
            body={
                "external_id": f"shopify-{customer_id}",
                "email": shopper["defaultEmailAddress"]["emailAddress"],
                "first_name": shopper["firstName"],
                "last_name": shopper["lastName"],
                "return_url": RETURN_URL,
            },
        )
    except NurishdError as error:
        if error.code == "person_already_connected":
            return page("<p>This email is already connected under another store account.</p>")
        raise
    if created["connection"]["status"] == "active":
        connected[customer_id] = created["user"]
        return page("<p>Your Nurish'd account is already connected.</p>")
    return page(
        "<p>Nurish'd asks you to approve the connection on its own page.</p>"
        f'<p><a href="{created["connect_url"]}">Continue to Nurish\'d</a></p>'
    )


@app.get("/proxy/return")
def returned():
    customer_id = request.args.get("logged_in_customer_id", "")
    if not customer_id:
        return sign_in_page()
    connection_id = request.args.get("connection_id", "")
    connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document")
    if connection["external_id"] != f"shopify-{customer_id}":
        abort(403)
    if connection["status"] != "active":
        return page("<p>The connection was not approved.</p>")
    connected[customer_id] = connection["user"]
    return page("<p>Your Nurish'd account is connected.</p>")


@app.get("/proxy/meals")
def meals():
    customer_id = request.args.get("logged_in_customer_id", "")
    if not customer_id:
        return jsonify(error="not_signed_in"), 401
    address = shopify_customer(customer_id)["defaultAddress"]
    if not address:
        return jsonify(error="no_default_address"), 400
    zones = call(
        "GET",
        "/meals/v1/zone/query/documents",
        {
            "city": address["city"],
            "state": address["provinceCode"],
            "country": address["countryCodeV2"],
        },
    )["data"]
    if not zones:
        return jsonify(meals=[])
    zone = zones[0]
    vendor_id = zone["vendor"]
    zone_id = zone["zone_id"]
    today = date.today()
    dates = call(
        "GET",
        f"/meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/query/documents",
        {"from": today.isoformat(), "to": (today + timedelta(days=30)).isoformat()},
    )["valid_delivery_dates"]
    if not dates:
        return jsonify(meals=[])
    day = dates[0][:10]
    offer = call(
        "GET", f"/meals/v1/vendor/{vendor_id}/zone/{zone_id}/delivery-date/{day}/get/document"
    )
    offered = set(offer["all_unique_product_ids"])
    found = [
        {"product_id": p["product_id"], "name": p["product_name"], "price": p["product_price"]}
        for p in pages(f"/meals/v1/vendor/{vendor_id}/product/query/documents", {"size": 50})
        if p["product_id"] in offered
    ]
    return jsonify(
        vendor=vendor_id, delivery_date=day, currency=zone["zone_currency"], meals=found
    )


@app.post("/proxy/orders")
def orders():
    customer_id = request.args.get("logged_in_customer_id", "")
    user = connected.get(customer_id)
    if not user:
        return jsonify(error="not_connected"), 409
    shopper = shopify_customer(customer_id)
    address = shopper["defaultAddress"]
    if not address:
        return jsonify(error="no_default_address"), 400
    choice = request.get_json()
    order = call(
        "POST",
        "/meals/v1/order/create/document",
        body={
            "user": user,
            "order_vendor": choice["vendor"],
            "order_delivery_date": choice["delivery_date"],
            "order_shipping_address": {
                "line1": address["address1"],
                "line2": address["address2"],
                "city": address["city"],
                "state": address["provinceCode"],
                "postal_code": address["zip"],
                "country": address["countryCodeV2"],
            },
            "line_items": choice["line_items"],
            "order_contact_email": shopper["defaultEmailAddress"]["emailAddress"],
            "order_contact_phone": choice["phone"],
        },
    )
    return jsonify(
        order_id=order["order_id"],
        stripe_payment_intent=order["stripe_payment_intent"],
        stripe_publishable_key=order["stripe_publishable_key"],
    )


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

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

const SHOPIFY_SHOP = process.env.SHOPIFY_SHOP;
const SHOPIFY_CLIENT_ID = process.env.SHOPIFY_CLIENT_ID;
const SHOPIFY_CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET;
const SHOPIFY_API_VERSION = '2026-10';
// For local tests only: send the Shopify calls to a fake server.
const SHOPIFY_URL = process.env.SHOPIFY_URL ?? `https://${SHOPIFY_SHOP}`;
const RETURN_URL = process.env.RETURN_URL;

const app = express();
// Shopify customer id -> Nurish'd customer id. A real app keeps this in its database.
const connected = new Map();
const token = { value: '', expiresAt: 0 };

/** Checks the signature Shopify adds to every app proxy request. */
function proxySignatureOk(queryString) {
	const values = new Map();
	let signature = '';
	for (const [name, value] of new URLSearchParams(queryString)) {
		if (name === 'signature') signature = value;
		else values.set(name, [...(values.get(name) ?? []), value]);
	}
	const message = [...values]
		.map(([name, items]) => `${name}=${items.join(',')}`)
		.sort()
		.join('');
	const expected = crypto
		.createHmac('sha256', SHOPIFY_CLIENT_SECRET)
		.update(message)
		.digest('hex');
	return (
		signature.length === expected.length &&
		crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
	);
}

app.use((req, res, next) => {
	const queryString = req.originalUrl.split('?')[1] ?? '';
	if (!proxySignatureOk(queryString)) return res.sendStatus(401);
	next();
});

/** A page Shopify shows inside the store's theme. */
function page(res, html) {
	res.type('application/liquid').end(html);
}

/** Asks the shopper to sign in. Shopify fills in the sign-in link. */
function signInPage(res) {
	page(
		res,
		'<p>Sign in to the store first.</p><p><a href="{{ routes.account_login_url }}">Sign in</a></p>',
	);
}

/** Gets an Admin API access token. Shopify's tokens last 24 hours. */
async function shopifyToken() {
	if (Date.now() < token.expiresAt - 60_000) return token.value;
	const res = await fetch(`${SHOPIFY_URL}/admin/oauth/access_token`, {
		method: 'POST',
		body: new URLSearchParams({
			grant_type: 'client_credentials',
			client_id: SHOPIFY_CLIENT_ID,
			client_secret: SHOPIFY_CLIENT_SECRET,
		}),
	});
	if (!res.ok) throw new Error(`Shopify token: ${res.status}`);
	const answer = await res.json();
	token.value = answer.access_token;
	token.expiresAt = Date.now() + answer.expires_in * 1000;
	return token.value;
}

/** Reads a customer's name, email and default address from Shopify. */
async function shopifyCustomer(customerId) {
	const query = `
	query ($id: ID!) {
	  customer(id: $id) {
	    firstName
	    lastName
	    defaultEmailAddress { emailAddress }
	    defaultAddress { address1 address2 city provinceCode countryCodeV2 zip }
	  }
	}`;
	const res = await fetch(
		`${SHOPIFY_URL}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`,
		{
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'X-Shopify-Access-Token': await shopifyToken(),
			},
			body: JSON.stringify({
				query,
				variables: { id: `gid://shopify/Customer/${customerId}` },
			}),
		},
	);
	if (!res.ok) throw new Error(`Shopify customer: ${res.status}`);
	const answer = await res.json();
	if (answer.errors)
		throw new Error(`Shopify said: ${JSON.stringify(answer.errors)}`);
	return answer.data.customer;
}

app.get('/proxy/connect', async (req, res) => {
	const customerId = req.query.logged_in_customer_id ?? '';
	if (!customerId) return signInPage(res);
	const shopper = await shopifyCustomer(customerId);
	let created;
	try {
		created = await call('POST', '/meals/v1/customer/create/document', {
			body: {
				external_id: `shopify-${customerId}`,
				email: shopper.defaultEmailAddress.emailAddress,
				first_name: shopper.firstName,
				last_name: shopper.lastName,
				return_url: RETURN_URL,
			},
		});
	} catch (error) {
		if (
			error instanceof NurishdError &&
			error.code === 'person_already_connected'
		) {
			return page(
				res,
				'<p>This email is already connected under another store account.</p>',
			);
		}
		throw error;
	}
	if (created.connection.status === 'active') {
		connected.set(customerId, created.user);
		return page(res, "<p>Your Nurish'd account is already connected.</p>");
	}
	page(
		res,
		"<p>Nurish'd asks you to approve the connection on its own page.</p>" +
			`<p><a href="${created.connect_url}">Continue to Nurish'd</a></p>`,
	);
});

app.get('/proxy/return', async (req, res) => {
	const customerId = req.query.logged_in_customer_id ?? '';
	if (!customerId) return signInPage(res);
	const connectionId = req.query.connection_id ?? '';
	const connection = await call(
		'GET',
		`/meals/v1/connection/${connectionId}/get/document`,
	);
	if (connection.external_id !== `shopify-${customerId}`)
		return res.sendStatus(403);
	if (connection.status !== 'active')
		return page(res, '<p>The connection was not approved.</p>');
	connected.set(customerId, connection.user);
	page(res, "<p>Your Nurish'd account is connected.</p>");
});

app.get('/proxy/meals', async (req, res) => {
	const customerId = req.query.logged_in_customer_id ?? '';
	if (!customerId) return res.status(401).json({ error: 'not_signed_in' });
	const address = (await shopifyCustomer(customerId)).defaultAddress;
	if (!address) return res.status(400).json({ error: 'no_default_address' });
	const zones = (
		await call('GET', '/meals/v1/zone/query/documents', {
			params: {
				city: address.city,
				state: address.provinceCode,
				country: address.countryCodeV2,
			},
		})
	).data;
	if (zones.length === 0) return res.json({ meals: [] });
	const zone = zones[0];
	const vendorId = zone.vendor;
	const zoneId = zone.zone_id;
	const today = new Date();
	const later = new Date(today.getTime() + 30 * 24 * 3600 * 1000);
	const dates = (
		await call(
			'GET',
			`/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/query/documents`,
			{
				params: {
					from: today.toISOString().slice(0, 10),
					to: later.toISOString().slice(0, 10),
				},
			},
		)
	).valid_delivery_dates;
	if (dates.length === 0) return res.json({ meals: [] });
	const day = dates[0].slice(0, 10);
	const offer = await call(
		'GET',
		`/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/${day}/get/document`,
	);
	const offered = new Set(offer.all_unique_product_ids);
	const found = [];
	for await (const p of pages(
		`/meals/v1/vendor/${vendorId}/product/query/documents`,
		{ size: 50 },
	)) {
		if (offered.has(p.product_id)) {
			found.push({
				product_id: p.product_id,
				name: p.product_name,
				price: p.product_price,
			});
		}
	}
	res.json({
		vendor: vendorId,
		delivery_date: day,
		currency: zone.zone_currency,
		meals: found,
	});
});

app.post('/proxy/orders', express.json(), async (req, res) => {
	const customerId = req.query.logged_in_customer_id ?? '';
	const user = connected.get(customerId);
	if (!user) return res.status(409).json({ error: 'not_connected' });
	const shopper = await shopifyCustomer(customerId);
	const address = shopper.defaultAddress;
	if (!address) return res.status(400).json({ error: 'no_default_address' });
	const choice = req.body;
	const order = await call('POST', '/meals/v1/order/create/document', {
		body: {
			user,
			order_vendor: choice.vendor,
			order_delivery_date: choice.delivery_date,
			order_shipping_address: {
				line1: address.address1,
				line2: address.address2,
				city: address.city,
				state: address.provinceCode,
				postal_code: address.zip,
				country: address.countryCodeV2,
			},
			line_items: choice.line_items,
			order_contact_email: shopper.defaultEmailAddress.emailAddress,
			order_contact_phone: choice.phone,
		},
	});
	res.json({
		order_id: order.order_id,
		stripe_payment_intent: order.stripe_payment_intent,
		stripe_publishable_key: order.stripe_publishable_key,
	});
});

app.listen(Number(process.env.PORT ?? 3000), () => {
	console.log(`Listening on port ${process.env.PORT ?? 3000}`);
});
```

```typescript
// file: shop.ts
import crypto from 'node:crypto';
import express, { type Response } from 'express';
import { NurishdError, call, pages, type Page } from './nurishd.ts';

const SHOPIFY_SHOP = process.env.SHOPIFY_SHOP ?? '';
const SHOPIFY_CLIENT_ID = process.env.SHOPIFY_CLIENT_ID ?? '';
const SHOPIFY_CLIENT_SECRET = process.env.SHOPIFY_CLIENT_SECRET ?? '';
const SHOPIFY_API_VERSION = '2026-10';
// For local tests only: send the Shopify calls to a fake server.
const SHOPIFY_URL = process.env.SHOPIFY_URL ?? `https://${SHOPIFY_SHOP}`;
const RETURN_URL = process.env.RETURN_URL ?? '';

/** A Shopify address, with the fields the query asks for. */
interface ShopifyAddress {
	address1: string;
	address2: string | null;
	city: string;
	provinceCode: string;
	countryCodeV2: string;
	zip: string;
}

/** A Shopify customer, with the fields the query asks for. */
interface ShopifyCustomer {
	firstName: string;
	lastName: string;
	defaultEmailAddress: { emailAddress: string };
	defaultAddress: ShopifyAddress | null;
}

/** The parts of Nurish'd answers this server reads. */
interface Connection {
	user: string;
	external_id: string;
	status: string;
}

interface CreatedCustomer {
	user: string;
	connection: Connection;
	connect_url: string;
}

interface Zone {
	zone_id: string;
	vendor: string;
	zone_currency: string;
}

interface Product {
	product_id: string;
	product_name: string;
	product_price: number;
}

interface Order {
	order_id: string;
	stripe_payment_intent: object | null;
	stripe_publishable_key: string | null;
}

/** What the storefront sends to place an order. */
interface OrderChoice {
	vendor: string;
	delivery_date: string;
	line_items: { line_item_product_id: string; line_quantity: number }[];
	phone: string;
}

const app = express();
// Shopify customer id -> Nurish'd customer id. A real app keeps this in its database.
const connected = new Map<string, string>();
const token = { value: '', expiresAt: 0 };

/** Checks the signature Shopify adds to every app proxy request. */
function proxySignatureOk(queryString: string): boolean {
	const values = new Map<string, string[]>();
	let signature = '';
	for (const [name, value] of new URLSearchParams(queryString)) {
		if (name === 'signature') signature = value;
		else values.set(name, [...(values.get(name) ?? []), value]);
	}
	const message = [...values]
		.map(([name, items]) => `${name}=${items.join(',')}`)
		.sort()
		.join('');
	const expected = crypto
		.createHmac('sha256', SHOPIFY_CLIENT_SECRET)
		.update(message)
		.digest('hex');
	return (
		signature.length === expected.length &&
		crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
	);
}

app.use((req, res, next) => {
	const queryString = req.originalUrl.split('?')[1] ?? '';
	if (!proxySignatureOk(queryString)) return res.sendStatus(401);
	next();
});

/** A page Shopify shows inside the store's theme. */
function page(res: Response, html: string) {
	res.type('application/liquid').end(html);
}

/** Asks the shopper to sign in. Shopify fills in the sign-in link. */
function signInPage(res: Response) {
	page(
		res,
		'<p>Sign in to the store first.</p><p><a href="{{ routes.account_login_url }}">Sign in</a></p>',
	);
}

/** Gets an Admin API access token. Shopify's tokens last 24 hours. */
async function shopifyToken(): Promise<string> {
	if (Date.now() < token.expiresAt - 60_000) return token.value;
	const res = await fetch(`${SHOPIFY_URL}/admin/oauth/access_token`, {
		method: 'POST',
		body: new URLSearchParams({
			grant_type: 'client_credentials',
			client_id: SHOPIFY_CLIENT_ID,
			client_secret: SHOPIFY_CLIENT_SECRET,
		}),
	});
	if (!res.ok) throw new Error(`Shopify token: ${res.status}`);
	const answer = (await res.json()) as {
		access_token: string;
		expires_in: number;
	};
	token.value = answer.access_token;
	token.expiresAt = Date.now() + answer.expires_in * 1000;
	return token.value;
}

/** Reads a customer's name, email and default address from Shopify. */
async function shopifyCustomer(customerId: string): Promise<ShopifyCustomer> {
	const query = `
	query ($id: ID!) {
	  customer(id: $id) {
	    firstName
	    lastName
	    defaultEmailAddress { emailAddress }
	    defaultAddress { address1 address2 city provinceCode countryCodeV2 zip }
	  }
	}`;
	const res = await fetch(
		`${SHOPIFY_URL}/admin/api/${SHOPIFY_API_VERSION}/graphql.json`,
		{
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'X-Shopify-Access-Token': await shopifyToken(),
			},
			body: JSON.stringify({
				query,
				variables: { id: `gid://shopify/Customer/${customerId}` },
			}),
		},
	);
	if (!res.ok) throw new Error(`Shopify customer: ${res.status}`);
	const answer = (await res.json()) as {
		data: { customer: ShopifyCustomer };
		errors?: unknown;
	};
	if (answer.errors)
		throw new Error(`Shopify said: ${JSON.stringify(answer.errors)}`);
	return answer.data.customer;
}

app.get('/proxy/connect', async (req, res) => {
	const customerId = String(req.query.logged_in_customer_id ?? '');
	if (!customerId) return signInPage(res);
	const shopper = await shopifyCustomer(customerId);
	let created: CreatedCustomer;
	try {
		created = await call<CreatedCustomer>(
			'POST',
			'/meals/v1/customer/create/document',
			{
				body: {
					external_id: `shopify-${customerId}`,
					email: shopper.defaultEmailAddress.emailAddress,
					first_name: shopper.firstName,
					last_name: shopper.lastName,
					return_url: RETURN_URL,
				},
			},
		);
	} catch (error) {
		if (
			error instanceof NurishdError &&
			error.code === 'person_already_connected'
		) {
			return page(
				res,
				'<p>This email is already connected under another store account.</p>',
			);
		}
		throw error;
	}
	if (created.connection.status === 'active') {
		connected.set(customerId, created.user);
		return page(res, "<p>Your Nurish'd account is already connected.</p>");
	}
	page(
		res,
		"<p>Nurish'd asks you to approve the connection on its own page.</p>" +
			`<p><a href="${created.connect_url}">Continue to Nurish'd</a></p>`,
	);
});

app.get('/proxy/return', async (req, res) => {
	const customerId = String(req.query.logged_in_customer_id ?? '');
	if (!customerId) return signInPage(res);
	const connectionId = String(req.query.connection_id ?? '');
	const connection = await call<Connection>(
		'GET',
		`/meals/v1/connection/${connectionId}/get/document`,
	);
	if (connection.external_id !== `shopify-${customerId}`)
		return res.sendStatus(403);
	if (connection.status !== 'active')
		return page(res, '<p>The connection was not approved.</p>');
	connected.set(customerId, connection.user);
	page(res, "<p>Your Nurish'd account is connected.</p>");
});

app.get('/proxy/meals', async (req, res) => {
	const customerId = String(req.query.logged_in_customer_id ?? '');
	if (!customerId) return res.status(401).json({ error: 'not_signed_in' });
	const address = (await shopifyCustomer(customerId)).defaultAddress;
	if (!address) return res.status(400).json({ error: 'no_default_address' });
	const zones = (
		await call<Page<Zone>>('GET', '/meals/v1/zone/query/documents', {
			params: {
				city: address.city,
				state: address.provinceCode,
				country: address.countryCodeV2,
			},
		})
	).data;
	if (zones.length === 0) return res.json({ meals: [] });
	const zone = zones[0];
	const vendorId = zone.vendor;
	const zoneId = zone.zone_id;
	const today = new Date();
	const later = new Date(today.getTime() + 30 * 24 * 3600 * 1000);
	const dates = (
		await call<{ valid_delivery_dates: string[] }>(
			'GET',
			`/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/query/documents`,
			{
				params: {
					from: today.toISOString().slice(0, 10),
					to: later.toISOString().slice(0, 10),
				},
			},
		)
	).valid_delivery_dates;
	if (dates.length === 0) return res.json({ meals: [] });
	const day = dates[0].slice(0, 10);
	const offer = await call<{ all_unique_product_ids: string[] }>(
		'GET',
		`/meals/v1/vendor/${vendorId}/zone/${zoneId}/delivery-date/${day}/get/document`,
	);
	const offered = new Set(offer.all_unique_product_ids);
	const found = [];
	for await (const p of pages<Product>(
		`/meals/v1/vendor/${vendorId}/product/query/documents`,
		{ size: 50 },
	)) {
		if (offered.has(p.product_id)) {
			found.push({
				product_id: p.product_id,
				name: p.product_name,
				price: p.product_price,
			});
		}
	}
	res.json({
		vendor: vendorId,
		delivery_date: day,
		currency: zone.zone_currency,
		meals: found,
	});
});

app.post('/proxy/orders', express.json(), async (req, res) => {
	const customerId = String(req.query.logged_in_customer_id ?? '');
	const user = connected.get(customerId);
	if (!user) return res.status(409).json({ error: 'not_connected' });
	const shopper = await shopifyCustomer(customerId);
	const address = shopper.defaultAddress;
	if (!address) return res.status(400).json({ error: 'no_default_address' });
	const choice = req.body as OrderChoice;
	const order = await call<Order>('POST', '/meals/v1/order/create/document', {
		body: {
			user,
			order_vendor: choice.vendor,
			order_delivery_date: choice.delivery_date,
			order_shipping_address: {
				line1: address.address1,
				line2: address.address2,
				city: address.city,
				state: address.provinceCode,
				postal_code: address.zip,
				country: address.countryCodeV2,
			},
			line_items: choice.line_items,
			order_contact_email: shopper.defaultEmailAddress.emailAddress,
			order_contact_phone: choice.phone,
		},
	});
	res.json({
		order_id: order.order_id,
		stripe_payment_intent: order.stripe_payment_intent,
		stripe_publishable_key: order.stripe_publishable_key,
	});
});

app.listen(Number(process.env.PORT ?? 3000), () => {
	console.log(`Listening on port ${process.env.PORT ?? 3000}`);
});
```

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

import com.fasterxml.jackson.databind.JsonNode;
import io.javalin.Javalin;
import io.javalin.http.Context;
import io.javalin.http.ForbiddenResponse;
import io.javalin.http.UnauthorizedResponse;
import java.net.URI;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Shop {
    static final String SHOPIFY_SHOP = System.getenv("SHOPIFY_SHOP");
    static final String SHOPIFY_CLIENT_ID = System.getenv("SHOPIFY_CLIENT_ID");
    static final String SHOPIFY_CLIENT_SECRET = System.getenv("SHOPIFY_CLIENT_SECRET");
    static final String SHOPIFY_API_VERSION = "2026-10";
    // For local tests only: send the Shopify calls to a fake server.
    static final String SHOPIFY_URL =
            System.getenv().getOrDefault("SHOPIFY_URL", "https://" + SHOPIFY_SHOP);
    static final String RETURN_URL = System.getenv("RETURN_URL");
    static final HttpClient HTTP = HttpClient.newHttpClient();

    // Shopify customer id -> Nurish'd customer id. A real app keeps this in its database.
    static final Map<String, String> connected = new HashMap<>();
    static String token = "";
    static long tokenExpiresAt = 0;

    /** Checks the signature Shopify adds to every app proxy request. */
    static boolean proxySignatureOk(String queryString) throws Exception {
        Map<String, List<String>> values = new HashMap<>();
        String signature = "";
        for (String pair : (queryString == null ? "" : queryString).split("&")) {
            if (pair.isEmpty()) continue;
            String[] parts = pair.split("=", 2);
            String name = URLDecoder.decode(parts[0], StandardCharsets.UTF_8);
            String value = parts.length > 1 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8) : "";
            if (name.equals("signature")) signature = value;
            else values.computeIfAbsent(name, key -> new ArrayList<>()).add(value);
        }
        List<String> pieces = new ArrayList<>();
        values.forEach((name, items) -> pieces.add(name + "=" + String.join(",", items)));
        pieces.sort(null);
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(SHOPIFY_CLIENT_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        String expected = HexFormat.of()
                .formatHex(mac.doFinal(String.join("", pieces).getBytes(StandardCharsets.UTF_8)));
        return MessageDigest.isEqual(
                expected.getBytes(StandardCharsets.UTF_8), signature.getBytes(StandardCharsets.UTF_8));
    }

    /** A page Shopify shows inside the store's theme. */
    static void page(Context ctx, String html) {
        ctx.contentType("application/liquid").result(html);
    }

    /** Asks the shopper to sign in. Shopify fills in the sign-in link. */
    static void signInPage(Context ctx) {
        page(ctx, "<p>Sign in to the store first.</p>"
                + "<p><a href=\"{{ routes.account_login_url }}\">Sign in</a></p>");
    }

    /** Gets an Admin API access token. Shopify's tokens last 24 hours. */
    static synchronized String shopifyToken() throws Exception {
        if (System.currentTimeMillis() < tokenExpiresAt - 60_000) return token;
        String form = "grant_type=client_credentials"
                + "&client_id=" + URLEncoder.encode(SHOPIFY_CLIENT_ID, StandardCharsets.UTF_8)
                + "&client_secret=" + URLEncoder.encode(SHOPIFY_CLIENT_SECRET, StandardCharsets.UTF_8);
        HttpRequest request = HttpRequest.newBuilder(URI.create(SHOPIFY_URL + "/admin/oauth/access_token"))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString(form))
                .build();
        HttpResponse<String> res = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        if (res.statusCode() != 200) throw new IllegalStateException("Shopify token: " + res.statusCode());
        JsonNode answer = Nurishd.JSON.readTree(res.body());
        token = answer.path("access_token").asText();
        tokenExpiresAt = System.currentTimeMillis() + answer.path("expires_in").asLong() * 1000;
        return token;
    }

    /** Reads a customer's name, email and default address from Shopify. */
    static JsonNode shopifyCustomer(String customerId) throws Exception {
        String query = """
                query ($id: ID!) {
                  customer(id: $id) {
                    firstName
                    lastName
                    defaultEmailAddress { emailAddress }
                    defaultAddress { address1 address2 city provinceCode countryCodeV2 zip }
                  }
                }""";
        String body = Nurishd.JSON.writeValueAsString(Map.of(
                "query", query,
                "variables", Map.of("id", "gid://shopify/Customer/" + customerId)));
        HttpRequest request = HttpRequest.newBuilder(
                        URI.create(SHOPIFY_URL + "/admin/api/" + SHOPIFY_API_VERSION + "/graphql.json"))
                .header("Content-Type", "application/json")
                .header("X-Shopify-Access-Token", shopifyToken())
                .POST(HttpRequest.BodyPublishers.ofString(body))
                .build();
        HttpResponse<String> res = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
        if (res.statusCode() != 200) throw new IllegalStateException("Shopify customer: " + res.statusCode());
        JsonNode answer = Nurishd.JSON.readTree(res.body());
        if (answer.has("errors")) throw new IllegalStateException("Shopify said: " + answer.get("errors"));
        return answer.path("data").path("customer");
    }

    static void connect(Context ctx) throws Exception {
        String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault("");
        if (customerId.isEmpty()) {
            signInPage(ctx);
            return;
        }
        JsonNode shopper = shopifyCustomer(customerId);
        JsonNode created;
        try {
            created = Nurishd.call("POST", "/meals/v1/customer/create/document", Map.of(), Map.of(
                    "external_id", "shopify-" + customerId,
                    "email", shopper.path("defaultEmailAddress").path("emailAddress").asText(),
                    "first_name", shopper.path("firstName").asText(),
                    "last_name", shopper.path("lastName").asText(),
                    "return_url", RETURN_URL));
        } catch (Nurishd.NurishdException error) {
            if (!error.code.equals("person_already_connected")) throw error;
            page(ctx, "<p>This email is already connected under another store account.</p>");
            return;
        }
        if (created.path("connection").path("status").asText().equals("active")) {
            connected.put(customerId, created.path("user").asText());
            page(ctx, "<p>Your Nurish'd account is already connected.</p>");
            return;
        }
        page(ctx, "<p>Nurish'd asks you to approve the connection on its own page.</p>"
                + "<p><a href=\"" + created.path("connect_url").asText() + "\">Continue to Nurish'd</a></p>");
    }

    static void returned(Context ctx) {
        String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault("");
        if (customerId.isEmpty()) {
            signInPage(ctx);
            return;
        }
        String connectionId = ctx.queryParamAsClass("connection_id", String.class).getOrDefault("");
        JsonNode connection =
                Nurishd.call("GET", "/meals/v1/connection/%s/get/document".formatted(connectionId));
        if (!connection.path("external_id").asText().equals("shopify-" + customerId)) {
            throw new ForbiddenResponse();
        }
        if (!connection.path("status").asText().equals("active")) {
            page(ctx, "<p>The connection was not approved.</p>");
            return;
        }
        connected.put(customerId, connection.path("user").asText());
        page(ctx, "<p>Your Nurish'd account is connected.</p>");
    }

    static void meals(Context ctx) throws Exception {
        String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault("");
        if (customerId.isEmpty()) {
            ctx.status(401).json(Map.of("error", "not_signed_in"));
            return;
        }
        JsonNode address = shopifyCustomer(customerId).path("defaultAddress");
        if (address.isMissingNode() || address.isNull()) {
            ctx.status(400).json(Map.of("error", "no_default_address"));
            return;
        }
        JsonNode zones = Nurishd.call("GET", "/meals/v1/zone/query/documents", Map.of(
                "city", address.path("city").asText(),
                "state", address.path("provinceCode").asText(),
                "country", address.path("countryCodeV2").asText()), null).path("data");
        if (zones.isEmpty()) {
            ctx.json(Map.of("meals", List.of()));
            return;
        }
        JsonNode zone = zones.get(0);
        String vendorId = zone.path("vendor").asText();
        String zoneId = zone.path("zone_id").asText();
        LocalDate today = LocalDate.now();
        JsonNode dates = Nurishd.call("GET",
                "/meals/v1/vendor/%s/zone/%s/delivery-date/query/documents".formatted(vendorId, zoneId),
                Map.of("from", today.toString(), "to", today.plusDays(30).toString()), null)
                .path("valid_delivery_dates");
        if (dates.isEmpty()) {
            ctx.json(Map.of("meals", List.of()));
            return;
        }
        String day = dates.get(0).asText().substring(0, 10);
        JsonNode offer = Nurishd.call("GET",
                "/meals/v1/vendor/%s/zone/%s/delivery-date/%s/get/document".formatted(vendorId, zoneId, day));
        Set<String> offered = new HashSet<>();
        offer.path("all_unique_product_ids").forEach(id -> offered.add(id.asText()));
        List<Map<String, Object>> found = new ArrayList<>();
        for (JsonNode p : Nurishd.pages(
                "/meals/v1/vendor/%s/product/query/documents".formatted(vendorId), Map.of("size", 50))) {
            if (offered.contains(p.path("product_id").asText())) {
                found.add(Map.of(
                        "product_id", p.path("product_id").asText(),
                        "name", p.path("product_name").asText(),
                        "price", p.path("product_price").asInt()));
            }
        }
        ctx.json(Map.of(
                "vendor", vendorId,
                "delivery_date", day,
                "currency", zone.path("zone_currency").asText(),
                "meals", found));
    }

    static void orders(Context ctx) throws Exception {
        String customerId = ctx.queryParamAsClass("logged_in_customer_id", String.class).getOrDefault("");
        String user = connected.get(customerId);
        if (user == null) {
            ctx.status(409).json(Map.of("error", "not_connected"));
            return;
        }
        JsonNode shopper = shopifyCustomer(customerId);
        JsonNode address = shopper.path("defaultAddress");
        if (address.isMissingNode() || address.isNull()) {
            ctx.status(400).json(Map.of("error", "no_default_address"));
            return;
        }
        JsonNode choice = Nurishd.JSON.readTree(ctx.body());
        Map<String, Object> shippingAddress = new HashMap<>();
        shippingAddress.put("line1", address.path("address1").asText());
        shippingAddress.put("line2", address.path("address2").isNull() ? null : address.path("address2").asText());
        shippingAddress.put("city", address.path("city").asText());
        shippingAddress.put("state", address.path("provinceCode").asText());
        shippingAddress.put("postal_code", address.path("zip").asText());
        shippingAddress.put("country", address.path("countryCodeV2").asText());
        JsonNode order = Nurishd.call("POST", "/meals/v1/order/create/document", Map.of(), Map.of(
                "user", user,
                "order_vendor", choice.path("vendor").asText(),
                "order_delivery_date", choice.path("delivery_date").asText(),
                "order_shipping_address", shippingAddress,
                "line_items", choice.path("line_items"),
                "order_contact_email", shopper.path("defaultEmailAddress").path("emailAddress").asText(),
                "order_contact_phone", choice.path("phone").asText()));
        Map<String, Object> answer = new HashMap<>();
        answer.put("order_id", order.path("order_id").asText());
        answer.put("stripe_payment_intent", order.path("stripe_payment_intent"));
        answer.put("stripe_publishable_key", order.path("stripe_publishable_key"));
        ctx.json(answer);
    }

    public static void main(String[] args) {
        int port = Integer.parseInt(System.getenv().getOrDefault("PORT", "3000"));
        Javalin app = Javalin.create();
        app.before(ctx -> {
            if (!proxySignatureOk(ctx.queryString())) throw new UnauthorizedResponse();
        });
        app.get("/proxy/connect", Shop::connect);
        app.get("/proxy/return", Shop::returned);
        app.get("/proxy/meals", Shop::meals);
        app.post("/proxy/orders", Shop::orders);
        app.start(port);
    }
}
```

## Optional: keep a record in Shopify

You can save the Nurish'd customer id on the Shopify customer, so store staff see it in the Shopify admin. Shopify calls such an extra field a metafield. The [metafieldsSet](https://shopify.dev/docs/api/admin-graphql/latest/mutations/metafieldsSet) mutation writes it. A mutation is a GraphQL request that changes data. It needs the scope `write_customers`, because it changes a customer. Add that scope to a new version of your app, as in step 1, and approve it in your store.

Send this the same way `shopify_customer` sends its query, with the ids of your shopper:

```graphql
mutation {
	metafieldsSet(
		metafields: [
			{
				ownerId: "gid://shopify/Customer/1001"
				namespace: "nurishd"
				key: "customer_id"
				type: "single_line_text_field"
				value: "6f1c0d2e-0000-4000-8000-000000000101"
			}
		]
	) {
		userErrors {
			field
			message
		}
	}
}
```

An empty `userErrors` list means it was saved.

## If something goes wrong

A Nurish'd or Shopify error inside a route makes your server answer `500`. The server's log then shows the error.

| What you see                                                                                    | Why                                                                                                                                                                         | What to do                                                                                                                                                                                         |
| ----------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Every request to your server answers `401`.                                                     | The signature does not verify. The secret is wrong, your code parsed the query and built it again, or something in front of your server changed the query string.           | Use the Client secret of this app. Check the signature on the raw query string, as in step 2. Make sure nothing in front of your server rewrites the query. Test with Shopify's example in step 9. |
| `401` when you open your server's address yourself.                                             | Only Shopify adds the signature.                                                                                                                                            | Open the store address, `/apps/nurishd/...`, not your server's.                                                                                                                                    |
| The sign-in page, although you are signed in.                                                   | `logged_in_customer_id` is empty. The shopper is not signed in to this store.                                                                                               | Sign in on the store's own domain, then open the page again.                                                                                                                                       |
| `500`, and the log shows `422 validation_error` from `POST /meals/v1/customer/create/document`. | The return URL is not registered in the Nurish'd console, or it differs from `RETURN_URL`.                                                                                  | Add the exact URL under **Settings**, **Return URLs**. See [Company settings](/docs/console/company-settings).                                                                                     |
| The page says the email is already connected under another store account.                       | Create answered `409 person_already_connected`: the email is connected to your company under another `external_id`.                                                         | Keep using the first `external_id` for that person. See [Connections](/docs/concepts/connections#one-external-id-per-person).                                                                      |
| `{"error":"no_default_address"}`                                                                | The shopper has no default address in Shopify.                                                                                                                              | Ask the shopper to add an address to their store account.                                                                                                                                          |
| `{"meals":[]}`                                                                                  | No zone was found for the address, or no delivery date is open in the next 30 days. The zone lookup compares city, province and country letter for letter, and case counts. | Check the spelling of the city in the shopper's address. See [Catalog](/docs/meals/catalog).                                                                                                       |
| `500`, and the log shows `Shopify said:` with `not approved to use` a field.                    | Your app may not read that protected customer field.                                                                                                                        | Select the fields in the Dev Dashboard, as in step 1.                                                                                                                                              |
| `500`, and the log shows `Shopify token:` with an error status.                                 | Shopify refused the client credentials. The grant works only with this app's Client ID and Client secret, for a store in the same organization as the app.                  | See [Authenticate an app for stores in your organization](https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant).                                              |
| `403` from `/apps/nurishd/return`.                                                              | The connection's `external_id` is not this shopper's.                                                                                                                       | Start again from `/apps/nurishd/connect` while signed in as that shopper.                                                                                                                          |

## Next

- [Place a meal order](/docs/tutorials/place-a-meal-order): the payment page with Stripe.js.
- [Receive order webhooks](/docs/tutorials/receive-order-webhooks): learn when the order is paid.
- [Show meals for an address](/docs/tutorials/show-meals-for-an-address): zones, delivery dates and the offer of a date.
- [Connections](/docs/concepts/connections): statuses, scopes and return URLs.
