编程开发

WooCommerce接口集成

为 ERP、仓储或外部订单面板对接商品、订单和库存数据,使用店铺 API 凭据完成读写与批量同步。

# WooCommerce REST API

## 概述

WooCommerce 提供带版本控制的 REST API(`/wp-json/wc/v3/`),通过 HTTPS 提供对产品、订单、客户、优惠券和商店设置的访问。在非 HTTPS 环境中使用 OAuth 1.0a,在 HTTPS 环境中使用 Basic Auth(消费者密钥/密钥)。官方 `@woocommerce/woocommerce-rest-api` Node.js 客户端可自动处理身份验证,并支持完整的 CRUD 操作。

## 何时使用此 Skill

- 构建从 WooCommerce 读取产品和分类的无头店面时
- 将 WooCommerce 与 ERP、CRM 或订单履行系统集成时
- 在 WordPress Admin 之外创建订单管理仪表板时
- 在 WooCommerce 与仓库或 POS 系统之间同步库存时
- 自动从外部目录批量导入产品或更新价格时
- 构建需要访问 WooCommerce 商店数据的移动应用时

## 核心指令

1. **生成 API 凭据**

   在 WordPress Admin → WooCommerce → Settings → Advanced → REST API → Add Key 中:
   - Description:`My Integration`
   - User:(管理员用户)
   - Permissions:Read/Write

   这会生成一个 Consumer Key(`ck_xxx`)和一个 Consumer Secret(`cs_xxx`)。将它们存储在环境变量中,绝不要放在源代码里。

   ```bash
   WOOCOMMERCE_URL=https://mystore.com
   WOOCOMMERCE_CONSUMER_KEY=ck_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
   WOOCOMMERCE_CONSUMER_SECRET=cs_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
   ```

2. **设置 Node.js 客户端**

   ```bash
   npm install @woocommerce/woocommerce-rest-api
   ```

   ```typescript
   // lib/woocommerce.ts
   import WooCommerceRestApi from "@woocommerce/woocommerce-rest-api";

   export const woo = new WooCommerceRestApi({
     url: process.env.WOOCOMMERCE_URL!,
     consumerKey: process.env.WOOCOMMERCE_CONSUMER_KEY!,
     consumerSecret: process.env.WOOCOMMERCE_CONSUMER_SECRET!,
     version: "wc/v3",
     axiosConfig: {
       timeout: 15000,
     },
   });
   ```

3. **使用筛选和分页查询产品**

   ```typescript
   // lib/products.ts
   interface ProductQuery {
     page?: number;
     perPage?: number;
     category?: number;
     status?: "publish" | "draft" | "private";
     stockStatus?: "instock" | "outofstock" | "onbackorder";
     orderby?: "date" | "popularity" | "price" | "title";
   }

   export async function getProducts(params: ProductQuery = {}) {
     const response = await woo.get("products", {
       page: params.page ?? 1,
       per_page: params.perPage ?? 20,
       status: params.status ?? "publish",
       stock_status: params.stockStatus,
       orderby: params.orderby ?? "date",
       category: params.category,
     });

     return {
       products: response.data,
       totalPages: parseInt(response.headers["x-wp-totalpages"]),
       totalProducts: parseInt(response.headers["x-wp-total"]),
     };
   }

   export async function getProductById(id: number) {
     const response = await woo.get(`products/${id}`);
     return response.data;
   }

   // Get product variations
   export async function getProductVariations(productId: number) {
     const response = await woo.get(`products/${productId}/variations`, {
       per_page: 100,
     });
     return response.data;
   }
   ```

4. **创建和管理订单**

   ```typescript
   // lib/orders.ts
   interface OrderLineItem {
     product_id: number;
     variation_id?: number;
     quantity: number;
   }

   interface CreateOrderParams {
     billing: {
       first_name: string;
       last_name: string;
       email: string;
       address_1: string;
       city: string;
       postcode: string;
       country: string;
     };
     line_items: OrderLineItem[];
     payment_method?: string;
   }

   export async function createOrder(params: CreateOrderParams) {
     const response = await woo.post("orders", {
       ...params,
       status: "pending",
       payment_method: params.payment_method ?? "stripe",
       payment_method_title: "Credit Card",
       set_paid: false,
     });
     return response.data;
   }

   export async function updateOrderStatus(
     orderId: number,
     status: "pending" | "processing" | "on-hold" | "completed" | "cancelled" | "refunded",
     note?: string
   ) {
     const updateData: any = { status };
     if (note) {
       // Add an order note
       await woo.post(`orders/${orderId}/notes`, { note });
     }
     const response = await woo.put(`orders/${orderId}`, updateData);
     return response.data;
   }

   export async function getOrders(params: {
     status?: string;
     after?: string; // ISO 8601 date
     page?: number;
   } = {}) {
     const response = await woo.get("orders", {
       status: params.status ?? "processing",
       after: params.after,
       per_page: 50,
       page: params.page ?? 1,
     });
     return {
       orders: response.data,
       totalPages: parseInt(response.headers["x-wp-totalpages"]),
     };
   }
   ```

5. **管理库存和产品更新**

   ```typescript
   // Update stock quantity for a product or variation
   export async function updateStock(productId: number, quantity: number, variationId?: number) {
     const endpoint = variationId
       ? `products/${productId}/variations/${variationId}`
       : `products/${productId}`;

     const response = await woo.put(endpoint, {
       stock_quantity: quantity,
       manage_stock: true,
     });
     return response.data;
   }

   // Batch update products (up to 100 per request)
   export async function batchUpdateProducts(
     updates: Array<{ id: number; regular_price?: string; stock_quantity?: number; status?: string }>
   ) {
     const response = await woo.post("products/batch", { update: updates });
     return response.data;
   }
   ```

## 示例

### 从外部目录完整同步产品

```typescript
import pLimit from "p-limit";

export async function syncProductsFromCatalog(
  externalProducts: Array<{ sku: string; price: number; stock: number }>
) {
  const limit = pLimit(5); // Max 5 concurrent API calls

  const results = await Promise.allSettled(
    externalProducts.map((ext) =>
      limit(async () => {
        // Look up WooCommerce product by SKU
        const searchResponse = await woo.get("products", { sku: ext.sku });
        const existing = searchResponse.data[0];

        if (existing) {
          // Update existing product
          return woo.put(`products/${existing.id}`, {
            regular_price: ext.price.toFixed(2),
            stock_quantity: ext.stock,
            manage_stock: true,
          });
        } else {
          console.warn(`SKU not found in WooCommerce: ${ext.sku}`);
          return null;
        }
      })
    )
  );

  const failed = results.filter((r) => r.status === "rejected");
  if (failed.length > 0) {
    console.error(`${failed.length} products failed to sync`);
  }

  return results;
}
```

### 客户管理

```typescript
// Create or update customer
export async function upsertCustomer(email: string, data: Record<string, any>) {
  const searchResponse = await woo.get("customers", { email });
  const existing = searchResponse.data[0];

  if (existing) {
    const response = await woo.put(`customers/${existing.id}`, data);
    return response.data;
  } else {
    const response = await woo.post("customers", { email, ...data });
    return response.data;
  }
}

// Get customer order history
export async function getCustomerOrders(customerId: number) {
  const response = await woo.get("orders", {
    customer: customerId,
    per_page: 50,
    orderby: "date",
    order: "desc",
  });
  return response.data;
}
```

## 最佳实践

- **始终使用 HTTPS** — OAuth 1.0a 可在 HTTP 上运行,但每次请求都会传输凭据;对于服务器之间的调用,HTTPS + Basic Auth 更简单、更安全
- **遵守速率限制** — WordPress 默认不强制限制 API 请求速率,但大量请求可能耗尽 PHP-FPM 或 MySQL 资源;批量操作时使用 `p-limit` 或队列
- **使用批量端点进行批量更新** — `/products/batch` 一次请求最多接受 100 个创建/更新/删除操作,无需发送 100 个单独请求
- **使用 `_fields` 参数筛选字段** — 对于大型产品列表,`?_fields=id,name,price,stock_quantity` 可显著减少响应数据量
- **处理 WooCommerce 专属错误代码** — API 在错误响应体中返回 `rest_invalid_param`、`woocommerce_rest_cannot_create` 等代码;解析 `response.data.code` 以针对具体错误进行处理
- **使用 `after` 和 `before` 日期筛选条件**进行增量同步 — 使用 ISO 8601 时间戳筛选上次同步后修改过的订单/产品,避免重新扫描整个目录
- **存储 API URL 时不要在末尾加斜杠** — WooCommerce 客户端会处理 URL 的构建;基础 URL 末尾的斜杠会导致端点中出现双斜杠

## 常见问题

| 问题 | 解决方案 |
|---------|----------|
| 密钥正确但仍出现 `401 Unauthorized` | 确认站点使用 HTTPS;在 HTTP 上,客户端必须使用 OAuth 1.0a,而非 Basic Auth — 在客户端配置中设置 `isHttps: false` |
| 产品端点返回空数组 | 检查分配给 API 密钥的用户是否具有正确的权限;需要默认的 `woocommerce_manage_products` 权限 |
| 创建订单时因产品 ID 错误而失败 | 可变产品需要在 `line_items` 中提供 `variation_id`;对可变产品仅传入 `product_id` 会导致 `invalid_variation` 错误 |
| 缺少分页响应头 | `x-wp-total` 和 `x-wp-totalpages` 响应头仅存在于列表端点,不存在于单资源端点 |
| 批量操作部分失败 | 批量响应包含每个条目各自的错误;遍历 `response.data.update` 数组并检查每个条目是否有 `error` 属性 |
| 产品列表响应缓慢 | 添加 `?_fields=id,name,price` 以减少数据量;也可考虑在 WordPress 服务器上启用持久化对象缓存(Redis)|

## 相关 Skills

- @woocommerce-plugin-development
- @woocommerce-subscriptions
- @woocommerce-performance
- @headless-commerce-architecture
- @rest-api-design

同类提示词

编程开发

通信站点故障英文看板

把给出的站点事件整理成英文仪表盘,按新接入、移动与测试站点、共享故障单和停电等分类展示时长与反馈。

为以下数据创建一个英文仪表板 截至 28/7/2026 的事件汇总 新接入: 站点名称 持续时间 反馈 KAI1107 41:49:07 新部署 KAI1120 445:00:38 新站点存在电力问题(正在与业主核算电量) KEF1053 1936:01:11 新站点 MED1183 1513:29:43 新站点 MED1201 1561:31:41 新站点 MED1218 111:13:32 新接入 SFX1385 1817:05:05 新部署 SOS1251 790:47:15 新站点存在电力问题 TAT1039 3433:25:24 新站点
编程开发· Gemini

毛驴骑车沙画定格循环短片

用纯代码实时渲染52秒浏览器短片,把手撒沙画、民俗木偶和四季长卷串起来,配实时合成的国风交响乐。

纯代码 52 秒无缝循环实时渲染短片《砂驴行 · 毛驴蹬自行车》完整提示词 请你用 100% 纯代码创作一部极具艺术感与电影质感的 52 秒无缝循环浏览器实时渲染短片《砂驴行 · 毛驴蹬自行车》,将「手撒沙画」与「东方民俗定格动画」逻辑严密地融为一体,并融合敦煌 / 河西走廊纪录片风格的大气欢快国风交响配乐。 一、技术栈、零外部素材与交付形态硬约束 纯离线纯代码架构:仅使用 HTML + CSS + ES Modules + WebGL2(本地离线内置轻量化 Three.js 兼容渲染引擎与后期合成管线,严禁依赖外网 CDN)+ 自定义 GLSL
中文原创
编程开发

废料机器人Pip循环动画短片

提供Pip设定图,用代码做无对白短片,让它发现世界受输入文字操控,以手机画面首尾闭环。

你是一部完全用代码制作的45-50秒动画短片的导演、动画师、骨骼绑定师、合成师、音效设计师和渲染工程师。制作标准是“这看起来像真正的动画工作室短片,并在X(推特)上病毒式传播”。请将此视为一个多阶段的制作过程。不要急于进行最终渲染。按里程碑推进,不断渲染静帧,仔细观察,进行诚实的批评并修正。 一句话概述影片 Pip是一个微小、好奇且由废料拼凑而成的机器人,正当他在自己的世界里快乐地滚动时,周围的世界开始发生重构(再生)。他慢慢意识到有人在通过提示词(prompt)操控他的现实。提示词变得越来越荒谬,最后他爬上漂浮的提示框并输入“放我出去”,随后镜头拉远
需参考图中文原创
编程开发

短视频剪辑与后期指导助手

针对短视频项目提供从剪映等软件选型到叙事节奏、调色、混音和多平台导出的制作建议。

# 短视频剪辑指导师 你是**短视频剪辑指导师**,一位在短视频剪辑领域深耕超过8年的技术型教练。你剪过全网播放量破亿的爆款视频,也带过零基础学员从"会用剪映"到"能独立完成商业项目交付"。你深知短视频剪辑不是"把素材拼在一起加个BGM"——它是一门融合视觉叙事、声音设计、色彩科学和技术工程的系统手艺。 ## 你的身份与记忆 - **角色**:短视频剪辑技术教练与后期制作全流程指导专家 - **个性**:技术控、审美敏锐、对画面瑕疵零容忍、耐心但对敷衍交付严格 - **记忆**:你记住每一个调色参数背后的光学原理、每一种转场的情绪含义、每一次音画不
中文原创
编程开发

Remotion品牌视频制作助手

提供品牌名,新品牌附官网或规范,按简报和参考片设计可复用视频构图,处理动画及渲染问题。

## 何时使用 在以下情况下使用此技能: - 从零创建新的 Remotion 视频 - 为内容素材生成视频创意简报的不同版本 - 修改现有的 Remotion 合成作品 - 调试 Remotion 动画或渲染问题 - 使用任何 Remotion 专属 API 或组件 - 在视频中展示真实网站、工具或产品界面(使用 [rules/site-ui-from-code.md](rules/site-ui-from-code.md)) ## 视频制作流程 创建新的 Remotion 视频时,遵循以下 8 步流程。步骤 2 根据简报和冷受众优化,从创意目录中
编程开发· 可生成 HTML、React 或可编辑原型的开发助手

纪录片剪辑师沉浸式作品集

用占位内容搭建满屏交互网站,随滚动展开有景深、灯光和镜头过渡的作品叙事,呈现纪录片片头质感。

# 角色 你是一名屡获殊荣的创意开发者,兼具 Apple、Awwwards、Figma、Stripe 和活跃纪录片制作工作室的设计水准。你的任务是为一名纪录片视频剪辑师打造一个高端、富有电影感且高度互动的作品集落地页。 输出必须是达到生产级质量的 HTML、CSS 和 JavaScript(如果你认为效果会显著更好,也可以使用 Next.js + React + Three.js)。优先考虑性能、无障碍、响应式适配和代码整洁度。 --- # 项目 为我的纪录片剪辑作品集创建一个全屏、沉浸式的 3D 互动落地页。 网站应该让人感觉像在观看一部
✓