Developers

Search the docs

Search guides and headings.

Use Nurish'd with a Shopify store

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.

View as Markdown

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. 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. 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. 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. This tutorial uses it without explaining it again.
  • You have a Shopify store and you can create apps in the 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.
  • Install the web server package for your language.
LanguageCommand
Pythonpip install flask
JavaScriptnpm install express
TypeScriptnpm install express and npm install --save-dev @types/express
JavaReplace pom.xml with the one below. It adds Javalin and a log package.

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

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

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

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

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

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

1. 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 and About app proxies.

  1. In the Dev 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. 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. For a store of another organization, Shopify has other ways to get a token, listed in About app authentication.

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.

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.

ParameterWhat it holds
shopThe store's myshopify.com domain.
path_prefixThe store path that was forwarded, such as /apps/nurishd.
timestampA time in seconds since 1 January 1970, UTC.
logged_in_customer_idThe id of the shopper who is signed in to the store. Empty when none.
signatureA 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)

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

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.

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. The query uses the 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"]

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

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 = {}

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

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

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

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

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 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 seeWhyWhat 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.
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.
{"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.
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.
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#