关于 woocommerce-webhooks
woocommerce-webhooks 是面向 WooCommerce 集成开发的技能,涵盖 Webhook 处理器、签名验证、事件和载荷参考,并提供多种框架示例。
主要功能
- 01Webhook 签名验证示例
- 02订单、商品和客户事件参考
- 03Express、Next.js 与 FastAPI 示例
- 04本地隧道测试说明
适用场景
- 01接收订单状态变化并触发通知
- 02同步商品数据到外部目录
- 03排查签名验证失败
- 04在本地检查 Webhook 请求
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ hookdeck/ webhook-skills --skill woocommerce-webhooks安装后在 Claude Code 中输入/woocommerce-webhooks确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
examples/express/.env.examplepackage.jsonREADME.mdexamples/express/src/index.jsexamples/express/test/webhook.test.jsexamples/fastapi/.env.examplemain.pyREADME.mdrequirements.txttest_webhook.pyexamples/nextjs/.env.examplepackage.jsonREADME.mdvitest.config.tsexamples/nextjs/app/webhooks/woocommerce/route.tsexamples/nextjs/test/webhook.test.tsreferences/overview.mdsetup.mdverification.md详细介绍
WooCommerce Webhooks
适用场景
- 设置 WooCommerce Webhook 处理程序
- 调试签名验证失败问题
- 了解 WooCommerce 事件类型和负载
- 处理订单、商品或客户事件
- 与 WooCommerce 商店集成
核心代码(请使用)
WooCommerce 签名验证(JavaScript)
const crypto = require('crypto');
function verifyWooCommerceWebhook(rawBody, signature, secret) {
if (!signature || !secret) return false;
const hash = crypto
.createHmac('sha256', secret)
.update(rawBody)
.digest('base64');
try {
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(hash)
);
} catch {
return false;
}
}
Express Webhook 处理程序
const express = require('express');
const app = express();
// CRITICAL: Use raw body for signature verification
app.use('/webhooks/woocommerce', express.raw({ type: 'application/json' }));
app.post('/webhooks/woocommerce', (req, res) => {
const signature = req.headers['x-wc-webhook-signature'];
const secret = process.env.WOOCOMMERCE_WEBHOOK_SECRET;
if (!verifyWooCommerceWebhook(req.body, signature, secret)) {
return res.status(400).send('Invalid signature');
}
const payload = JSON.parse(req.body);
const topic = req.headers['x-wc-webhook-topic'];
console.log(`Received ${topic} event:`, payload.id);
res.status(200).send('OK');
});
Next.js API 路由(App Router)
import crypto from 'crypto';
import { NextRequest } from 'next/server';
export async function POST(request: NextRequest) {
const signature = request.headers.get('x-wc-webhook-signature');
const secret = process.env.WOOCOMMERCE_WEBHOOK_SECRET;
const rawBody = await request.text();
if (!verifyWooCommerceWebhook(rawBody, signature, secret)) {
return new Response('Invalid signature', { status: 400 });
}
const payload = JSON.parse(rawBody);
const topic = request.headers.get('x-wc-webhook-topic');
console.log(`Received ${topic} event:`, payload.id);
return new Response('OK', { status: 200 });
}
FastAPI 处理程序
import hmac
import hashlib
import base64
from fastapi import FastAPI, Request, HTTPException
app = FastAPI()
def verify_woocommerce_webhook(raw_body: bytes, signature: str, secret: str) -> bool:
if not signature or not secret:
return False
hash_digest = hmac.new(
secret.encode(),
raw_body,
hashlib.sha256
).digest()
expected_signature = base64.b64encode(hash_digest).decode()
return hmac.compare_digest(signature, expected_signature)
@app.post('/webhooks/woocommerce')
async def handle_webhook(request: Request):
raw_body = await request.body()
signature = request.headers.get('x-wc-webhook-signature')
secret = os.getenv('WOOCOMMERCE_WEBHOOK_SECRET')
if not verify_woocommerce_webhook(raw_body, signature, secret):
raise HTTPException(status_code=400, detail='Invalid signature')
payload = await request.json()
topic = request.headers.get('x-wc-webhook-topic')
print(f"Received {topic} event: {payload.get('id')}")
return {'status': 'success'}
常见事件类型
| 事件 | 触发时机 | 常见用例 |
|---|---|---|
order.created | 下单时 | 发送确认邮件、更新库存 |
order.updated | 订单状态更改时 | 跟踪履约情况、发送通知 |
order.deleted | 删除订单时 | 清理外部系统 |
product.created | 添加商品时 | 同步到外部目录 |
product.updated | 修改商品时 | 更新定价、库存 |
customer.created | 新客户注册时 | 发送欢迎邮件、同步到 CRM |
customer.updated | 客户信息更改时 | 更新个人资料、偏好设置 |
环境变量
WOOCOMMERCE_WEBHOOK_SECRET=your_webhook_secret_key
标头参考
WooCommerce Webhook 包含以下标头:
X-WC-Webhook-Signature- HMAC SHA256 签名(base64)X-WC-Webhook-Topic- 事件类型(例如,“order.created”)X-WC-Webhook-Resource- 资源类型(例如,“order”)X-WC-Webhook-Event- 操作(例如,“created”)X-WC-Webhook-Source- 商店 URLX-WC-Webhook-ID- Webhook IDX-WC-Webhook-Delivery-ID- 唯一投递 ID
本地开发
如需在本地测试 Webhook,请安装 Hookdeck CLI:
然后启动隧道:
npx hookdeck-cli listen 3000 woocommerce --path /webhooks/woocommerce
无需账号。提供本地隧道和 Web 界面,可用于检查请求。
参考资料
overview.md- WooCommerce Webhook 简介和常见事件类型setup.md- 在 WooCommerce 管理后台配置 Webhook 并获取签名密钥verification.md- 签名验证详情和注意事项examples/- 各框架完整的可运行示例
推荐:webhook-handler-patterns
如需用于生产环境的 Webhook 处理程序,还可安装 webhook-handler-patterns 技能,了解:
相关技能
- stripe-webhooks - 使用 HMAC 验证的 Stripe 支付 Webhook
- shopify-webhooks - 使用 HMAC 验证的 Shopify 商店 Webhook
- github-webhooks - GitHub 仓库 Webhook
- paddle-webhooks - Paddle 账单 Webhook
- webhook-handler-patterns - 幂等性、错误处理、重试逻辑
- hookdeck-event-gateway - 生产环境 Webhook 基础设施
评论
支持 Markdown