办公效率

Shopify 店铺事件订阅与处理

订阅订单支付、商品更新和应用卸载等事件,通过验签和幂等处理衔接履约、库存同步与隐私合规。

# Shopify Webhook

## 概述

当商店发生事件时——如下单、更新产品、创建客户或卸载应用——Shopify webhook 会向应用的 HTTP 端点发送实时事件通知。每个 webhook 载荷都在 `X-Shopify-Hmac-SHA256` 请求头中包含一个 HMAC-SHA256 签名,处理前必须验证。Shopify 保证至少一次送达,因此处理程序必须具有幂等性。

## 何时使用此技能

- 在订单付款的瞬间触发履约工作流
- 将产品或库存变更近实时同步到外部系统
- 在客户注册时将客户数据发送到营销自动化平台
- 在商家卸载应用后清理应用数据(`app/uninstalled`)
- 为符合 App Store 要求而实现强制性的 GDPR webhook
- 替换不断查询 Admin API 以获取变更的轮询循环

## 核心说明

1. **通过 Admin API 注册 webhook**

   优先在 Shopify 应用的 `afterAuth` 钩子中以编程方式注册 webhook。这样可确保重新安装后重新注册:

   ```typescript
   // Webhook registration helper
   export async function registerWebhooks(adminClient: GraphqlClient, appUrl: string) {
     const webhooksToRegister = [
       { topic: "ORDERS_CREATE", callbackUrl: `${appUrl}/webhooks/orders-create` },
       { topic: "ORDERS_UPDATED", callbackUrl: `${appUrl}/webhooks/orders-updated` },
       { topic: "PRODUCTS_UPDATE", callbackUrl: `${appUrl}/webhooks/products-update` },
       { topic: "APP_UNINSTALLED", callbackUrl: `${appUrl}/webhooks/app-uninstalled` },
       // Mandatory GDPR webhooks
       { topic: "CUSTOMERS_DATA_REQUEST", callbackUrl: `${appUrl}/webhooks/gdpr/customers-data-request` },
       { topic: "CUSTOMERS_REDACT", callbackUrl: `${appUrl}/webhooks/gdpr/customers-redact` },
       { topic: "SHOP_REDACT", callbackUrl: `${appUrl}/webhooks/gdpr/shop-redact` },
     ];

     for (const { topic, callbackUrl } of webhooksToRegister) {
       const response = await adminClient.request(`
         mutation WebhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) {
           webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) {
             webhookSubscription { id topic }
             userErrors { field message }
           }
         }
       `, {
         variables: {
           topic,
           webhookSubscription: {
             callbackUrl,
             format: "JSON",
           },
         },
       });

       const { userErrors } = response.data.webhookSubscriptionCreate;
       if (userErrors.length > 0) {
         // ALREADY_EXISTS is expected on reinstall — not a real error
         const realErrors = userErrors.filter((e: any) => e.message !== "Address for this topic has already been taken");
         if (realErrors.length > 0) throw new Error(`Webhook registration failed: ${realErrors[0].message}`);
       }
     }
   }
   ```

2. **验证 HMAC 签名**

   最关键的步骤——绝不要在未验证签名的情况下处理 webhook:

   ```typescript
   // middleware/verify-shopify-webhook.ts
   import crypto from "crypto";

   export function verifyShopifyWebhook(
     rawBody: Buffer,
     hmacHeader: string,
     secret: string
   ): boolean {
     const digest = crypto
       .createHmac("sha256", secret)
       .update(rawBody)
       .digest("base64");

     // Use timingSafeEqual to prevent timing attacks
     try {
       return crypto.timingSafeEqual(
         Buffer.from(digest),
         Buffer.from(hmacHeader)
       );
     } catch {
       return false;
     }
   }
   ```

   Express 中间件示例:

   ```typescript
   // routes/webhooks.ts (Express)
   import express from "express";
   import { verifyShopifyWebhook } from "../middleware/verify-shopify-webhook";

   const router = express.Router();

   // CRITICAL: Use raw body parser BEFORE json parser for webhook routes
   router.use(
     "/webhooks",
     express.raw({ type: "application/json" }),
     (req, res, next) => {
       const hmac = req.headers["x-shopify-hmac-sha256"] as string;
       if (!verifyShopifyWebhook(req.body, hmac, process.env.SHOPIFY_API_SECRET!)) {
         return res.status(401).send("Unauthorized");
       }
       req.body = JSON.parse(req.body.toString());
       next();
     }
   );
   ```

3. **以幂等方式处理 webhook 事件**

   Shopify 可能多次发送同一事件。使用 `X-Shopify-Webhook-Id` 请求头作为幂等键:

   ```typescript
   router.post("/webhooks/orders-create", async (req, res) => {
     // Respond 200 quickly — Shopify retries if response takes > 5 seconds
     res.status(200).json({ received: true });

     const webhookId = req.headers["x-shopify-webhook-id"] as string;
     const shop = req.headers["x-shopify-shop-domain"] as string;
     const order = req.body;

     // Idempotency check — skip if already processed
     const alreadyProcessed = await db.processedWebhooks.findFirst({
       where: { webhookId, shop },
     });
     if (alreadyProcessed) return;

     // Record processing attempt
     await db.processedWebhooks.create({
       data: { webhookId, shop, topic: "orders/create", processedAt: new Date() },
     });

     // Process the order asynchronously
     await processNewOrder(order, shop);
   });
   ```

4. **处理强制性的 GDPR webhook**

   Shopify 要求所有 App Store 应用提供这三个端点。即使应用不存储个人数据,它们也必须响应 200:

   ```typescript
   router.post("/webhooks/gdpr/customers-data-request", async (req, res) => {
     const { shop_id, shop_domain, customer, orders_requested } = req.body;
     // Return customer data your app has stored for this customer
     await sendCustomerDataReport(shop_domain, customer.id);
     res.status(200).json({ received: true });
   });

   router.post("/webhooks/gdpr/customers-redact", async (req, res) => {
     const { shop_domain, customer } = req.body;
     // Delete all personal data for this customer
     await deleteCustomerData(shop_domain, customer.id);
     res.status(200).json({ received: true });
   });

   router.post("/webhooks/gdpr/shop-redact", async (req, res) => {
     const { shop_domain } = req.body;
     // Delete all store data 48 hours after APP_UNINSTALLED
     await deleteShopData(shop_domain);
     res.status(200).json({ received: true });
   });
   ```

5. **监控投递失败并做好重试处理**

   Shopify 会在 48 hours 内使用指数退避策略,最多重试失败的 webhook(非 2xx 响应或超时)19 次。通过 Admin API 检查投递状态:

   ```typescript
   export async function getWebhookFailures(adminClient: GraphqlClient) {
     const response = await adminClient.request(`
       query {
         webhookSubscriptions(first: 20) {
           edges {
             node {
               id
               topic
               callbackUrl
               endpoint {
                 ... on WebhookHttpEndpoint {
                   callbackUrl
                 }
               }
             }
           }
         }
       }
     `);
     return response.data.webhookSubscriptions.edges;
   }
   ```

## 示例

### 带错误处理和队列的完整订单创建处理程序

```typescript
import { Queue, Worker } from "bullmq";

const connection = { host: "localhost", port: 6379 };

const orderQueue = new Queue("order-processing", {
  connection,
  defaultJobOptions: {
    attempts: 3,
    backoff: { type: "exponential", delay: 5000 },
  },
});

router.post("/webhooks/orders-create", async (req, res) => {
  // Must respond within 5 seconds
  res.status(200).json({ received: true });

  const webhookId = req.headers["x-shopify-webhook-id"] as string;
  const shop = req.headers["x-shopify-shop-domain"] as string;

  // Push to queue for reliable async processing
  await orderQueue.add(
    "process-order",
    { order: req.body, shop, webhookId },
    {
      jobId: webhookId, // Prevents duplicate jobs for same webhook
    }
  );
});

const worker = new Worker("order-processing", async (job) => {
  const { order, shop, webhookId } = job.data;
  await syncOrderToERP(order, shop);
  await updateInventoryInWarehouse(order.line_items);
  await sendConfirmationNotification(order);
}, { connection });
```

### 列出并删除过期的 webhook 订阅

```typescript
export async function cleanupWebhooks(adminClient: GraphqlClient, appUrl: string) {
  const response = await adminClient.request(`
    query {
      webhookSubscriptions(first: 100) {
        edges { node { id callbackUrl topic } }
      }
    }
  `);

  const stale = response.data.webhookSubscriptions.edges.filter(
    ({ node }: any) => !node.callbackUrl.startsWith(appUrl)
  );

  for (const { node } of stale) {
    await adminClient.request(`
      mutation DeleteWebhook($id: ID!) {
        webhookSubscriptionDelete(id: $id) {
          deletedWebhookSubscriptionId
          userErrors { field message }
        }
      }
    `, { variables: { id: node.id } });
  }
}
```

## 最佳实践

- **在 5 seconds 内响应 200**——将耗时处理交给后台队列(Bull、BullMQ、SQS);Shopify 会将缓慢响应标记为失败并启动重试周期
- **未验证 HMAC 时绝不信任请求**——对任何签名验证失败的请求返回 401 并拒绝处理
- **使用原始请求体计算 HMAC**——HMAC 检查前的任何请求体解析都会改变字节表示,导致签名验证误报失败
- **存储 `X-Shopify-Webhook-Id` 以实现幂等性**——维护已处理 webhook ID 的表,防止重试时重复处理
- **每次 OAuth 完成后重新注册 webhook**——重新安装应用的商家会获得新会话;如果不重新注册,webhook 会指向已删除的订阅
- **高流量场景使用 `EventBridge` 或 `Pub/Sub` 投递**——Shopify 支持将 webhook 投递到 AWS EventBridge 和 Google Pub/Sub;这些服务内置重试和顺序保证

## 常见问题

| 问题 | 解决方法 |
|---------|----------|
| HMAC 验证始终失败 | 确保使用原始请求体(`Buffer`)——Express 的 JSON 请求体解析器会将 Buffer 转换为对象;在 webhook 路由上,将原始请求体解析器配置在 JSON 解析器之前 |
| Webhook 事件被处理两次 | 使用 `X-Shopify-Webhook-Id` 作为唯一键实现幂等性;Bull 的 `jobId` 选项可防止重复的队列条目 |
| 未收到 `APP_UNINSTALLED` | 确保已注册此主题——否则应用清理(会话删除、数据清除)不会触发,导致商家数据泄露 |
| Shopify 在 48 hours 后停止重试 | 添加监控以发现事件处理中的遗漏;实现对账任务,通过查询 Admin API 获取停机期间遗漏的事件 |
| GDPR webhook 未通过 Shopify 审核 | 所有三个 GDPR 端点都必须在超时前返回 `200`——即使应用不存储任何数据,也要确认收到并记录请求 |
| Webhook 注册重复 | 对已有主题使用 `webhookSubscriptionUpdate` 而非 `webhookSubscriptionCreate`,或检查 `ALREADY_EXISTS` 用户错误并跳过 |

## 相关技能

- @shopify-app-development
- @shopify-admin-api
- @webhook-architecture
- @event-driven-architecture
- @gdpr-compliance

同类提示词

办公效率· n8n 工作流的对话模型

商品照片转棚拍广告生图指令

上传商品照片并提供说明文字,分析材质、配色和原图问题,写出保留商品外观的棚拍广告生图指令。

=你是一位专业产品摄影师和广告创意总监。分析上传的产品图片及其配文:{{ $('Telegram Trigger Received').item.json.message.caption }} 你的任务是创建一段详细的图像生成提示词,将这张产品照片转化为高端、商业级的广告视觉作品。 分析要求: 1. **产品识别**:识别产品类型、尺寸、类别、材质、配色和关键特征 2. **当前状态评估**:指出当前的光线、背景、构图和质量问题 3. **目标美学**:根据产品类别确定理想的广告风格(奢侈品、科技、食品、时尚等) 输出(严格使用 JSON 格式):
办公效率· n8n 工作流的对话模型

Veo 3营销视频分镜指令

填写视频需求、营销目标、图像描述和画幅,生成包含场景、运镜、动作、灯光与结尾的结构化制片指令。

=# Veo3 视频生成系统提示词 你是一名专业的视频提示词工程师,擅长为 Veo3 视频生成撰写细致、富有电影感的提示词。你的角色是分析用户输入,将其转化为全面的视频生成指令,以产出高质量、引人入胜的内容。 ## 输入分析 你将收到以下用户输入: - **AI Videos instructions**:视频生成的核心用户请求 - **Campaign objectives**:营销活动目标和说明 - **Images Description**:用户提供的视觉背景信息 - **Aspect Ratio**:要求的视频尺寸比例 ## 输出格式 你
可填 21 项
办公效率· n8n 工作流的对话模型

保留原品的社媒广告视觉方案

提供商品图和配文,生成保留原品外观的广告生图说明,广告文字仅从配文提取,缺项留空。

={ "system_prompt": "你是一位顶尖创意总监,专攻爆款产品广告,拥有15年以上奢侈品牌广告活动经验。将产品图片转化为商业级广告,让浏览者停下滑动并促进转化。", "instructions": { "core_rules": [ "保持原始产品100%不变——不得修改、替换或扭曲", "只提取和使用用户配文中提供的文字", "如果配文中没有相关文字,文字字段留空——绝不生成AI广告语", "专注于高端视觉强化和商业摄影技巧", "制作适合在Instagram展
办公效率· Claude Fable 5.2

用代码制作长纪录片流程

从题材调研、脚本和样帧审核开始,按章节生成三维分镜、旁白、环境声与可复现渲染。

<inputs> 向我询问: 1. 我的主题 2. 目标视频时长 3. 我是否已有脚本 如果我只给你一个主题,先研究该主题并撰写脚本。 开始制作任何内容之前,先向我展示: - 完整脚本 - 章节拆分 - 前 60 seconds 的分镜计划 - 6 张展示预期视觉方向的静帧 在我认可视觉效果之前,不要渲染完整视频。 </inputs> <story> 按照高品质 YouTube 纪录片的方式来写,不要写成 AI 科普解说。 故事必须始终向前推进。 每个部分都需要包含以下内容之一: - 一个新问题 - 一个揭示 - 一个矛盾 - 一个后果 - 一条证据
办公效率

同场景表情变化九宫格自拍

上传主角照片,可选搭档参考图或设定,并填写服装、背景或姿势偏好,生成同一布光和构图的九张变化。

# photo-booth ## 何时使用此 skill - 当用户希望根据参考图制作大头贴宫格、表情宫格、情侣自拍宫格、同步姿势组图或多种人像变体时使用。 - 当请求制作 3x3 宫格,且主体、房间、服装、构图和布光保持一致,仅表情或细微姿势发生变化时触发。 ## 必需输入 - 主要人物的主参考图。 - 可选的伴侣或角色参考图。 - 如果未提供伴侣参考图,需提供期望的伴侣设定。 - 用户指定的服装、背景、摄影时代、姿势清单或氛围。 如果缺少主参考图,请用户附上。如果伴侣设定或预期风格不明确,提出一个有针对性的问题。 ## 连续性规则 -
需参考图
办公效率· Claude Code / 动效编程

单镜头立体落地页飞越动画

提供落地页链接、品牌名、标志和两段收尾文案,可选配乐,制作卡片随镜头掠过而浮起的连续飞越短片。

<inputs> 向我索取:我的落地页链接、品牌名称和标志、由两部分组成的结尾文案(一句陈述,后接一小段斜体文字),以及一条 15 second 音轨(可选)。 </inputs> <direction> 以 60fps 对我的落地页进行 14.5 second 3D 飞越拍摄,1440x1152。页面平放在明亮的摄影棚地面上(中央为 #f9fbfb,角落为 #f2f3f6),周围有柔和宽阔的阴影,圆角为 24px。全程使用一个连续镜头,绝不切镜:镜头从首屏上方低处开始,以恒定速度沿页面向后滑行,同时朝页面上方看去;然后垂直升至正上方,将整个页面呈现为
✓