如何在Stripe中统计某一产品的所有支付金额总和?
获取Stripe中某一产品的所有支付金额总和
你用stripe.prices.list({ product: productId })只能拿到该产品对应的定价方案,不是实际产生的支付记录,自然算不出总支付金额。要统计实际支付总和,得从支付记录(Payment Intents或Charges)入手,关联到对应的产品,具体实现如下:
实现思路
支付记录不会直接关联产品,需要通过Line Item(订单项)关联到Price(定价),再关联到Product(产品)。因此需要查询支付记录并展开关联的产品信息,筛选目标产品后累加金额。
代码实现
方式一:通过Payment Intents查询(推荐,适用于大多数场景)
let totalAmount = 0; let hasMoreRecords = true; let lastRecordId = null; // 循环处理分页,直到获取所有记录 while (hasMoreRecords) { const paymentIntents = await stripe.paymentIntents.list({ limit: 100, // 单次查询最大数量,Stripe上限为100 starting_after: lastRecordId, expand: ['data.lines.data.price.product'] // 展开关联的产品信息 }); // 遍历成功的支付记录,累加目标产品的金额 paymentIntents.data.forEach(intent => { if (intent.status === 'succeeded') { intent.lines.data.forEach(line => { if (line.price.product.id === productId) { totalAmount += line.amount; // 金额为最小货币单位(如分) } }); } }); hasMoreRecords = paymentIntents.has_more; lastRecordId = paymentIntents.data.at(-1)?.id; } // 转换为常规货币单位(如人民币/美元,除以100) totalAmount = totalAmount / 100; console.log(`该产品总支付金额:${totalAmount}`);
方式二:通过Charges查询(适用于订阅/发票场景)
如果支付是通过订阅或发票生成的,可以用Charges关联到Invoice再筛选产品:
let totalAmount = 0; let hasMoreRecords = true; let lastRecordId = null; while (hasMoreRecords) { const charges = await stripe.charges.list({ limit: 100, starting_after: lastRecordId, expand: ['data.invoice.lines.data.price.product'] }); charges.data.forEach(charge => { if (charge.status === 'succeeded' && charge.invoice) { charge.invoice.lines.data.forEach(line => { if (line.price.product.id === productId) { totalAmount += line.amount; } }); } }); hasMoreRecords = charges.has_more; lastRecordId = charges.data.at(-1)?.id; } totalAmount = totalAmount / 100; console.log(`该产品总支付金额:${totalAmount}`);
注意事项
- 金额单位转换:Stripe返回的金额是最小货币单位(如人民币分、美元分),必须除以100得到实际金额
- 分页处理:Stripe列表接口单次最多返回100条数据,必须循环处理分页直到
has_more为false - 筛选成功支付:只统计
status为succeeded的记录,避免包含失败、待处理的支付 - 扩展字段:必须使用
expand参数获取关联的产品信息,否则无法直接判断支付对应的产品
内容的提问来源于stack exchange,提问作者Zahar
相关产品推荐
相关产品推荐

