Build your first app
Make an app that installs on a store through OAuth, reads it, hears about new orders, puts a banner on the storefront and cleans up when it is uninstalled. With the starter app it takes about 15 minutes, and all you need is Node.
From zero to installed#
Hello World, the starter app, does the whole job in a few hundred lines with no dependencies. It installs the way any App Store app does, and it is small enough to read in one sitting. By the end you will have:
- installed it on your own store through OAuth, the way a merchant installs an App Store app;
- read the store with the Admin API and shown its name;
- received a signed
orders/createwebhook, checked its signature and ignored duplicates; - added a script to the storefront;
- handled the uninstall and the privacy webhooks, and started the install again when the store had uninstalled the app.
You need Node 20.6 or newer, a Weftstore account with a store of your own to test on, and a confirmed email address. An app that isn't published can be installed only by its developer, on a store their own account owns: staff in someone else's store can't test an app there. The store's plan has to include App Store apps.
1. Create the app in the partner dashboard#
- 1Join as a developerOpen the partner dashboard at https://store.weftgrid.com/partners. Developers use a Weftstore account like merchants do: create a store to test on (or log in), confirm your email address, come back and choose Join as a developer.
- 2Create the app
Choose Create app and fill in the form. For the starter app:
Field What to enter App name Hello World Handle Leave it. It is the address of the app's listing, /apps/<handle>.App URL http://127.0.0.1:4200Allowed redirect URLs http://127.0.0.1:4200/auth/callback. Merchants come back to one of these after they approve the app, and only to an exact match. The first one is where installs from the App Store, and Test on your store, land.Privacy webhook URL http://127.0.0.1:4200/privacy. Where privacy requests are sent. Every app needs one before it can be submitted.Where the app opens In a new tab is the simplest. The starter also works inside the admin, see Embedded apps. Access Orders: View. Storefront scripts: View and edit. URLs are https, or
httponlocalhost,127.0.0.1or*.localhostwhile you build. There are no wildcards, and you can list up to 10 redirect URLs. On a Weftstore that runs in production, the privacy webhook URL has to be reachable from the internet: use a tunnel's https address, as in Run it on your machine. - 3Copy the client ID and the client secretAfter Create app you see both. The client ID starts with
slc_and the client secret withslcs_. The secret is shown once, so copy it now. If you lose it, choose Rotate secret on the app's page: the old one stops working at once, and everything sent to your app from then on is signed with the new one.
2. Download and run the starter app#
Download storeloom-hello-world-app.zip. If you run this Weftstore from its repository, the same files are in examples/hello-world-app.
| File | What it is |
|---|---|
server.mjs | The app: install, open, webhooks, privacy requests and the storefront banner. |
verify-hmac.mjs | Checks the hmac on the install redirect and on the address that opens the app. |
webhooks.mjs | Checks the signature on a webhook. |
package.json, .env.example, README.md | The start command, the settings and a short readme. |
unzip storeloom-hello-world-app.zip
cd storeloom-hello-world-app
cp .env.example .envOpen .env and fill in the client ID and secret. This Weftstore is at https://store.weftgrid.com, so SHOP_SCHEME is https and SHOP_DOMAIN is weftgrid.store. The scheme is the one the store's address is served on, which the next section explains. The domain is the one its stores live under: the app sends a merchant only to a store on it, so that /auth can't be used to send someone to another site.
# From the app's page in the partner dashboard. The client secret is shown once, when you
# create the app or rotate its secret.
STORELOOM_CLIENT_ID=
STORELOOM_CLIENT_SECRET=
# Where this app can be reached, with no path. The redirect URL you save in the partner
# dashboard is this address plus /auth/callback.
# On your own machine: http://127.0.0.1:4200. Behind a tunnel: the tunnel's https address.
APP_URL=http://127.0.0.1:4200
# http for a Weftstore on your own machine (stores at http://<slug>.localhost:3000),
# https for a hosted one.
SHOP_SCHEME=http
# The domain your Weftstore's stores live under, with no scheme: localhost:3000 for a Weftstore on
# your own machine (its stores are <slug>.localhost:3000), weftgrid.store for the Weftgrid one (its
# stores are <slug>.weftgrid.store). /auth only sends a merchant to a store under it, and is switched
# off until it is set.
SHOP_DOMAIN=localhost:3000
# Optional: the port to listen on (4200), and where the storefront banner script is served
# from (APP_URL/hello.js).
# PORT=4200
# SCRIPT_URL=https://my-app.example.com/hello.js$ npm start
[hello] listening on http://127.0.0.1:4200 (port 4200)There is nothing to install: the app uses only what Node has. Open http://127.0.0.1:4200 and you see "Open this app from a store's admin". That is right, because nothing has installed it yet.
Run it on your machine#
Your app runs on your computer, and the store it works with runs somewhere else, or on your computer too. Three things follow from that.
Where the store is#
| A hosted Weftstore | Weftstore on your machine | |
|---|---|---|
| The platform | https://<your Weftstore> | http://localhost:3000 |
| A store (its shop address) | example-store.<your Weftstore> | example-store.localhost:3000 |
SHOP_SCHEME | https | http |
SHOP_DOMAIN | <your Weftstore> | localhost:3000 |
| Webhook addresses | Public https addresses only | Also http://127.0.0.1:4200/webhooks |
| Storefront script addresses | https | https, and http://localhost, 127.0.0.1 and *.localhost |
| App URL and redirect URLs | https, or http on localhost, 127.0.0.1 and *.localhost | The same |
The shop address has no scheme. The redirect gives your app shop=example-store.weftgrid.store, not https://example-store.weftgrid.store. Your server puts the scheme in front when it calls the store, to swap the code for a token and to call the Admin API, and the starter reads it from SHOP_SCHEME. Set it to the scheme your Weftstore serves its stores on: http on your machine, https when it is hosted. A scheme the store doesn't serve ends in a connection error at the token exchange.
/auth only sends a merchant to a store of your Weftstore. The starter's /auth?shop=… takes the store from the link, and anyone can write a link, so it checks that shop is one name (letters, digits and hyphens) followed by SHOP_DOMAIN, like example-store.localhost:3000, before it redirects. Any other address gets a 400, and so does every address while SHOP_DOMAIN isn't set: without the check a link could make your app send a visitor to another site. An install from the App Store, or from Test on your store, doesn't pass through /auth: it starts at Weftstore, and the hmac covers the shop it brings, so a store on its own domain can install that way.
Reaching *.localhost#
Most browsers open *.localhost addresses with no setup. Node asks the operating system instead, and on some machines the system doesn't know example-store.localhost. The token exchange then fails with ENOTFOUND, and the starter says which address it couldn't find. Add one line to your hosts file for each store you test on. A hosts file takes no wildcards.
127.0.0.1 example-store.localhostIf your browser can't open *.localhost either, install from the dashboard with Test on your store. Your browser then never visits a store address: only your server does.
Webhooks need an address Weftstore can reach#
A Weftstore that runs in production sends webhooks only to public https addresses. It refuses local and private ones, and plain http, and says so: "Webhooks can't be sent to local or private network addresses. Expose your app with a tunnel such as ngrok or Cloudflare Tunnel and use its https address." Storefront scripts need https there too. So when you work against a hosted Weftstore, run a tunnel to your app:
# ngrok
ngrok http 127.0.0.1:4200
# Cloudflare Tunnel
cloudflared tunnel --url http://127.0.0.1:4200Put the tunnel's https address in APP_URL in .env, restart the app, and save the same address as the app URL, the redirect URL and the privacy webhook URL in the partner dashboard. The starter builds its webhook address and its script address from APP_URL.
A Weftstore that runs as a development server on your machine accepts http://127.0.0.1 for all of it, and needs no tunnel. One that you run yourself in production mode refuses local addresses like a hosted one does. For testing only, start it with WEBHOOK_ALLOW_PRIVATE=1 and WEBHOOK_ALLOW_HTTP=1 to lift the two rules.
3. Install it on your store#
- 1Choose Test on your storeOn the app's page in the partner dashboard, choose Test on your store. The consent screen names the app and its developer, marks it Test install, says it isn't published and that you can install it on stores you own, shows the store it will go on, lists what it will be able to see and edit, and shows its pricing. Choose Install app. (Cancel goes back to the listing.)
- 2Your first redirect URL receives a code
The browser goes to the first of your redirect URLs. There is no
state, because your app didn't start this install:Your redirect URL receiveshttp://127.0.0.1:4200/auth/callback?code=Qm9vay1hLXBpY2t1cC…&shop=example-store.weftgrid.store×tamp=1761390720&hmac=4b1d0e… - 3The app checks the redirect
Anyone can type that address into a browser. The
hmacis made with your client secret, so a request without a valid one didn't come from Weftstore. The starter checks it first, then thestatewhen it sent one, then that the redirect is fresh:server.mjs// Is this really from Weftstore? Anyone can type this address. The hmac is made with your client secret. if (!validHmac(q, STORELOOM_CLIENT_SECRET)) return page(res, 400, "Not from Weftstore", "<p>The signature on this address is wrong, so nothing was installed. Start again from /auth.</p>"); const shop = q.get("shop"); if (!isShop(shop)) return page(res, 400, "Not a store address", "<p>The store address in this link isn't valid.</p>"); // Did this app start the install? Installs that began at /auth come back with the state sent there. An install that // began in the App Store or with "Test on your store" has no state: the hmac is the proof, and it is enough. const state = q.get("state"); if (state !== null) { if (pendingStates.get(state)?.shop !== shop) return page(res, 400, "Unknown install", "<p>This install wasn't started here, or it was already used. Start again from /auth.</p>"); pendingStates.delete(state); } // A redirect is only good for a few minutes. An old one is a copy someone kept. const age = Math.abs(Date.now() / 1000 - Number(q.get("timestamp"))); if (!(age <= 300)) return page(res, 400, "Link too old", "<p>This link is more than five minutes old, or has no time on it. Start the install again.</p>"); - 4It swaps the code for a token
The code works once and for 10 minutes. The request goes to the store's own address, the
shopyou were given. The starter then reads the store with the new token: the store's id is how webhooks name it later, because a webhook'sX-Storeloom-Shop-Domainis the store's main address, which can be its own domain.server.mjs// Swap the one-time code for an access token. This call goes to the store's address, not to Weftstore's main one. // A code works once and expires after 10 minutes. Asking again with the same code fails. let token; try { const exchange = await fetch(`${shopUrl(shop)}/admin/oauth/access_token`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: STORELOOM_CLIENT_ID, client_secret: STORELOOM_CLIENT_SECRET, code: q.get("code") }), }); token = await exchange.json(); if (!exchange.ok) return page(res, 502, "Install failed", `<p>Weftstore refused the code: <code>${esc(token.error ?? exchange.status)}</code>. ${esc(token.error_description ?? "")}</p>`); } catch (error) { return page(res, 502, "Install failed", `<p>${esc(networkProblem(shop, error))}</p>`); } const install = { shop, id: null, name: shop, token: token.access_token, scope: token.scope }; // Read the store: its id is how webhooks will name it. If this fails the token isn't usable, so the install isn't kept. const info = await admin(install, "GET", "/shop.json"); if (info.status !== 200) return page(res, 502, "Install failed", `<p>${esc(info.problem ?? `The store answered ${info.status} when asked for its details.`)} Start the install again.</p>`); install.id = info.body.shop.id; install.name = info.body.shop.name; installs.set(shop, install); - 5It subscribes to webhooks and adds the script
Webhook subscriptions and storefront scripts belong to an install, so the app makes them after every install. It looks before it creates: the same topic at the same address twice is refused with a 422.
server.mjs// Subscribe to the topics this app listens to, once each. Installing again (to approve more access, say) keeps // the subscriptions it already has, so look before creating: the same topic and address twice is refused. async function subscribe(install) { const existing = await admin(install, "GET", "/webhooks.json"); for (const topic of ["orders/create", "app/uninstalled"]) { if (existing.body?.webhooks?.some((w) => w.topic === topic && w.address === WEBHOOK_URL)) continue; const created = await admin(install, "POST", "/webhooks.json", { webhook: { topic, address: WEBHOOK_URL, format: "json" } }); if (created.status === 201) log("subscribed to", topic); // A 422 says what's wrong with the address, in words. A local address needs a tunnel on a hosted Weftstore. else log("could not subscribe to", topic, created.status, JSON.stringify(created.body)); } }The terminal shows what happened, and the browser shows "Installed on" and the store's name:
The terminal[hello] installed on example-store.weftgrid.store with access read_orders,write_script_tags [hello] subscribed to orders/create [hello] subscribed to app/uninstalled [hello] added the storefront script - 6Open it from the adminIn the store's admin, open Apps and then Hello World. Its address gets
shop,host,timestamp,locale(andembedded=1when it opens inside the admin) and anhmacmade the same way as on the redirect. The starter checks it and shows "Hello, <your store>" with the number of orders it has heard about. A visit without a validhmacshows nothing about the store.
An install can also start from your own app: send the merchant to /auth?shop=<store> (try http://127.0.0.1:4200/auth?shop=example-store.weftgrid.store; the store has to be on SHOP_DOMAIN) and the starter sends them to the store's authorize address with a state. The redirect back is then checked against it. Public apps and OAuth describes both ways in full.
4. Hear about orders#
Place a test order in your store, on its storefront or from a draft order in the admin. The app subscribed to orders/create during the install (the read_orders access you gave it allows that), so a signed POST arrives within a moment and the terminal shows the order:
[hello] new order #1001 in example-store.weftgrid.storeReload the app in the admin and it counts the order. The Webhooks tab of your app in the partner dashboard also has Send test, which posts a message that says it is a test and holds no store data. The starter recognizes it and only logs it.
The starter does four things with every message, in this order:
async function receive(req, res) {
const body = await readBody(req);
// Too big to be a Weftstore message. Close the connection too: the rest of the body is still on its way.
if (body === null) return send(res, 413, "too large", "text/plain", { Connection: "close" });
// 1. Check the signature first, on the raw body. A message that fails is not from Weftstore: answer 401 and do nothing.
if (!validWebhook(body, req.headers["x-storeloom-hmac-sha256"], STORELOOM_CLIENT_SECRET)) return send(res, 401, "bad signature");
// 2. Don't do the work twice. Weftstore sends a message again when it doesn't get a 2xx in time, and the same message
// keeps its X-Storeloom-Webhook-Id. Answer 200 again so it stops.
const id = String(req.headers["x-storeloom-webhook-id"]);
if (handled.has(id)) return send(res, 200, "already handled");
handled.add(id);
if (handled.size > 10_000) handled.delete(handled.values().next().value); // a real app keeps these in a database for a few days
// 3. Answer at once. Weftstore waits 5 seconds for a 2xx; anything slower counts as a failure and is sent again later.
// Do slow work after answering, from a queue. (Here the work is quick, and it doesn't throw.)
send(res, 200, "ok");
const { "x-storeloom-topic": topic, "x-storeloom-shop-id": shopId } = req.headers;
try {
await work(String(topic), String(shopId), JSON.parse(body.toString("utf8")));
} catch (error) {
log("could not handle", topic, id, error);
}
}- Check the signature, with the client secret.
X-Storeloom-Hmac-Sha256is the base64 HMAC-SHA256 of the raw body. Check it before parsing anything, and answer 401 when it doesn't match. Verifying signatures has the same check in four languages. - Ignore duplicates. A message that wasn't answered in time is sent again with the same
X-Storeloom-Webhook-Id. Answer 200 again and do nothing. - Answer at once. Any 2xx within 5 seconds counts as delivered. Anything else is tried again, 9 attempts over about two days. Responses and retries has the schedule.
- Then do the work. Slow work belongs on a queue, after the answer.
5. Handle uninstall and privacy messages#
A merchant can uninstall your app whenever they like. Its token stops working, its webhook subscriptions and storefront scripts are removed, and Weftstore tells your app:
app/uninstalledgoes to the address you subscribed with. If your server doesn't answer 2xx it is tried again on the usual schedule.shop/redactgoes to your privacy webhook URL 48 hours later. It means: erase everything you kept about the store. If the store installs your app again before then, it is cancelled.customers/data_requestandcustomers/redactgo to your privacy webhook URL when a merchant asks for the data apps hold about a customer, or erases a customer. Send what you hold to the store's contact, or erase it. A store tells only an app that can read customer data: one with access to customers, orders, draft orders, returns, store credit, gift cards or reviews (view or edit), because the message names the customer. The starter hasread_orders, so it is told.
Only app/uninstalled needs a subscription. The other three go to the privacy webhook URL, signed the same way, so the starter answers them at /privacy with the function above. It logs the ids, never the person:
case "app/uninstalled":
// The uninstall message. It is retried for about two days when your server is down, so it can arrive after the store
// has installed the app again. Ask the API before forgetting: only a 401 means the install is really over.
if (install && (await admin(install, "GET", "/shop.json")).status === 401) {
installs.delete(install.shop);
log("uninstalled from", install.shop);
}
break;
case "shop/redact":
// Sent to your privacy webhook URL 48 hours after an uninstall, unless the store installed the app again first:
// erase everything you kept about the store. This app keeps its counters in memory.
ordersSeen.delete(shopId);
log("erase everything about shop", payload.shop_domain);
break;
case "customers/data_request":
// A merchant asked for the data you hold about one customer. Send it to the store's contact (the shop's email
// from /shop.json), within the time the law gives the merchant. Log the ids, not the person.
log("customer data request", payload.data_request?.id, "for customer", payload.customer?.id, "orders", payload.orders_requested);
break;
case "customers/redact":
// A merchant erased a customer: erase what you hold about them and the orders listed. This app keeps nothing.
log("customer erased", payload.customer?.id, "orders", payload.orders_to_redact);
break;The uninstall message is tried again for about two days, so it can arrive after the store has installed your app again. The starter asks the API before it forgets the store. Privacy webhooks has the payloads and what your app owes the merchant.
A 401 from the Admin API is the signal that always arrives, even when a webhook was missed. It means the store uninstalled the app, or approved it again, which gives your app a new code and replaces the token: the old token answers 401 from then on, and the merchant is asked again. Forget the install and start it over. Inside the admin's frame the approval page can't open, so the starter offers a link that opens it in a new tab.
const info = await admin(install, "GET", "/shop.json");
if (info.status === 0) return page(res, 502, "Can't reach the store", `<p>${esc(info.problem)}</p>`, headers);
// 401 means this token no longer works: the store uninstalled the app (or installed it again, which replaces the token).
// It is the one signal that always arrives, even when a webhook was missed. Forget the install and start over.
if (info.status === 401) {
installs.delete(shop);
log("the token for", shop, "was refused: the app was uninstalled, or installed again and given a new token");
return needInstall(res, shop, framed, headers);
}Reinstalling gives a new token. The old one stays dead, so the app can't use a copy it kept.
When something goes wrong#
| What you see | What it means |
|---|---|
| "This app's install link isn't right" on the store's authorize page: "The redirect_uri isn't one of … allowed redirect URLs" | The redirect URL your app sent isn't one saved for the app. It has to match character for character: scheme, host, port and path. Compare APP_URL plus /auth/callback with the redirect URLs in the dashboard. |
| "Couldn't reach … (ENOTFOUND)" | Node can't find the store's address. Add the hosts line from Reaching *.localhost. |
"Weftstore refused the code", invalid_grant | The code was used already, is older than 10 minutes, or belongs to another store or app. Start the install again for a new one. |
invalid_client | The client ID or the client secret is wrong. Copy them again from the app's page, or rotate the secret. |
| "… asks for write_script_tags, which isn't in the access it declared" on the store's authorize page | The app asks for access you didn't choose for it. In the partner dashboard, open the app's App setup tab, set Orders to View and Storefront scripts to View and edit, save, and start the install again. |
"Set SHOP_DOMAIN" at /auth | The app doesn't know the domain your stores live under, so /auth is switched off. Set SHOP_DOMAIN in .env (step 2 has the value for this Weftstore) and restart the app. |
"Which store?" at /auth | The shop in the link isn't one name followed by SHOP_DOMAIN. Use example-store.localhost:3000, not localhost:3000 or an address on another domain. |
| "could not subscribe to orders/create" with a 422 about local or private addresses | This Weftstore won't send webhooks to your machine. Use a tunnel, as in Webhooks need an address Weftstore can reach. |
"could not add the storefront script" with must be an https URL | Storefront scripts need https, except on a Weftstore running as a development server, which also takes localhost. Set SCRIPT_URL, or APP_URL to the tunnel's address. |
| "You're staff in … so you can't test your own app there" on the consent screen | An unpublished app installs only on stores its developer owns. Test on a store your account owns, or publish the app first. |
6. Submit it for review#
When the app works, put it on a public https address and save that address as the app URL, the redirect URLs and the privacy webhook URL: merchants and reviewers can't reach 127.0.0.1. The app's page in the partner dashboard keeps a checklist, and Submit for review works when every item is done:
- Add an app icon
- Add at least one screenshot
- Write a tagline
- Describe what the app does
- Give a support email
- Link to your privacy policy
- Add at least one redirect URL
- Add a privacy webhook URL
- Choose the access the app needs
A reviewer approves the app or turns it down with a note, and you get an email either way. Before you submit, install it on a fresh store and go through the whole life once: install, open, place an order, uninstall, install again.
7. After you publish#
Once an app is published, what merchants trusted it with can't change behind their backs. A save that asks for more access, or changes the app URL, the redirect URLs or the privacy webhook URL, is held and reviewed before it goes live. Until a reviewer approves it, installs and OAuth keep using the values that are live. You can withdraw a waiting change, and a rejection comes with a note.
Everything else applies at once: removing access, the name, where the app opens, listing text and images, and support details. Each app keeps an activity log of reviews, changes and rotated secrets, never the secrets themselves.
Stores that installed the app keep the access they approved. When the app's live access goes beyond what a store approved, the store's admin says the app wants more access and which, on the app's page and in the apps list. Nothing is granted automatically, and stores aren't emailed: the app asks through the same approval screen it was installed with, and the merchant sees what is new.
The merchant approves it when the app asks. So an app that adds access should compare the scope of its token (the token response lists what the store approved) with what it needs every time it opens, and start the install again when the token falls short. The starter does this when it opens: it keeps the scope from the token exchange and offers the approval again, in a new tab inside the admin.