woocommerce-webhooks

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

WooCommerce Webhooks

WooCommerce Webhooks

When to Use This Skill

何时使用此技能

  • Setting up WooCommerce webhook handlers
  • Debugging signature verification failures
  • Understanding WooCommerce event types and payloads
  • Handling order, product, or customer events
  • Integrating with WooCommerce stores
  • 搭建WooCommerce webhook处理器
  • 调试签名验证失败问题
  • 了解WooCommerce事件类型与负载
  • 处理订单、商品或客户相关事件
  • 与WooCommerce店铺集成

Essential Code (USE THIS)

核心代码(请使用此代码)

WooCommerce Signature Verification (JavaScript)

WooCommerce 签名验证(JavaScript)

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;
  }
}
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 Handler

Express Webhook 处理器

javascript
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');
});
javascript
const express = require('express');
const app = express();

// 关键:使用原始请求体进行签名验证
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 Route (App Router)

Next.js API 路由(App Router)

typescript
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 });
}
typescript
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 Handler

FastAPI 处理器

python
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'}
python
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'}

Common Event Types

常见事件类型

EventTriggered WhenCommon Use Cases
order.created
New order placedSend confirmation emails, update inventory
order.updated
Order status changedTrack fulfillment, send notifications
order.deleted
Order deletedClean up external systems
product.created
Product addedSync to external catalogs
product.updated
Product modifiedUpdate pricing, inventory
customer.created
New customer registeredWelcome emails, CRM sync
customer.updated
Customer info changedUpdate profiles, preferences
事件触发时机常见应用场景
order.created
新订单创建时发送确认邮件、更新库存
order.updated
订单状态变更时跟踪履约进度、发送通知
order.deleted
订单被删除时清理外部系统数据
product.created
商品新增时同步至外部商品目录
product.updated
商品信息修改时更新定价、库存数据
customer.created
新客户注册时发送欢迎邮件、同步至CRM
customer.updated
客户信息变更时更新用户档案、偏好设置

Environment Variables

环境变量

bash
WOOCOMMERCE_WEBHOOK_SECRET=your_webhook_secret_key
bash
WOOCOMMERCE_WEBHOOK_SECRET=your_webhook_secret_key

Headers Reference

请求头参考

WooCommerce webhooks include these headers:
  • X-WC-Webhook-Signature
    - HMAC SHA256 signature (base64)
  • X-WC-Webhook-Topic
    - Event type (e.g., "order.created")
  • X-WC-Webhook-Resource
    - Resource type (e.g., "order")
  • X-WC-Webhook-Event
    - Action (e.g., "created")
  • X-WC-Webhook-Source
    - Store URL
  • X-WC-Webhook-ID
    - Webhook ID
  • X-WC-Webhook-Delivery-ID
    - Unique delivery ID
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
    - 店铺URL
  • X-WC-Webhook-ID
    - Webhook ID
  • X-WC-Webhook-Delivery-ID
    - 唯一交付ID

Local Development

本地开发

For local webhook testing, install Hookdeck CLI:
bash
undefined
对于本地webhook测试,安装Hookdeck CLI:
bash
undefined

Install via npm

通过npm安装

npm install -g hookdeck-cli
npm install -g hookdeck-cli

Or via Homebrew

或通过Homebrew安装

brew install hookdeck/hookdeck/hookdeck

Then start the tunnel:

```bash
hookdeck listen 3000 --path /webhooks/woocommerce
No account required. Provides local tunnel + web UI for inspecting requests.
brew install hookdeck/hookdeck/hookdeck

然后启动隧道:

```bash
hookdeck listen 3000 --path /webhooks/woocommerce
无需注册账号,提供本地隧道与用于检查请求的Web界面。

Reference Materials

参考资料

  • overview.md
    - What WooCommerce webhooks are, common event types
  • setup.md
    - Configure webhooks in WooCommerce admin, get signing secret
  • verification.md
    - Signature verification details and gotchas
  • examples/
    - Complete runnable examples per framework
  • overview.md
    - 介绍WooCommerce webhook定义、常见事件类型
  • setup.md
    - 在WooCommerce后台配置webhook、获取签名密钥
  • verification.md
    - 签名验证细节与注意事项
  • examples/
    - 各框架对应的完整可运行示例

Recommended: webhook-handler-patterns

推荐:webhook-handler-patterns

For production-ready webhook handlers, also install the webhook-handler-patterns skill for:
  • <a href="https://github.com/hookdeck/webhook-skills/blob/main/skills/webhook-handler-patterns/references/handler-sequence.md">Handler sequence</a>
  • <a href="https://github.com/hookdeck/webhook-skills/blob/main/skills/webhook-handler-patterns/references/idempotency.md">Idempotency</a>
  • <a href="https://github.com/hookdeck/webhook-skills/blob/main/skills/webhook-handler-patterns/references/error-handling.md">Error handling</a>
  • <a href="https://github.com/hookdeck/webhook-skills/blob/main/skills/webhook-handler-patterns/references/retry-logic.md">Retry logic</a>
如需生产级别的webhook处理器,还可安装webhook-handler-patterns技能以获取:
  • <a href="https://github.com/hookdeck/webhook-skills/blob/main/skills/webhook-handler-patterns/references/handler-sequence.md">处理器流程</a>
  • <a href="https://github.com/hookdeck/webhook-skills/blob/main/skills/webhook-handler-patterns/references/idempotency.md">幂等性处理</a>
  • <a href="https://github.com/hookdeck/webhook-skills/blob/main/skills/webhook-handler-patterns/references/error-handling.md">错误处理</a>
  • <a href="https://github.com/hookdeck/webhook-skills/blob/main/skills/webhook-handler-patterns/references/retry-logic.md">重试逻辑</a>

Related Skills

相关技能