Branch8

Shopify Plus 香港分店多倉庫存預警自動化設定教學

Matt Li
December 1, 2026
13 mins read
Shopify Plus 香港分店多倉庫存預警自動化設定教學

Key Takeaways

  • 先修正 location 命名與結構,自動化邏輯才站得穩
  • Shopify Flow 做即時斷貨,排程 GraphQL 做每日跨倉比對
  • 用 Location metafield 為每間分店設差異化安全庫存門檻
  • 務必處理 GraphQL throttleStatus,節流錯誤回在 200 回應中
  • LLM 只做摘要與翻譯,補貨判斷留在可審計的程式碼裡

在 Shopify Plus 設定香港分店多倉庫存預警,核心是三層:用 Shopify Flow 做基本低庫存觸發、用 Metafields 為每間分店設差異化安全水位、再用 GraphQL Admin API 排程掃描補上 Flow 做不到的跨倉比對,最後推送到 Slack 或 WhatsApp。

為什麼香港多分店零售特別需要庫存預警自動化?

香港零售的現實是:門市面積細、後倉空間貴、同一個 SKU 可能同時放在觀塘倉、銅鑼灣門市、尖沙咀門市,加上一個供應線上訂單的第三方物流倉。當線上線下共用同一池庫存,任何一間分店的爆單都會在幾小時內把線上可售數量吃光。

Shopify Plus 本身支援最多 1,000 個 inventory location(根據 Shopify Help Center 的 Locations 說明,Plus 方案的地點上限遠高於標準方案的 10 個),技術上要把每間分店都建成獨立 location 完全沒問題。問題在於:原生後台只提供「低於某個數字」的人手查看,沒有按分店差異化、沒有按補貨前置期計算、也不會主動把訊息送到店長手機。

這套教學會把預警拆成可以獨立運作的幾層,讓你可以從最簡單的 Flow 版本開始,再按需要往上疊。對於在香港設營運中心、同時管理台灣與新加坡門市的品牌,同一套架構只需要調整 location 分組即可複用。

開始前需要準備什麼?

帳戶與權限

  1. Shopify Plus 方案(Shopify Flow 在所有付費方案都可用,但本教學第四步用到的 GraphQL 高額呼叫量,在 Plus 的速率配額下才舒服)。
  2. Store owner 或具備 write_inventory、read_locations、read_products 權限的 Custom App access token。
  3. 已安裝 Shopify Flow(Shopify App Store 免費官方 App)。
  4. 一個 Slack workspace 與 Incoming Webhook URL,或 Email 群組。

資料前置條件

  • 每間分店已在 Settings → Locations 建立獨立 location,並命名有規律,例如 HK-TST-Retail、HK-CWB-Retail、HK-KT-Warehouse、TW-TPE-Retail。命名規律是後面做分組邏輯的基礎。
  • 商品已啟用 Track quantity,否則 inventory level 不會更新。
  • 建議先在 Settings → Custom data → Location 準備 metafield 定義(下文第三步會用到)。

建立 Custom App Token

在 Settings → Apps and sales channels → Develop apps → Create an app,開啟 Admin API scopes 後安裝,取得 shpat_ 開頭的 token。測試連線:

1curl -s -X POST \
2 "https://your-store.myshopify.com/admin/api/2025-01/graphql.json" \
3 -H "X-Shopify-Access-Token: $SHOPIFY_TOKEN" \
4 -H "Content-Type: application/json" \
5 -d '{"query":"{ shop { name currencyCode } }"}'

預期輸出:

1{"data":{"shop":{"name":"Your Store","currencyCode":"HKD"}}}

若回傳 401 Invalid API key or access token,代表 App 未安裝或 token 複製時少了字元。

Ready to Transform Your Ecommerce Operations?

Branch8 specializes in ecommerce platform implementation and AI-powered automation solutions. Contact us today to discuss your ecommerce automation strategy.

第一步:盤點分店與庫存地點結構

先確認系統內實際有哪些 location、哪些有開啟 fulfillment。用以下 GraphQL query:

1query ListLocations {
2 locations(first: 50, includeInactive: false) {
3 edges {
4 node {
5 id
6 name
7 isActive
8 fulfillsOnlineOrders
9 address { city province country }
10 }
11 }
12 }
13}

預期會看到類似:

1{
2 "id": "gid://shopify/Location/71234567890",
3 "name": "HK-TST-Retail",
4 "isActive": true,
5 "fulfillsOnlineOrders": false
6}

把每個 gid://shopify/Location/... 記錄下來,之後 Flow 條件與 API script 都會引用。這裡最常見的錯誤,是有人把「門市陳列貨」與「門市後倉」混成同一個 location,結果線上可售數量包含了櫥窗上的陳列品。建議陳列品另開一個不供線上履約的 location,並把 fulfillsOnlineOrders 設為 false。

第二步:用 Shopify Flow 建立最基本的低庫存預警

Shopify Flow 是官方的 no-code 自動化工具,內建 Inventory quantity changed 觸發器,這是整套預警最便宜、最穩定的第一層。

Workflow 設定

  1. 開啟 Shopify Flow → Create workflow。
  2. Trigger 選 Inventory quantity changed。
  3. 加入 Condition:
  • Inventory level → Available is less than or equal to 5
  • AND Inventory level → Location → Name contains HK-
  1. Action 選 Send internal email 或 Send Slack message(需先在 Flow 連接 Slack connector)。

訊息模板(Flow 用 Liquid 語法):

1⚠️ 低庫存警示
2SKU: {{ inventoryLevel.item.variant.sku }}
3商品: {{ inventoryLevel.item.variant.product.title }}
4分店: {{ inventoryLevel.location.name }}
5現有可售: {{ inventoryLevel.quantities[0].quantity }}
6後台連結: https://admin.shopify.com/store/your-store/products/{{ inventoryLevel.item.variant.product.legacyResourceId }}

這一層的限制要先講清楚

Flow 是事件驅動的:只有當庫存「發生變動」時才會檢查。如果一個 SKU 已經是 2 件、之後三星期沒有任何交易,Flow 不會每天提醒你。它也無法在一次執行中讀取「其他分店」的庫存做比較。這兩個缺口,分別由第四步的排程掃描和跨倉邏輯補上。

另外,同一個 SKU 在繁忙時段可能每分鐘變動數次,Flow 會每次都觸發。建議在 Condition 加上 Available is greater than or equal to 0 以外,再於下游(Slack 側)做去重,或直接把即時通知限制在「可售 = 0」的斷貨事件,把日常低水位交給排程版本。

Ready to Transform Your Ecommerce Operations?

Branch8 specializes in ecommerce platform implementation and AI-powered automation solutions. Contact us today to discuss your ecommerce automation strategy.

第三步:用 Metafields 為每間分店設差異化安全庫存

銅鑼灣旗艦店一天賣 20 件的 SKU,安全水位設 5 顯然太低;而觀塘後倉放的是慢銷長尾,設 5 又太高。固定門檻在多分店環境必然失效。

建立 Location metafield

在 Settings → Custom data → Locations → Add definition:

  • Name: Reorder Multiplier
  • Namespace and key: ops.reorder_multiplier
  • Type: Decimal

再建立一個 Product variant 層的定義:

  • Name: Base Safety Stock
  • Namespace and key: ops.base_safety_stock
  • Type: Integer

實際門檻 = base_safety_stock × reorder_multiplier。例如一件基礎安全庫存為 4 的 T-shirt,在倍數 3.0 的旗艦店門檻是 12,在倍數 0.5 的慢銷店門檻是 2。

批次寫入 metafield

1mutation SetLocationMultiplier {
2 metafieldsSet(metafields: [
3 {
4 ownerId: "gid://shopify/Location/71234567890",
5 namespace: "ops",
6 key: "reorder_multiplier",
7 type: "number_decimal",
8 value: "3.0"
9 }
10 ]) {
11 metafields { id key value }
12 userErrors { field message }
13 }
14}

userErrors 回空陣列代表成功。若收到 Owner type does not support metafields of this definition,通常是 definition 建在了 Product 而不是 Location。

在 Flow 中引用 metafield

Flow 的 Condition 支援 metafield 變數,但無法直接做乘法運算。做法是在 Flow 內加一個 Condition 節點比對 inventoryLevel.location.metafield 的值分流(例如 multiplier ≥ 2 走高門檻分支、< 2 走低門檻分支),每個分支各自硬編一個數字。這對兩到三種店型夠用;超過就應該走第四步的 script 版本。

第四步:用排程 GraphQL 掃描做跨倉補貨建議

這一層解決 Flow 的兩個缺口:定期全量掃描,以及跨 location 比較。你可以用 Google Apps Script(零基建、最快上線)或 Cloudflare Workers Cron Triggers(更適合正式營運)。

掃描 Query

1query LowStockScan($cursor: String) {
2 productVariants(first: 100, after: $cursor, query: "inventory_total:<50") {
3 pageInfo { hasNextPage endCursor }
4 edges {
5 node {
6 sku
7 displayName
8 baseSafety: metafield(namespace: "ops", key: "base_safety_stock") { value }
9 inventoryItem {
10 inventoryLevels(first: 20) {
11 edges {
12 node {
13 location {
14 name
15 multiplier: metafield(namespace: "ops", key: "reorder_multiplier") { value }
16 }
17 quantities(names: ["available", "incoming"]) { name quantity }
18 }
19 }
20 }
21 }
22 }
23 }
24 }
25}

注意 quantities(names: [...]) 是 2023-10 之後 Admin API 的寫法;舊版的 available 單一欄位已被 inventory states 取代,遷移時最常見的錯誤就是沿用舊欄位導致 Field 'available' doesn't exist。

Cloudflare Workers 版本

1export default {
2 async scheduled(event, env, ctx) {
3 const alerts = [];
4 let cursor = null, hasNext = true;
5
6 while (hasNext) {
7 const res = await fetch(
8 `https://${env.SHOP}/admin/api/2025-01/graphql.json`,
9 {
10 method: "POST",
11 headers: {
12 "X-Shopify-Access-Token": env.SHOPIFY_TOKEN,
13 "Content-Type": "application/json",
14 },
15 body: JSON.stringify({ query: LOW_STOCK_SCAN, variables: { cursor } }),
16 }
17 );
18 const { data, errors } = await res.json();
19 if (errors) throw new Error(JSON.stringify(errors));
20
21 for (const { node: v } of data.productVariants.edges) {
22 const base = parseInt(v.baseSafety?.value ?? "4", 10);
23 const levels = v.inventoryItem.inventoryLevels.edges.map(e => e.node);
24
25 // 計算全網可調撥總量
26 const networkTotal = levels.reduce(
27 (sum, l) => sum + qty(l, "available"), 0
28 );
29
30 for (const l of levels) {
31 const mult = parseFloat(l.location.multiplier?.value ?? "1");
32 const threshold = Math.ceil(base * mult);
33 const available = qty(l, "available");
34 const incoming = qty(l, "incoming");
35
36 if (available + incoming <= threshold) {
37 alerts.push({
38 sku: v.sku,
39 title: v.displayName,
40 location: l.location.name,
41 available, incoming, threshold,
42 // 只有全網仍有貨才建議調撥,否則建議向供應商下單
43 action: networkTotal > threshold * 2 ? "TRANSFER" : "PURCHASE",
44 });
45 }
46 }
47 }
48
49 hasNext = data.productVariants.pageInfo.hasNextPage;
50 cursor = data.productVariants.pageInfo.endCursor;
51 }
52
53 await postToSlack(env.SLACK_WEBHOOK, alerts);
54 },
55};
56
57function qty(level, name) {
58 return level.quantities.find(q => q.name === name)?.quantity ?? 0;
59}

wrangler.toml 的排程設定(UTC 時間,香港時間需減 8 小時):

1name = "inventory-alerts"
2main = "src/index.js"
3compatibility_date = "2025-01-01"
4
5[triggers]
6# 每日香港時間 09:00 與 17:00
7crons = ["0 1 * * *", "0 9 * * *"]

部署:

1npx wrangler secret put SHOPIFY_TOKEN
2npx wrangler secret put SLACK_WEBHOOK
3npx wrangler deploy
4npx wrangler tail # 即時觀察執行日誌

速率限制怎麼算?

Shopify 的 Admin GraphQL API 採用 calculated query cost 機制。根據 shopify.dev 的 Rate limits 文件,標準方案的 bucket 為 1,000 points、每秒回補 50 points,而 Shopify Plus 為 2,000 points、每秒回補 100 points。上面那個 query 每頁大約消耗 300–600 points(視 inventoryLevels 數量而定),所以在 Plus 上大約每 5 秒可以安全抓一頁。

穩妥做法是讀取回應中的 extensions.cost.throttleStatus.currentlyAvailable,低於門檻時自行 sleep:

1const { currentlyAvailable, restoreRate } = json.extensions.cost.throttleStatus;
2if (currentlyAvailable < 600) {
3 await new Promise(r => setTimeout(r, (600 - currentlyAvailable) / restoreRate * 1000));
4}

若忽略這一步,你會收到 THROTTLED error 而不是 HTTP 429 — GraphQL 的節流是在 200 回應的 errors 陣列裡回報,很多人第一次寫時會整個漏掉。

Ready to Transform Your Ecommerce Operations?

Branch8 specializes in ecommerce platform implementation and AI-powered automation solutions. Contact us today to discuss your ecommerce automation strategy.

第五步:把通知推到店長真正會看的地方

香港與東南亞門市團隊的現實是:店長不會登入 Shopify Admin,但一定會看 WhatsApp 或 Slack。

Slack Block Kit 格式

1async function postToSlack(webhook, alerts) {
2 if (!alerts.length) return;
3 const byLocation = {};
4 for (const a of alerts) (byLocation[a.location] ??= []).push(a);
5
6 const blocks = [{
7 type: "header",
8 text: { type: "plain_text", text: `📦 補貨警示 ${alerts.length} 項` },
9 }];
10
11 for (const [loc, items] of Object.entries(byLocation)) {
12 blocks.push({
13 type: "section",
14 text: {
15 type: "mrkdwn",
16 text: `*${loc}*\n` + items.slice(0, 10).map(i =>
17 `• \`${i.sku}\` ${i.title} — 現有 ${i.available}(門檻 ${i.threshold})→ *${i.action}*`
18 ).join("\n"),
19 },
20 });
21 }
22
23 await fetch(webhook, {
24 method: "POST",
25 headers: { "Content-Type": "application/json" },
26 body: JSON.stringify({ blocks }),
27 });
28}

按 location 分組是關鍵:尖沙咀的店長不需要看到台北店的清單。如果用 Slack,每間分店開一個 channel,用不同 webhook URL 分發;如果用 WhatsApp Business API,則用不同的 template 收件群組。

把 LLM 加在摘要層,而不是判斷層

不少團隊現在會把警示清單丟給 LLM 產生中文摘要與行動建議。可行,但要劃清界線:門檻計算、調撥判斷這些有確定答案的邏輯留在程式碼裡;LLM 只負責把 40 行清單壓成「今天有 3 個 SKU 建議從觀塘倉調去銅鑼灣,2 個需要向供應商下單」這種一句話摘要,並翻成繁中或當地語言。判斷邏輯交給模型,你會得到一個無法審計、也無法重現的補貨決策。

第六步:加上 Webhook 做即時斷貨攔截

排程掃描每天兩次,對週末爆單不夠快。訂閱 inventory_levels/update webhook 可以把延遲壓到秒級。

1curl -X POST \
2 "https://your-store.myshopify.com/admin/api/2025-01/graphql.json" \
3 -H "X-Shopify-Access-Token: $SHOPIFY_TOKEN" \
4 -H "Content-Type: application/json" \
5 -d '{
6 "query": "mutation { webhookSubscriptionCreate(topic: INVENTORY_LEVELS_UPDATE, webhookSubscription: { callbackUrl: \"https://alerts.example.com/hooks/inventory\", format: JSON }) { userErrors { message } webhookSubscription { id } } }"
7 }'

接收端必須驗證 HMAC,否則任何人都能偽造警示:

1import crypto from "node:crypto";
2
3function verify(rawBody, hmacHeader, secret) {
4 const digest = crypto
5 .createHmac("sha256", secret)
6 .update(rawBody, "utf8")
7 .digest("base64");
8 return crypto.timingSafeEqual(
9 Buffer.from(digest),
10 Buffer.from(hmacHeader)
11 );
12}

根據 shopify.dev 的 Webhooks 文件,Shopify 要求端點在 5 秒內回應 2xx,失敗會重試 19 次、分佈在 48 小時內;連續失敗則會自動移除訂閱。所以接收端應該先回 200,再把處理丟進 queue,不要在 request 週期內做 GraphQL 查詢。

Ready to Transform Your Ecommerce Operations?

Branch8 specializes in ecommerce platform implementation and AI-powered automation solutions. Contact us today to discuss your ecommerce automation strategy.

跨時區團隊怎樣分工值班?

這是把庫存預警做成實際營運能力、而不只是多一個 Slack channel 的分別。一個常見的分工模型:

  1. 香港團隊(UTC+8) 負責門市調撥決策與供應商下單,覆蓋 09:00–19:00。
  2. 台北或吉隆坡團隊(UTC+8) 作為同時區備援,處理週末與公眾假期差異(香港與台灣的假期日曆不同,正好互補)。
  3. 澳洲團隊(UTC+10/+11) 覆蓋香港時間清晨時段,處理歐美線上訂單在亞洲夜間造成的斷貨。

對總部在倫敦或紐約的品牌來說,這個安排的價值在於:亞洲營運中心在總部下班後仍然在處理亞洲市場的補貨,而不是等到隔天早上。把預警的 action 欄位(TRANSFER / PURCHASE)當成值班手冊的分派條件,就能讓不同時區的人在沒有交接會議的情況下接手。

Branch8 曾為一家在香港與台灣同時經營門市的多品牌零售集團建置類似架構 — 門市 location 加上第三方物流倉共十餘個節點,Flow 負責即時斷貨攔截、Cloudflare Workers 排程負責每日跨倉比對,通知按店分流到各自的 Slack channel。最花時間的從來不是寫 code,而是跟營運團隊逐店談清楚安全庫存的倍數該設多少。

常見錯誤與排錯清單

警示數量爆炸(一天數百條)

門檻設得太高,或沒有過濾已停產 SKU。在 query 加上 status:active 與 published_status:published 過濾,並對 Available + Incoming 而非只對 Available 判斷 — 已下單在途的貨不應該重複警示。

Flow 完全沒觸發

依序檢查:workflow 是否處於 Active 狀態;商品是否啟用 Track quantity;Condition 中的 location name 比對是否大小寫或空格不符(HK -TST 與 HK-TST 是不同字串)。Flow 的 Activity log 會顯示每次執行與條件判斷結果,是最快的排錯入口。

GraphQL 回傳 THROTTLED

如前述,實作 throttleStatus 退避。另外避免在同一時間跑多個 script — 速率配額是整個 store 共用的,你的預警 script 跟 ERP 同步 job 搶同一個 bucket。

Webhook 收到但內容是舊數值

inventory_levels/update 的 payload 只帶 available、location_id、inventory_item_id,不帶商品資訊,而且在高頻變動時可能亂序抵達。正確做法是把 payload 當成「有東西變了」的訊號,再用 inventory_item_id 去 query 當下真實數值,不要直接信 payload 裡的數字。

數量跟實體盤點對不上

檢查是否有 location 被設為 fulfillsOnlineOrders: true 但實際不出貨,以及退貨是否有正確 restock 回原 location。香港門市常見的狀況是退貨統一送回總倉,但系統上 restock 到了銷售門市。

Ready to Transform Your Ecommerce Operations?

Branch8 specializes in ecommerce platform implementation and AI-powered automation solutions. Contact us today to discuss your ecommerce automation strategy.

什麼時候該從 Flow 升級到自建服務?

繼續用 Flow 就夠的情況

  • 分店少於 5 間,SKU 數在數千以內。
  • 安全庫存只有兩三種店型分級。
  • 只需要斷貨與低水位兩種警示。

應該自建 script 或 App 的情況

  • 需要按過去 N 天銷售速度動態計算門檻(Flow 無法讀取歷史訂單彙總)。
  • 需要跨 location 比較並自動建立 transfer。
  • 需要把警示同步寫回 ERP 或採購系統。
  • 需要多店(multi-store)跨市場比對,例如香港店缺貨時查台灣倉是否有餘量。

多店架構要特別注意:每個 Shopify store 有獨立的 access token 與速率配額,跨店比對需要在你自己的服務層做合併,Shopify 不會替你跨 store 查庫存。

可以從今天開始的三步

  1. 今天:跑第一步的 location query,確認命名規範,修正混用的門市/後倉 location。
  2. 本週:上線第二步的 Flow,只針對「可售 = 0」發通知,先讓團隊習慣這個 channel。
  3. 本月:建立 metafield 分級與排程掃描,把每日補貨清單自動化。

先做對資料結構,自動化才有意義。門檻數字可以隨時調,但 location 建錯了,後面每一層邏輯都會歪。

如果你正在把香港或亞太多分店營運搬上 Shopify Plus,又不想把庫存邏輯寫成一堆無人維護的 script,Branch8 在香港、台北、新加坡與吉隆坡都有 Shopify Plus 實作團隊,可以一起檢視你的 location 架構與自動化路線圖。歡迎與我們聯絡。

Ready to Transform Your Ecommerce Operations?

Branch8 specializes in ecommerce platform implementation and AI-powered automation solutions. Contact us today to discuss your ecommerce automation strategy.

Sources

FAQ

不行。Shopify Flow 的 Inventory quantity changed 觸發器只能存取當次變動的那一個 inventory level,無法在同一次執行中讀取其他 location 的數量。要做跨倉比對與調撥建議,必須透過 Admin GraphQL API 的排程掃描,把同一個 inventory item 的所有 inventoryLevels 一次取回再運算。

About the Author

Matt Li

Co-Founder & CEO, Branch8 & Second Talent

Matt Li is Co-Founder and CEO of Branch8, a Y Combinator-backed (S15) Adobe Solution Partner and e-commerce consultancy headquartered in Hong Kong, and Co-Founder of Second Talent, a global tech hiring platform ranked #1 in Global Hiring on G2. With 12 years of experience in e-commerce strategy, platform implementation, and digital operations, he has led delivery of Adobe Commerce Cloud projects for enterprise clients including Chow Sang Sang, HomePlus (HKBN), Maxim's, Hong Kong International Airport, Hotai/Toyota, and Evisu. Prior to founding Branch8, Matt served as Vice President of Mid-Market Enterprises at HSBC. He serves as Vice Chairman of the Hong Kong E-Commerce Business Association (HKEBA). A self-taught software engineer, Matt graduated from the University of Toronto with a Bachelor of Commerce in Finance and Economics.