Stripe Webhook如何获取用户购买的产品ID/名称等标识信息?
通过Stripe Webhook获取购买产品信息的方法
为什么payment_intent.succeeded里没有直接的产品信息?
Stripe的PaymentIntent核心职责是处理支付状态、金额流转、资金确认,属于支付层对象。产品、订单这类业务信息属于交易的业务载体(比如Checkout Session、Invoice),所以Stripe将这些拆分到关联对象中,保持职责单一,避免对象结构臃肿。
具体获取方法
根据你创建支付的方式,分三种场景处理:
1. 支付来自Checkout Session
payment_intent.succeeded事件的payment_intent对象里会包含checkout_session字段(对应Checkout Session的ID)。通过这个ID调用Stripe API获取Session详情,就能拿到line_items数组,里面包含每个商品的价格ID和关联的产品ID:
// 处理Webhook事件示例(Node.js) const stripe = require('stripe')('你的API密钥'); if (event.type === 'payment_intent.succeeded') { const paymentIntent = event.data.object; if (paymentIntent.checkout_session) { // 获取Checkout Session详情 const checkoutSession = await stripe.checkout.sessions.retrieve(paymentIntent.checkout_session); // 遍历商品项 for (const item of checkoutSession.line_items.data) { const productId = item.price.product; // 获取产品详情 const product = await stripe.products.retrieve(productId); console.log('产品ID:', productId); console.log('产品名称:', product.name); // 其他产品信息:product.description、product.images等 } } }
2. 支付来自Invoice
如果是通过Invoice发起的支付,payment_intent对象里会有invoice字段(对应Invoice的ID)。调用API获取Invoice详情后,同样从line_items中提取产品信息:
if (paymentIntent.invoice) { const invoice = await stripe.invoices.retrieve(paymentIntent.invoice); for (const item of invoice.line_items.data) { const productId = item.price.product; const product = await stripe.products.retrieve(productId); console.log('产品ID:', productId); console.log('产品名称:', product.name); } }
3. 手动创建Payment Intent的场景
如果是你手动创建的PaymentIntent,可以在创建时将产品ID、名称等信息存入metadata字段,这样Webhook事件里就能直接读取:
// 创建Payment Intent时存入metadata const paymentIntent = await stripe.paymentIntents.create({ amount: 1000, currency: 'usd', metadata: { product_id: 'prod_XXXXXXX', product_name: '示例产品' }, }); // Webhook中读取 if (paymentIntent.metadata.product_id) { console.log('产品ID:', paymentIntent.metadata.product_id); console.log('产品名称:', paymentIntent.metadata.product_name); // 也可以用product_id调用API获取更详细信息 }
优化建议
- 若想减少API调用次数,可在创建Checkout Session/Invoice时,将必要的产品信息提前存入对应对象的
metadata中,后续直接从Webhook事件的关联对象里读取。 - 确保你的API密钥拥有
read_checkout_sessions、read_invoices、read_products的权限。
内容的提问来源于stack exchange,提问作者Руслан Миров
相关产品推荐
相关产品推荐

