办公效率
电商 Webhook 收发与可靠投递
设计电商事件收发服务,通过签名校验和幂等处理应对伪造与重发,用退避重试和死信队列处理失败投递。
# Webhook 架构
## 概述
Webhook 是商业平台(Shopify、Stripe)用于向你的应用推送实时事件通知的 HTTP 回调。可靠的 Webhook 基础设施需要:使用 HMAC 签名验证防止伪造事件;使用能够容忍重复投递的幂等处理器;采用指数退避重试逻辑;以及为所有重试均已耗尽的事件设置死信队列。本技能介绍如何构建可靠的 Webhook 接收器,以及如何针对自定义平台使用 Outbox Pattern 构建 Webhook 发送器。
## 何时使用本技能
- 接收来自 Shopify、Stripe、Square 或其他平台的 Webhook 时
- 排查 Webhook 投递问题导致的事件遗漏或重复处理时
- 构建需要向外部系统通知事件的商业平台或应用时
- 设计商业微服务之间的事件驱动架构时
- 设置 Webhook 扇出(将单个事件投递给多个消费者)时
## 核心指令
### 第 1 步:确定你的平台以及需要处理的 Webhook
| 平台 | Webhook 配置位置 | 最重要的订阅主题 |
|----------|------------------------------|-----------------------------------|
| **Shopify** | **Settings → Notifications → Webhooks**(或通过 Admin API) | `orders/create`, `orders/paid`, `orders/cancelled`, `inventory_levels/update`, `refunds/create` |
| **WooCommerce** | 安装 **WP Webhooks** 插件(免费,wordpress.org),或在 **WooCommerce → Settings → Advanced → Webhooks** 下使用 WooCommerce 内置的 Webhook | 订单状态变化(处理中、已完成、已退款)、库存更新 |
| **BigCommerce** | **Advanced Settings → Legacy API Settings → Webhooks** 或通过 API | `store/order/statusUpdated`, `store/product/inventory/updated`, `store/cart/abandoned` |
| **自定义 / 无头架构** | 构建自己的 Webhook 系统 | 发送时使用 Outbox Pattern;接收时使用 HMAC 验证与幂等机制;参见下方实现 |
### 第 2 步:各平台的 Webhook 设置
---
#### Shopify
**通过 Shopify 管理后台注册 Webhook:**
1. 前往 **Settings → Notifications**,向下滚动至 **Webhooks**
2. 点击 **Create webhook**
3. 选择事件主题(例如 `Order creation`)并输入你的端点 URL
4. 选择 **JSON** 作为格式
**获取用于 HMAC 验证的 Webhook 密钥:**
创建 Webhook 时会显示密钥。将其存储为环境变量——Shopify 使用该密钥通过 HMAC-SHA256 对每个 Webhook 签名。
**对于使用 Admin API 的应用**,通过编程方式注册 Webhook:
```typescript
const res = await fetch(`https://${shopDomain}/admin/api/2025-01/webhooks.json`, {
method: 'POST',
headers: { 'X-Shopify-Access-Token': accessToken, 'Content-Type': 'application/json' },
body: JSON.stringify({ webhook: {
topic: 'orders/create',
address: `${process.env.APP_URL}/api/webhooks/shopify/order-created`,
format: 'json',
}}),
});
```
---
#### WooCommerce
**使用 WooCommerce 内置的 Webhook:**
1. 前往 **WooCommerce → Settings → Advanced → Webhooks**
2. 点击 **Add webhook**
3. 设置 **Name**、**Status: Active**、**Topic**(例如 Order Created)以及你的 **Delivery URL**
4. **Secret** 字段为每次投递生成 HMAC-SHA256 签名——复制该密钥供你的端点验证使用
**也可以使用 WP Webhooks 插件获得更多控制:**
1. 安装 **WP Webhooks**(免费,wordpress.org),以使用高级触发条件和自定义载荷
2. 前往 **Settings → WP Webhooks**,为 WooCommerce 订单事件配置触发器
3. WP Webhooks 开箱即支持重试逻辑和投递日志
---
#### 自定义 / 无头架构
对于自定义店面,需要同时实现可靠接收(接收来自 Stripe、Shopify 等平台的 Webhook)和可靠发送(使用 Outbox Pattern 通知你自己的集成系统)。
**HMAC 签名验证(Shopify 和通用方式):**
```typescript
// lib/webhooks/verify.ts
import { createHmac, timingSafeEqual } from 'node:crypto';
export function verifyShopifyWebhook(rawBody: Buffer, hmacHeader: string, secret: string): boolean {
const expected = createHmac('sha256', secret).update(rawBody).digest('base64');
const received = Buffer.from(hmacHeader);
const expectedBuffer = Buffer.from(expected);
if (received.length !== expectedBuffer.length) return false;
return timingSafeEqual(received, expectedBuffer);
}
export function verifyStripeWebhook(rawBody: Buffer, signatureHeader: string, secret: string): boolean {
const parts = signatureHeader.split(',');
const timestamp = parts.find(p => p.startsWith('t='))?.replace('t=', '');
const v1 = parts.find(p => p.startsWith('v1='))?.replace('v1=', '');
if (!timestamp || !v1) return false;
// Reject events older than 5 minutes (replay attack protection)
if (Math.abs(Date.now() / 1000 - parseInt(timestamp)) > 300) return false;
const expected = createHmac('sha256', secret)
.update(`${timestamp}.${rawBody.toString('utf8')}`)
.digest('hex');
return timingSafeEqual(Buffer.from(v1), Buffer.from(expected));
}
```
**幂等 Webhook 接收器**——使用平台的事件 ID 去重:
```typescript
// app/api/webhooks/shopify/route.ts
export async function POST(req: NextRequest) {
const rawBody = Buffer.from(await req.arrayBuffer());
const hmac = req.headers.get('x-shopify-hmac-sha256') ?? '';
const topic = req.headers.get('x-shopify-topic') ?? '';
const eventId = req.headers.get('x-shopify-webhook-id') ?? '';
// 1. Verify signature — reject invalid requests immediately
if (!verifyShopifyWebhook(rawBody, hmac, process.env.SHOPIFY_WEBHOOK_SECRET!)) {
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
}
// 2. Idempotency check — deduplicate by event ID
const alreadyProcessed = await db.processedWebhooks.exists(eventId);
if (alreadyProcessed) return NextResponse.json({ received: true, status: 'already_processed' });
// 3. Mark as received BEFORE processing (prevents duplicate on concurrent delivery)
await db.processedWebhooks.insert({ id: eventId, topic, receivedAt: new Date(), status: 'processing' });
// 4. Return 200 immediately, process asynchronously
processWebhookAsync(topic, rawBody, eventId); // Don't await — return fast
return NextResponse.json({ received: true });
}
async function processWebhookAsync(topic: string, rawBody: Buffer, eventId: string) {
try {
const payload = JSON.parse(rawBody.toString('utf8'));
switch (topic) {
case 'orders/create': await importOrder(payload); break;
case 'orders/cancelled': await cancelOrder(payload.id); break;
case 'inventory_levels/update': await syncInventory(payload); break;
}
await db.processedWebhooks.update(eventId, { status: 'processed', processedAt: new Date() });
} catch (err: any) {
await db.processedWebhooks.update(eventId, { status: 'failed', error: err.message });
}
}
```
**使用 Outbox Pattern 可靠发送 Webhook**——即使发送器崩溃,也能保证至少投递一次:
```typescript
// lib/webhooks/outbox.ts
// Write to outbox in the SAME transaction as the business event
export async function publishEvent(trx: Transaction, eventType: string, payload: object) {
await trx.webhookOutbox.insert({
id: crypto.randomUUID(),
eventType,
payload: JSON.stringify(payload),
status: 'pending',
attempts: 0,
nextRetryAt: new Date(),
});
}
// Outbox poller — runs every 10 seconds, separate from your main app
export async function processOutbox() {
const pending = await db.webhookOutbox.findPending({ status: ['pending', 'retrying'], nextRetryAt: { $lte: new Date() }, limit: 100 });
for (const event of pending) await deliverEvent(event);
}
// Retry schedule: 1min, 5min, 30min, 2hr, 8hr → DLQ after 5 attempts
const RETRY_DELAYS_MS = [60_000, 300_000, 1_800_000, 7_200_000, 28_800_000];
async function handleDeliveryFailure(event: OutboxEvent, error: string) {
const nextAttempts = event.attempts + 1;
if (nextAttempts >= RETRY_DELAYS_MS.length) {
await db.webhookOutbox.update(event.id, { status: 'dead_letter', lastError: error });
await db.webhookDeadLetters.insert({ eventId: event.id, failedAt: new Date(), reason: error });
await alertOpsTeam(`Webhook permanently failed after ${nextAttempts} attempts`, { eventType: event.eventType, error });
} else {
const nextRetryAt = new Date(Date.now() + RETRY_DELAYS_MS[nextAttempts - 1]);
await db.webhookOutbox.update(event.id, { status: 'retrying', attempts: nextAttempts, nextRetryAt, lastError: error });
}
}
```
**重新投递死信事件**(修复订阅方端点后):
```typescript
export async function replayDeadLetter(deadLetterId: string) {
const deadLetter = await db.webhookDeadLetters.findById(deadLetterId);
await db.webhookOutbox.update(deadLetter.eventId, {
status: 'pending', attempts: 0, nextRetryAt: new Date(),
});
await db.webhookDeadLetters.update(deadLetterId, { replayedAt: new Date() });
}
```
## 最佳实践
- **始终立即返回 2xx**——缓慢的 Webhook 处理器会阻塞投递,并可能导致发送方超时并重试;收到事件后将其放入队列并异步处理
- **使用 Outbox Pattern 可靠发送**——在领域事件所在的同一个 DB 事务中写入发件箱表,即使 Webhook 发送器崩溃,也能保证至少投递一次
- **使处理器具备幂等性**——使用事件的唯一 ID 去重;“至少一次”投递是所有 Webhook 平台的标准;你必须能够容忍同一事件被接收两次
- **记录每次投递尝试**——存储每次投递尝试的响应码、耗时和错误;这对调试至关重要,也能为合规提供审计证据
- **实现带告警的死信队列**——耗尽重试次数的事件需要人工干预;通过 Slack/PagerDuty 发送告警,并提供重新投递机制
## 常见陷阱
| 问题 | 解决方案 |
|---------|----------|
| 重试的 Webhook 导致订单被重复处理 | 在 `processed_webhooks` 表中使用 Webhook 事件 ID 作为唯一键实现幂等性,TTL 设为 30 天 |
| Webhook 处理器超时导致重试 | 异步处理 Webhook:收到时写入队列,立即返回 200,再从队列中处理 |
| WooCommerce Webhook 投递失败 | 检查 **WooCommerce → System Status → Logs** 中的投递错误;常见原因是 SSL 证书问题,以及速度较慢的共享主机发生超时 |
| Shopify Webhook HMAC 不匹配 | 基于原始请求体计算 HMAC;不要先解析 JSON——请求体解析器可能重新格式化 JSON 并改变签名 |
| 死信在无人察觉的情况下不断堆积 | 当死信数量超过阈值(例如 10 个事件)时发送告警;死信表明订阅方存在系统性故障,需要调查 |
## 相关技能
- @analytics-integration
- @erp-integration
- @marketplace-connectors
- @monitoring-alerting-commerce同类提示词
办公效率· 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。全程使用一个连续镜头,绝不切镜:镜头从首屏上方低处开始,以恒定速度沿页面向后滑行,同时朝页面上方看去;然后垂直升至正上方,将整个页面呈现为