Developers

Search the docs

Search guides and headings.

Connect a customer from your own sign-in

Build a small web app that links a person who is signed in to your site with a Nurish'd meals customer, so your server can order for them.

View as Markdown

You will build a small web app. It sends a signed-in person to a Nurish'd page to approve, checks the answer when they come back, and remembers that they are connected.

Nurish'd Connect has no SAML or OpenID single sign-on. It has an account link instead. Your site already knows who is signed in. You create a Nurish'd customer under your own id for that person, and you send them once to a Nurish'd page to approve. They come back to your site. After that your server acts for them with the API, and they never sign in to Nurish'd on your site.

This is how the pieces map to what you know from single sign-on:

In single sign-onIn Nurish'd Connect
Your user idexternal_id, your own id for the person
The consent screenThe page at connect_url, shown once
The redirect back to your siteYour return_url
A valid sessionA connection with the status active

A customer is a person you place meal orders for. The connection is their consent.

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 order:write and order:read. They are needed to create a customer and to read the connection. Run check_key from the setup tutorial to see your scopes.
  • A return URL is the address Nurish'd sends the person back to. It must start with https:// and be registered in the console. Step 1 shows how to get one while you build.
  • 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.

1. Get a public address and register the return URL#

Nurish'd cannot send the browser back to localhost. While you build, a tunnel tool gives your computer a public HTTPS address that forwards to your server. Two common ones are ngrok and Cloudflare Tunnel. Follow their own setup guides, then start a tunnel to port 3000.

  • ngrok: ngrok http 3000
  • Cloudflare Tunnel: cloudflared tunnel --url http://localhost:3000

The tool prints an address such as https://example-name.trycloudflare.com. Your return URL is that address plus /nurishd/return. Leave the tunnel running.

Register the return URL in the console. See Company settings. A return URL that does not start with https:// or is not on the list answers 422 validation_error.

The program reads the return URL from the NURISHD_RETURN_URL environment variable. Set it in the terminal where you run the program. Use your own address.

  • macOS and Linux: export NURISHD_RETURN_URL="https://example-name.trycloudflare.com/nurishd/return"
  • Windows PowerShell: $env:NURISHD_RETURN_URL = "https://example-name.trycloudflare.com/nurishd/return"

2. Add a stand-in for your sign-in#

This tutorial is about Nurish'd, so it does not build a sign-in. The program has one fixed signed-in user. A real app takes this user from its session.

The id is your own id for the person. It becomes the external_id. The program also keeps what it learns about each user in memory. A real app uses its database.

python
app = Flask(__name__)

# The return URL you registered in the console. It starts with https://.
RETURN_URL = os.environ.get("NURISHD_RETURN_URL")
if not RETURN_URL:
    raise SystemExit("Set NURISHD_RETURN_URL first.")

# Stands in for your own sign-in. A real app reads this from its session.
SIGNED_IN_USER = {
    "id": "customer-1001",
    "email": "ada.lovelace@example.com",
    "first_name": "Ada",
    "last_name": "Lovelace",
}

# What we know about each user's link, by user id. A real app uses its database.
links = {}

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

RETURN_URL is the address you registered. The program stops with a message when NURISHD_RETURN_URL is not set. CONNECTION_ID is a check for step 5.

3. Turn a refusal into words#

Two answers of POST /meals/v1/customer/create/document are 409 refusals. Nothing is created. Each one needs a different message for the person.

CodeWhat it meansWhat to tell the person
external_id_conflictYour id already belongs to a customer with a different email.Their email changed. Ask them to contact your support.
person_already_connectedThis email is already connected to your company under a different id.They have another account with you. Ask them to use that one.

Keep using the first external_id of a person. Do not make a new one.

The helper page sends a small HTML answer. The helper explain picks the message. Any other error is printed for you, and the person sees a general message.

python
def page(text, status=200):
    return f"<p>{text}</p>", status


def explain(error):
    if error.code == "external_id_conflict":
        return page("Your email changed. Contact support so we can fix the link.", 409)
    if error.code == "person_already_connected":
        return page("This email is already linked to another account. Sign in to that account.", 409)
    print(error)
    return page("We could not start the link. Try again later.", 502)

GET /nurishd/connect runs when the person presses a "Connect Nurish'd" button on your site. It calls POST /meals/v1/customer/create/document with the person's details and your return_url.

The answer has three things you use:

  • user is the id of the customer. You use it later to place orders.
  • connection.connection_id is the id of the connection.
  • connect_url is the Nurish'd page where the person approves.

The route stores the first two for this user and redirects the browser to connect_url. Open the link as a full page. Never put it in a frame or a web view, because the page refuses to load there.

The link works once and for 24 hours. If the person waits too long, call create again with the same external_id. You get the same customer and a fresh link.

connect_url is null when the person does not need to approve now. The route then goes straight to /me.

python
@app.get("/nurishd/connect")
def connect():
    user = SIGNED_IN_USER
    try:
        customer = call(
            "POST",
            "/meals/v1/customer/create/document",
            body={
                "external_id": user["id"],
                "email": user["email"],
                "first_name": user["first_name"],
                "last_name": user["last_name"],
                "return_url": RETURN_URL,
            },
        )
    except NurishdError as error:
        return explain(error)
    connection = customer["connection"]
    links[user["id"]] = {
        "customer_id": customer["user"],
        "connection_id": connection["connection_id"],
        "connected": connection["status"] == "active",
    }
    if customer["connect_url"] is None:
        return redirect("/me")
    return redirect(customer["connect_url"])

5. Handle the return#

The person approves on the Nurish'd page. Then Nurish'd sends the browser to your return_url with connection_id and status in the query, for example /nurishd/return?connection_id=connection-0001&status=approved.

Never trust that status. Anyone can type a URL. The route does three checks instead:

  1. It checks the shape of connection_id, because the id goes into a URL path.
  2. It reads the connection with GET /meals/v1/connection/{connection_id}/get/document. The answer comes from Nurish'd, so you can trust it.
  3. It checks that the connection's external_id is the signed-in user's id. This refuses a person who pastes the id of someone else's connection.

Only then does it look at the status of the connection it read. The connection has one of four statuses:

StatusThe page says
activeThe person is connected.
pendingNot approved yet. Start again.
declinedThe person declined.
revokedThe link ended. Start again.

Only active marks the user as connected.

python
@app.get("/nurishd/return")
def come_back():
    user = SIGNED_IN_USER
    connection_id = request.args.get("connection_id", "")
    if not CONNECTION_ID.fullmatch(connection_id):
        return page("This link is not valid.", 400)
    try:
        connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document")
    except NurishdError as error:
        if error.status == 404:
            return page("We do not know this connection.", 404)
        print(error)
        return page("We could not check the connection.", 502)
    if connection["external_id"] != user["id"]:
        return page("This connection belongs to someone else.", 403)
    if connection["status"] == "active":
        links[user["id"]] = {
            "customer_id": connection["user"],
            "connection_id": connection["connection_id"],
            "connected": True,
        }
        return page("You are connected to Nurish'd.")
    if connection["status"] == "pending":
        return page("Not approved yet. Go to /nurishd/connect for a new link.")
    if connection["status"] == "declined":
        return page("You declined the link. Go to /nurishd/connect to start again.")
    return page("The link ended. Go to /nurishd/connect to start again.")

6. Show the state#

GET /me answers from what the program stored. After this, your pages and your order code check this state before they act for the person.

The last lines start the server on port 3000.

python
@app.get("/me")
def me():
    user = SIGNED_IN_USER
    if links.get(user["id"], {}).get("connected"):
        return page(f"{user['first_name']}, you are connected to Nurish'd.")
    return page(f"{user['first_name']}, you are not connected yet. Go to /nurishd/connect.")


app.run(port=3000)

7. Run it#

Start the server.

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

Open your tunnel address in a browser, for example https://example-name.trycloudflare.com/me. It says you are not connected. Then open https://example-name.trycloudflare.com/nurishd/connect. The browser goes to the Nurish'd page. Use the tunnel address and not localhost, because Nurish'd sends the browser back to the address you registered.

In the Sandbox, no email is sent. The approval page accepts the code 424242. See Environments. After you approve, the browser lands on /nurishd/return and the page says you are connected. Open /me again to see the stored state.

To see the redirect without a browser, ask your server for the route with curl on localhost.

bash
curl -i http://localhost:3000/nurishd/connect

Among the headers you see the status 302 and a Location header. It holds the connect_url of your customer.

text
HTTP/1.1 302 Found
Location: https://connect.example.com/approve/8f3k2m9q7x4z

Now call the return route with the connection id the create call answered. Then call it with an id that does not exist.

bash
curl -i "http://localhost:3000/nurishd/return?connection_id=connection-0001&status=approved"
curl -i "http://localhost:3000/nurishd/return?connection_id=missing-1&status=approved"

The same for a care patient#

The flow for a care patient is the same. You call POST /care/v1/patient/create/document and read the connection with GET /care/v1/connection/{connection_id}/get/document. A patient also needs a date of birth and an address. See Connecting a patient. To use a connected patient, follow Book a dietitian visit.

Do not wait for the browser#

The person may close the tab before they return to your site. The connection.approved event tells your server the same thing without the browser. See Receive order webhooks and Events.

The whole program#

python
# file: connect.py
import os
import re

from flask import Flask, redirect, request

from nurishd import NurishdError, call

app = Flask(__name__)

# The return URL you registered in the console. It starts with https://.
RETURN_URL = os.environ.get("NURISHD_RETURN_URL")
if not RETURN_URL:
    raise SystemExit("Set NURISHD_RETURN_URL first.")

# Stands in for your own sign-in. A real app reads this from its session.
SIGNED_IN_USER = {
    "id": "customer-1001",
    "email": "ada.lovelace@example.com",
    "first_name": "Ada",
    "last_name": "Lovelace",
}

# What we know about each user's link, by user id. A real app uses its database.
links = {}

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


def page(text, status=200):
    return f"<p>{text}</p>", status


def explain(error):
    if error.code == "external_id_conflict":
        return page("Your email changed. Contact support so we can fix the link.", 409)
    if error.code == "person_already_connected":
        return page("This email is already linked to another account. Sign in to that account.", 409)
    print(error)
    return page("We could not start the link. Try again later.", 502)


@app.get("/nurishd/connect")
def connect():
    user = SIGNED_IN_USER
    try:
        customer = call(
            "POST",
            "/meals/v1/customer/create/document",
            body={
                "external_id": user["id"],
                "email": user["email"],
                "first_name": user["first_name"],
                "last_name": user["last_name"],
                "return_url": RETURN_URL,
            },
        )
    except NurishdError as error:
        return explain(error)
    connection = customer["connection"]
    links[user["id"]] = {
        "customer_id": customer["user"],
        "connection_id": connection["connection_id"],
        "connected": connection["status"] == "active",
    }
    if customer["connect_url"] is None:
        return redirect("/me")
    return redirect(customer["connect_url"])


@app.get("/nurishd/return")
def come_back():
    user = SIGNED_IN_USER
    connection_id = request.args.get("connection_id", "")
    if not CONNECTION_ID.fullmatch(connection_id):
        return page("This link is not valid.", 400)
    try:
        connection = call("GET", f"/meals/v1/connection/{connection_id}/get/document")
    except NurishdError as error:
        if error.status == 404:
            return page("We do not know this connection.", 404)
        print(error)
        return page("We could not check the connection.", 502)
    if connection["external_id"] != user["id"]:
        return page("This connection belongs to someone else.", 403)
    if connection["status"] == "active":
        links[user["id"]] = {
            "customer_id": connection["user"],
            "connection_id": connection["connection_id"],
            "connected": True,
        }
        return page("You are connected to Nurish'd.")
    if connection["status"] == "pending":
        return page("Not approved yet. Go to /nurishd/connect for a new link.")
    if connection["status"] == "declined":
        return page("You declined the link. Go to /nurishd/connect to start again.")
    return page("The link ended. Go to /nurishd/connect to start again.")


@app.get("/me")
def me():
    user = SIGNED_IN_USER
    if links.get(user["id"], {}).get("connected"):
        return page(f"{user['first_name']}, you are connected to Nurish'd.")
    return page(f"{user['first_name']}, you are not connected yet. Go to /nurishd/connect.")


app.run(port=3000)

If something goes wrong#

What you seeWhyWhat to do
409 external_id_conflict on createThe external_id belongs to a customer with another email.Keep using the first id of the person. Do not change it.
409 person_already_connected on createThe email is connected under another external_id.Use the id you first gave to this person.
422 validation_error on createA field is wrong, or the return URL is not https or not registered.Register the return URL in the console. Use the tunnel address, not http or localhost. Check the email.
Set NURISHD_RETURN_URL first.The variable is not set in this terminal.Run the export or $env command from step 1 again in the same terminal.
403 scope_not_grantedYour key lacks order:write or order:read.Create a key with both scopes.
404 not_found when you read the connectionThe id does not exist, or it belongs to another environment.Use the connection.connection_id of the create answer in the same Sandbox.
The Nurish'd page does not open or says the link usedThe link works once and for 24 hours, or it was in a frame.Open /nurishd/connect again for a fresh link. Open it as a full page.

Next#