Stripe阶梯价格更新无Webhook触发问题求助
问题描述
配置Stripe Webhook时遇到以下问题:阶梯价格(tiered prices)更新时不会触发Webhook,但普通固定价格(flat rate)更新时Webhook可正常触发,其他Webhook功能均正常。查阅Stripe官方文档未找到相关明确说明,想问Stripe是否不为阶梯价格的更新事件发送Webhook?
相关代码
stripeWebhookRoute.mjs
import express from "express"; import bodyParser from "body-parser" import stripePackage from 'stripe' import { handleStripeWebhooks } from "../services/stripeServices/handleWebhooks.mjs"; const stripe = stripePackage(process.env.STRIPE_API_KEY); const router = express.Router(); router.post('/webhook', bodyParser.raw({ type: 'application/json' }), async (req, res) => { let event; const sig = req.headers['stripe-signature']; const webHookSecret = process.env.STRIPE_WEBHOOK_KEY; try { if (webHookSecret) { event = stripe.webhooks.constructEvent(req.body, sig, webHookSecret); } } catch (error) { console.error('⚠️ Webhook signature verification failed.', error.message); return res.status(400).send(`Webhook Error: ${error.message}`); } // Acknowledge receipt of the event right away res.status(200).json({ received: true }); handleStripeWebhooks(event); }) export default router;
handleWebhook.mjs
import { handlePriceUpdate } from "./pricing/handlePricingUpdate.mjs"; /** * @param {*} event a stripe event * Receives a stripe webhook event and triggers execution logic. */ export const handleStripeWebhooks = async(event) => { switch (event.type) { case 'price.updated': console.log("Price updated"); handlePriceUpdate(event); break; default: console.log(`Unhandled event type ${event.type}.`); } }
解答
Stripe的price.updated Webhook事件会对所有价格类型触发,包括阶梯价格,不存在只针对固定价格发送事件的情况。你遇到的问题大概率是以下原因之一:
阶梯价格的操作未实际修改价格对象
如果你修改阶梯价格后,新的配置和原配置完全一致(比如tiers的金额、区间没有变化),Stripe不会生成price.updated事件。请确认你的更新操作确实修改了价格对象的字段。Stripe事件日志排查
登录Stripe Dashboard,进入【Developers】→【Events】,搜索对应阶梯价格的price.updated事件,查看:- 该事件是否存在;
- 事件是否成功发送到你的Webhook端点;
- 有没有发送失败的记录(比如超时、返回错误码)。
异步处理的潜在问题
你的代码中,在返回200响应后才调用handleStripeWebhooks,如果handlePriceUpdate内部出现未捕获的异常,可能导致日志无法输出,但不会影响Webhook的触发。建议在handlePriceUpdate中添加错误捕获,避免异常被吞掉:// 示例:在handlePriceUpdate中添加错误处理 export const handlePriceUpdate = async (event) => { try { // 你的业务逻辑 } catch (err) { console.error('处理价格更新失败:', err); } }Webhook端点订阅确认
虽然固定价格能触发事件,但仍建议确认Webhook端点是否确实订阅了price.updated事件(在Stripe Dashboard的【Webhooks】→【端点详情】中查看已订阅的事件列表)。
内容的提问来源于stack exchange,提问作者rhys

