Webhooks API

Webhook 允许你的应用在 Mercozy 商店发生事件时接收实时 HTTP 通知。无需轮询 API,只需注册一个 URL,Mercozy 会自动将事件数据 POST 到该地址。

快速开始

3 步即可开始接收事件:

第 1 步:注册你的端点

从以下位置获取 API 密钥 设置 > 集成 > API 密钥. 需要管理员权限。Webhook 签名密钥(whsec_xxx)在创建端点时自动生成,且仅显示一次。

bash
curl -X POST "https://api.mercozy.com/api/v1/external/webhooks" \
  -H "X-API-Key: mk_live_your_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My ERP Integration",
    "url": "https://your-app.com/webhooks/mercozy",
    "events": ["order.created", "order.cancelled", "payment.received"]
  }'
第 2 步:处理传入的事件
javascript
app.post('/webhooks/mercozy', (req, res) => {
  // 1. Verify signature (see below)
  const signature = req.headers['x-webhook-signature'];
  if (!verifySignature(req.body, signature, WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }

  // 2. Process the event
  const { type, data } = req.body;
  switch (type) {
    case 'order.created':
      syncOrderToERP(data);
      break;
    case 'payment.received':
      updateAccountingSystem(data);
      break;
  }

  // 3. Respond quickly with 200
  res.status(200).json({ received: true });
});
第 3 步:测试你的端点
bash
curl -X POST "https://api.mercozy.com/api/v1/external/webhooks/{id}/test" \
  -H "X-API-Key: mk_live_your_key_here"

接口列表

GET

/webhooks

webhooks:read

列出所有已注册的 Webhook 端点。

POST

/webhooks

webhooks:write

注册新的 Webhook 端点以接收事件通知。

PUT

/webhooks/:id

webhooks:write

更新现有 Webhook 端点(URL、事件或启用状态)。

DELETE

/webhooks/:id

webhooks:write

删除 Webhook 端点。事件将不再推送。

字段参考
字段类型必填描述

id

string

唯一 Webhook 标识符(只读)

name

string

端点的描述性名称

url

string

接收 Webhook 事件的 HTTPS 端点 URL

events

string[]

要订阅的事件类型数组

secret

string

用于验证负载的签名密钥(只读,创建时生成)

isActive

boolean

Webhook 是否启用(默认:true)

createdAt

datetime

ISO 8601 时间戳(只读)


可用事件类型

Mercozy 支持 6 个类别共 18 种 Webhook 事件类型。只需订阅你需要的事件。

订单
  • order.created

    新订单创建时触发

  • order.updated

    订单信息修改时触发

  • order.cancelled

    订单取消时触发

  • order.completed

    订单标记为已完成时触发

  • order.status_changed

    订单状态变更时触发

支付
  • payment.received

    收款成功或货到付款收款时触发

  • payment.refunded

    退款或取消付款时触发

商品
  • product.created

    新增商品时触发

  • product.updated

    商品信息变更时触发

  • product.deleted

    删除商品时触发

库存
  • stock.low

    库存低于阈值时触发

  • stock.updated

    库存数量变更时触发

客户
  • customer.created

    新客户注册时触发

  • customer.updated

    客户信息更新时触发

配送
  • delivery.batch_started

    配送批次发车时触发

  • delivery.batch_completed

    批次中所有站点完成时触发

  • delivery.completed

    单个配送完成时触发

  • delivery.failed

    配送尝试失败时触发


Webhook 负载

每次 Webhook 推送包含事件类型、时间戳和相关资源数据。

订单事件数据
json
{
  "id": "evt_clx1abc2def3",
  "type": "order.created",
  "timestamp": "2026-03-19T10:30:00Z",
  "data": {
    "id": "clx9order123",
    "orderNumber": "ORD-1042",
    "status": "PENDING",
    "total": 4999,
    "currency": "USD"
  }
}
支付事件数据
json
{
  "id": "evt_clx2pay4ghi5",
  "type": "payment.received",
  "timestamp": "2026-03-19T10:35:00Z",
  "data": {
    "orderId": "clx9order123",
    "orderNumber": "ORD-1042",
    "amount": 4999,
    "currency": "USD",
    "paymentMethod": "CARD",
    "status": "CAPTURED"
  }
}
商品事件数据
json
{
  "id": "evt_clx3prod6jkl",
  "type": "product.created",
  "timestamp": "2026-03-19T11:00:00Z",
  "data": {
    "id": "clx9prod789",
    "name": "Organic Coffee Beans",
    "sku": "COF-001",
    "price": 1299,
    "status": "ACTIVE"
  }
}
配送事件数据
json
{
  "id": "evt_clx4del7mno",
  "type": "delivery.completed",
  "timestamp": "2026-03-19T14:22:00Z",
  "data": {
    "orderId": "clx9order123",
    "orderNumber": "ORD-1042"
  }
}

HTTP 请求头

每个 Webhook 请求包含以下请求头:

字段类型必填描述

Content-Type

string

application/json

X-Webhook-Signature

string

HMAC-SHA256 签名:sha256={十六进制摘要}

X-Webhook-Timestamp

string

Unix 毫秒时间戳

X-Webhook-ID

string

用于去重的唯一事件 ID

User-Agent

string

Mercozy-Webhook/1.0 (+https://www.mercozy.com/docs/webhooks)


签名验证

每个 Webhook 请求都包含 X-Webhook-Signature 头,其中包含 HMAC-SHA256 签名。在处理事件前务必验证此签名,确保请求来自 Mercozy。

Node.js
javascript
const crypto = require('crypto');

function verifyWebhook(rawBody, signature, timestamp, secret) {
  // Signature is computed over "timestamp.body"
  const message = timestamp + '.' + rawBody;
  const expected = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(message)
    .digest('hex');
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

// Express middleware
app.post('/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
  const sig = req.headers['x-webhook-signature'];
  const ts = req.headers['x-webhook-timestamp'];
  if (!verifyWebhook(req.body, sig, ts, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Invalid signature');
  }
  const event = JSON.parse(req.body);
  // Process event...
  res.status(200).json({ received: true });
});
Python
python
import hmac
import hashlib

def verify_webhook(payload: bytes, signature: str, timestamp: str, secret: str) -> bool:
    # Signature is computed over "timestamp.body"
    message = (timestamp + '.').encode() + payload
    expected = 'sha256=' + hmac.new(
        secret.encode(),
        message,
        hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected)

# Flask example
@app.route('/webhooks', methods=['POST'])
def handle_webhook():
    sig = request.headers.get('X-Webhook-Signature')
    ts = request.headers.get('X-Webhook-Timestamp')
    if not verify_webhook(request.data, sig, ts, WEBHOOK_SECRET):
        return 'Invalid signature', 401
    event = request.get_json()
    # Process event...
    return {'received': True}, 200
PHP
php
<?php
function verifyWebhook(string $payload, string $signature, string $timestamp, string $secret): bool {
    // Signature is computed over "timestamp.body"
    $message = $timestamp . '.' . $payload;
    $expected = 'sha256=' . hash_hmac('sha256', $message, $secret);
    return hash_equals($expected, $signature);
}

$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_WEBHOOK_SIGNATURE'] ?? '';
$timestamp = $_SERVER['HTTP_X_WEBHOOK_TIMESTAMP'] ?? '';
if (!verifyWebhook($payload, $signature, $timestamp, $webhookSecret)) {
    http_response_code(401);
    exit('Invalid signature');
}
$event = json_decode($payload, true);
// Process event...
http_response_code(200);
echo json_encode(['received' => true]);

重试策略

如果你的端点返回非 2xx 状态码或超时(10 秒),Mercozy 将使用指数退避进行重试:

字段类型必填描述

第 1

立即

第 2

延迟 ~1s

第 3

延迟 ~4s

3 次重试失败后,投递将标记为失败。你可以通过仪表板或 API 手动重试。


最佳实践

  • 5 秒内响应立即返回 200 状态码,异步处理事件。Mercozy 超时时间为 10 秒。

  • 始终验证签名处理事件前检查 X-Webhook-Signature 头,防止伪造请求。

  • 处理重复(幂等性)使用 X-Webhook-ID 头去重。存储已处理的事件 ID,跳过重复事件。

  • 使用 HTTPS 端点生产环境要求使用 HTTPS URL 以保护传输中的数据。

  • 记录日志并监控记录所有传入的 Webhook 并监控失败情况。使用投递日志 API 检查投递状态。