Communitygithub.com

無頭 WooCommerce API 設定指南

設定並查詢 WooCommerce API,包含 WPGraphQL、WooGraphQL 和 JWT 驗證,用於無頭前端應用。適用於將 Next.js 連接到 WooCommerce 或擷取商店目錄資料。

無頭 WooCommerce API 設定指南 是什麼?

這個技能提供了一個完整的指南,用來將 WooCommerce 設定為一個無頭(headless)後端,以支援如 Next.js、Remix 或行動應用等分離式前端。它涵蓋了端到端的流程:安裝必要的 WordPress 外掛(WPGraphQL、WooGraphQL)、透過 JWT 或 OAuth 設定驗證、查詢公開與受保護的商店資料(產品、類別、購物車、客戶),並將這些功能整合到 Next.js 前端中(使用 SSG/ISR 進行快取、管理購物車令牌、實現結帳橋接)。此技能還處理重要的邊緣情況,例如產品查詢中的聯合類型、必要的購物車工作階段的持續性,以及 CORS 設定,以確保生產環境中的可靠性。它被設計為與任何支援 GraphQL 的無頭前端搭配使用,並提供具體的設定指令、安全最佳實踐以及可立即整合的範例程式碼(如 storefront-client.ts)。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/BIGboss248/nextjs-wordpress/tree/HEAD/.agents/skills/headless-woocommerce-api

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

無頭 WooCommerce API 指南

設定、查詢及保護 WooCommerce 後端 API(WPGraphQL 和 REST)以支援分離式前端應用(Next.js、Remix、行動應用)的編排指南。


先決條件與前置作業

  • 已安裝 WordPress 並啟用 WooCommerce 外掛。
  • 可存取的 GraphQL 端點(預設:https://your-store.com/graphql)。
  • 如需深入查詢與技術範例,請參閱 headless-api-reference.md。
  • 如需前端客戶端設定,請檢查 storefront-client.ts。

逐步執行檢查清單

flowchart TD
    S1["1. 安裝 WPGraphQL 與 WooGraphQL"] --> S2["2. 植入模擬 / 正式目錄資料"]
    S2 --> S3["3. 設定驗證 (JWT / OAuth)"]
    S3 --> S4["4. 使用 GraphiQL 驗證 Schema"]
    S4 --> S5["5. 在 Next.js 中連接客戶端查詢"]

階段 1:後端外掛部署

  • 安裝 WPGraphQL 核心:
    • 從 WordPress 外掛目錄安裝並啟用 wp-graphql。
    • 驗證端點是否正常運作:GET/POST /graphql。
  • 安裝 WooGraphQL 擴充功能:
    • 下載並安裝 wp-graphql-woocommerce。
    • 驗證 Product、ProductCategory、Cart、Customer 等型別是否出現在 GraphQL schema 中。
  • 植入測試資料:
    • 在 WordPress 管理後台執行 工具 → 匯入 → WooCommerce 產品 (CSV),使用 sample-data/sample_products.csv 檔案匯入。

階段 2:設定無頭驗證

  • 選項 A:JWT 驗證 (wp-graphql-jwt-authentication):
    • 上傳並啟用 wp-graphql-jwt-authentication。
    • 產生一個 64 字元的密鑰(openssl rand -base64 48 | tr -dc 'A-Za-z0-9_#%+=@!' | head -c 64 或使用 PowerShell 等效指令)。
    • 注入到容器中(docker exec -it <container> sed -i ... /var/www/html/wp-config.php),加到 .env 中(GRAPHQL_JWT_AUTH_SECRET_KEY),或直接加到 wp-config.php:
      define( 'GRAPHQL_JWT_AUTH_SECRET_KEY', 'your-strong-random-secret' );
      
  • 選項 B:無頭登入 (wp-graphql-headless-login):
    • 如果需要外部 OAuth 2.0 / 社交登入(Google、GitHub)時使用。
    • 透過篩選器或管理員設定來設定提供者。

階段 3:查詢商店資料

  • 公開目錄:使用聯合片段(... on SimpleProduct、... on VariableProduct)查詢類別和產品。
  • 客戶工作階段:在購物車變更時捕捉 woocommerce-session 標頭,並在後續請求中傳遞它。
  • 受保護的個人檔案:傳遞 Authorization: Bearer <authToken> 以查詢客戶訂單和地址更新。

階段 4:前端整合 (Next.js)

  • 使用公開 GraphQL 查詢為靜態產品頁面實作 SSG/ISR。
  • 在客戶端狀態(Zustand / LocalStorage)中維護購物車令牌,以保持 Next.js 頁面可被快取。
  • 實作原生結帳橋接:重新導向至 WordPress /checkout 以使用本地支付閘道和 e-Namad 合規性。

邊緣情況與已知 AI 陷阱

  1. 產品查詢中的聯合類型:WooCommerce 產品是多型的。切勿直接在 products { nodes { price } } 上查詢 price;你必須使用型別條件(... on SimpleProduct { price }、... on VariableProduct { price })。
  2. 缺少工作階段標頭:如果伺服器回傳的 woocommerce-session 令牌沒有被前端客戶端儲存並重新傳送,購物車項目將會在下一個請求時消失。
  3. 管理員 React 不相容:如果使用嚴格的核心 WordPress 且沒有自訂建置步驟,請避免使用具有舊版 Gutenberg 管理套件(如 wp-graphql-headless-login 設定面板)的外掛;請堅持使用常數驅動的外掛,例如 wp-graphql-jwt-authentication。
  4. CORS 標頭:確保 WordPress 允許來自前端來源的請求,方法是設定標頭或反向代理。

驗證與自我檢查

  • 對 /graphql 執行測試查詢,確認 productCategories 和 products 有回傳節點。
  • 執行 login mutation,確認產生了有效的 authToken。
  • 確認在新增項目到購物車時,伺服器有回傳 woocommerce-session 標頭。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

BIGboss248/nextjs-wordpress

Create, configure, manage, and validate Google Antigravity customizations including skills, rules, MCP servers, lifecycle hooks, plugins, and custom JSON configs. Use when adding new capabilities to Antigravity, configuring MCP servers, writing rules, creating skills, setting up hooks, or modernizing legacy workflows.

BIGboss248/nextjs-wordpress

Spawn multiple agents into a shared conversation where they debate, disagree, and converge on a solution via a shared chat.json file. Use for architecture decisions, code review debates, design trade-offs, or any problem that benefits from adversarial reasoning. Triggers on "chatroom", "agent debate", "have agents discuss", "agent chatroom", "debate this", or /agent-chatrooms. Also triggers on phrases like "have 3 agents argue about", "multi-agent discussion", or "let them debate".

BIGboss248/nextjs-wordpress

Always-active code intelligence, search, and navigation skill utilizing the codebase-memory MCP server. Enforces an index-first protocol (verifying and refreshing the knowledge graph via index_repository or index_status before searching, required because background auto_watch is disabled to eliminate editor stutter and system lag), followed by graph-first exploration (search_graph, trace_path, get_code_snippet, query_graph, get_architecture, detect_changes) instead of naive text grep or full-file reads. Always activate before searching the codebase, inspecting unknown architecture, finding symbols, or tracing callers/callees.

BIGboss248/nextjs-wordpress

>- Discover, interview, and craft comprehensive UX/UI design specifications (design-spec.md) and design tokens for web components. Triggers on "/component-design", "design component", "design section", "design UI", "wireframe component", or "create design spec".

BIGboss248/nextjs-wordpress

Orchestrate parallel browser automation using multiple Chrome DevTools MCP instances. Use when a task requires doing the same browser action across many targets simultaneously (e.g., submitting contact forms, filling applications, scraping pages that need JS rendering). Spin up 1-5 parallel Chrome agents.

BIGboss248/nextjs-wordpress

Workflow for spawning an independent subagent to conduct unbiased code reviews and inject adversarial edge-case tests ([ComponentName].edge.test.tsx).

BIGboss248/nextjs-wordpress

>- Build Next.js App Router React components with Suspense skeletons, semantic OKLCH tokens, Jest + RTL unit tests, Playwright visual/hydration checks, and Tailwind logical styling. Triggers on "/nextjs-component-dev", "create component", "new component", "build component", or "develop component".

BIGboss248/nextjs-wordpress

>- Bootstrap, configure, and verify the complete Next.js App Router development environment, developer tooling, testing suites, MCP servers, Docker containerization, and CI/CD. Triggers on "/nextjs-dev-setup", "setup nextjs dev environment", "start a nextjs project", or "containerize nextjs app".

BIGboss248/nextjs-wordpress

>- Configure production health monitoring endpoints (/api/health), Docker Compose probes, and runtime metrics in Next.js App Router applications. Use when asked to "setup health check", "add health endpoint", "docker compose healthcheck nextjs", "configure health monitor", or "/nextjs-healthcheck".

BIGboss248/nextjs-wordpress

Bootstrap, configure, and verify next-intl App Router internationalization (proxy.ts/middleware.ts, next/root-params, [locale] layout, routing). Triggers on "/nextjs-i18n-setup", "setup i18n", "install next-intl", "configure next-intl", "add internationalization", "setup locale routing", "migrate to [locale]".

BIGboss248/nextjs-wordpress

Read/write translation dictionaries (messages/[locale].json), next-intl hooks (getTranslations/useTranslations), providers (Storybook/tests/subtrees), and BiDi styling. Triggers on "/nextjs-i18n-usage", "i18n dictionary", "use translations", "read dictionary", "i18n provider", "next-intl hooks", "storybook i18n", "test i18n", "add translation keys", "localize component", "create a component", "update a component".

BIGboss248/nextjs-wordpress

>- Configure, test, and verify OpenTelemetry (OTel) observability in Next.js App Router applications. Triggers on "/nextjs-otel", "setup otel", "configure opentelemetry", "test otel", or "verify opentelemetry".

BIGboss248/nextjs-wordpress

Step-by-step workflow for designing and building Next.js App Router pages (RSC page.tsx, loading skeleton, metadata, JSON-LD schema, and dynamic static params). Triggers on "/nextjs-page-dev", "create page", "new page", "develop page", "build route", or "implement page".

BIGboss248/nextjs-wordpress

>- Orchestrate end-to-end planning for Next.js App Router projects, generating canonical specifications, design systems, and a 7-phase modular implementation roadmap in docs/plan/. Triggers on "/nextjs-plan", "plan a nextjs project", "plan nextjs app", "create nextjs project plan", "outline nextjs architecture", or "generate plan".

BIGboss248/nextjs-wordpress

Workflow and engineering standards for crafting co-located Storybook CSF3 stories ([ComponentName].stories.tsx) with interactive controls, action spies, and 4 canonical theme variants.

BIGboss248/nextjs-wordpress

>- Build Next.js e-commerce frontends backed by WooCommerce APIs, handling ISR catalogs, cart sessions, and JWT authentication. Use when building or querying Next.js stores with WooCommerce.

BIGboss248/nextjs-wordpress

Self-correcting rules engine and feedback loop that learns from user corrections, mistakes, and project-specific constraints by maintaining a persistent autofix ruleset. Scans learned rules before starting any task, resolves conflicts, and automatically appends new rules upon corrections. Triggers on user corrections ("no, do it this way", "never do X", "always use Y"), /learn, "self repair", "add rule", "update rules", or when diagnosing assumptions and bugs. CRITICAL ALWAYS-ACTIVE LIFECYCLE SKILL. Must always be kept in context, loaded at session start, and consulted before starting ANY task to read and apply active constraints from autofix.json. MUST ALWAYS be triggered immediately whenever the user provides ANY correction, preference, criticism, rejection of an approach, or adjustment ("no", "don't do X", "use Y", "remember", "prefer"), or when any mistake/bug is identified. Automatically and immediately formulates and appends the new imperative rule to the project's autofix.json ruleset file.

BIGboss248/nextjs-wordpress

Setup, automate, and execute SEO audits, CI/CD pre-push/pre-deploy checks, and ranking optimizations using the seo CLI and MCP server.

BIGboss248/nextjs-wordpress

End-to-end repository onboarding and development environment setup skill. Scans repository structure, configures project metadata (docs/project.json), sets up the codebase-memory-mcp code intelligence knowledge graph server (in workspace mcp.json and globally for AGY only), configures git hooks with Husky and Commitlint, establishes multi-stage production Docker containerization, and automates credit-optimized Release Please CI/CD with multi-arch (AMD64 & ARM64) GHCR package deployment. Triggers on "/setup-repository", "setup repository", "setup repo", "initialize repository", "new repo setup", or when preparing any repository for development and AI agent workflows.

BIGboss248/nextjs-wordpress

AI screen scaffolding, layout generation, and variant exploration workflow powered by Google Stitch (StitchMCP). Consumes a component design specification (docs/design/components/[page name]/[component name]/design-spec.md), verifies and reuses the central Stitch project in docs/project.json (or creates/persists one if absent), seeds the project's design system into Stitch, synthesizes layout prompts to generate a screen and create one variant of the given design spec file, downloads and saves Stitch JPG screenshots and HTML code files directly into docs/design/components/[page name]/[component name]/stitch/ using binary-safe PowerShell Invoke-WebRequest, outputs image prompts to the user if visual assets are needed (without calling generate_image to conserve tokens), updates design-spec.md with Stitch layout benchmarks, and audits asset download integrity with an independent subagent. Triggers on "/stitch-design", "generate stitch screen", "create stitch variant", "scaffold screen with stitch", or "stitch...

相關技能