用途
Shopify Webhooks 技能用于指导开发者处理 Shopify Webhook,包括配置、验证与处理。Webhook 是与 Shopify 数据保持同步的推荐方式,它允许应用在店铺发生事件时(例如 orders/create、app/uninstalled)接收实时通知。当用户需要设置 Webhook 订阅、验证请求来源或处理 Webhook 事件时,可使用此技能。
主要能力
1. 验证(关键)
所有 Webhook 请求都必须经过验证,以确认其确实来自 Shopify。
HMAC 验证:Shopify 在每个 Webhook 请求中都包含 X-Shopify-Hmac-Sha256 头。这是请求体的 base64 编码 HMAC-SHA256 摘要,使用你的 Client Secret(API Secret Key)作为签名密钥。
重要提示:验证时务必使用原始请求体(Buffer)。经过解析的 JSON 请求体可能存在细微差异,导致验证失败。
Node.js 通用示例:
const crypto = require('crypto');
function verifyWebhook(rawBody, hmacHeader, apiSecret) {
const digest = crypto
.createHmac('sha256', apiSecret)
.update(rawBody, 'utf8')
.digest('base64');
return crypto.timingSafeEqual(
Buffer.from(digest),
Buffer.from(hmacHeader)
);
}
Remix / Shopify App Template(推荐):如果使用 @shopify/shopify-app-remix,验证由 authenticate.webhook 辅助函数自动处理。
/* app/routes/webhooks.tsx */
import { authenticate } from "../shopify.server";
export const action = async ({ request }) => {
const { topic, shop, session, admin, payload } = await authenticate.webhook(request);
if (!admin) {
// The webhook request was not valid.
return new Response();
}
switch (topic) {
case "APP_UNINSTALLED":
if (session) {
await db.session.deleteMany({ where: { shop } });
}
break;
case "ORDERS_CREATE":
console.log(`Order created: ${payload.id}`);
break;
}
return new Response();
};
2. 注册
应用级 Webhook(推荐):在 shopify.app.toml 中配置,应用部署时会自动注册,更易于管理。适用于应用通用的事件(例如 app/uninstalled)。
[webhooks]
api_version = "2025-10"
[[webhooks.subscriptions]]
topics = [ "app/uninstalled", "orders/create" ]
uri = "/webhooks"
店铺级 Webhook(高级):通过 Admin API 使用 webhookSubscriptionCreate。适用于:按店铺定制、配置方式不支持的事件、运行时动态注册。
mutation webhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) {
webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) {
userErrors {
field
message
}
webhookSubscription {
id
}
}
}
3. 强制合规(GDPR)
公共应用必须实现特定的 Webhook 以符合隐私法规。这些在 Partner Dashboard(App > Configuration > Privacy compliance)中配置,而不是在 shopify.app.toml 或通过 API 配置。
- customers/data_request:导出客户数据的请求。
- customers/redact:删除客户数据的请求。
- shop/redact:删除店铺数据的请求(卸载后 48 小时)。
警告:未能处理这些请求可能导致应用被下架。
使用方式与最佳实践
- 幂等性:Webhook 可能被多次投递。确保处理逻辑具备幂等性(例如,在执行操作前检查订单是否已被处理)。
- 响应时间:立即返回 200 OK(5 秒内)。长时间运行的任务应异步执行(例如使用后台队列)。
- 应用卸载:始终处理 app/uninstalled,以清理店铺数据并取消订阅。该 Webhook 充当“下线”信号。
常见事件:
- APP_UNINSTALLED:应用被移除,需要清理。
- ORDERS_CREATE:新订单创建。
- ORDERS_PAID:订单支付状态变为已支付。
- PRODUCTS_UPDATE:产品详情变更。
适用场景
适用于需要与 Shopify 店铺实时同步数据的应用开发,包括监听订单、产品变更,以及处理应用卸载和隐私合规请求。
限制
资料中未提供关于收费、价格或平台支持范围的其他说明。