如何在Node.js中调用Stripe API获取Stripe Dashboard净交易额、单客消费及按区间查销售额
Stripe核心指标API获取方案
以下所有方法返回的数值和Stripe Dashboard展示数据完全对齐:
1. 指定日期区间总销售额查询
推荐使用Balance Transactions API实现,统计精度更高,操作步骤如下:
- 传入
created参数过滤时间范围,值为对应日期的Unix时间戳,用gte匹配开始时间,lte匹配结束时间 - 过滤交易类型
type: 'charge'仅统计成功的支付订单 - 所有返回结果的
amount字段求和后,除以100转换为常规货币单位(Stripe默认返回最小货币单位,如美元对应美分、人民币对应分)
示例代码(Node.js):
const stripe = require('stripe')('你的Stripe API密钥'); // 示例时间范围:2024-01-01 00:00:00 至 2024-01-31 23:59:59 const balanceTransactions = await stripe.balanceTransactions.list({ created: { gte: 1704067200, lte: 1706745599 }, limit: 100, type: 'charge' }); // 计算总销售额 const totalSales = balanceTransactions.data.reduce((sum, txn) => sum + txn.amount, 0) / 100;
数据量大时启用Stripe自动分页功能,避免遗漏交易记录。
2. 净交易额获取
净交易额为总销售额扣除退款、拒付、Stripe手续费后的实际到账金额,直接对Balance Transactions所有交易的net字段求和即可,不需要额外过滤交易类型(退款、拒付的net值为负数,会自动扣减):
const netAmount = balanceTransactions.data.reduce((sum, txn) => sum + txn.net, 0) / 100;
3. 单客消费(客单价)计算
客单价=指定区间总销售额/区间内成功支付的去重客户数,操作步骤如下:
- 调用Payment Intents API,过滤
status: 'succeeded'的成功支付记录 - 提取所有关联的
customer_id并去重,得到实际支付的客户总数 - 总销售额除以客户总数得到客单价
示例代码:
const paymentIntents = await stripe.paymentIntents.list({ created: { gte: 1704067200, lte: 1706745599 }, status: 'succeeded', limit: 100 }); // 去重得到独立支付客户数 const uniqueCustomers = [...new Set(paymentIntents.data.map(pi => pi.customer).filter(Boolean))]; const averageSpendPerCustomer = totalSales / uniqueCustomers.length;
注意事项
- 时间戳的时区需要和Stripe Dashboard设置的时区保持一致,否则统计结果会出现偏差
- 如需获取更多维度的汇总指标,可以直接调用Stripe Reporting API的预定义报表模板,不需要自行聚合交易数据
- 所有涉及金额的字段都需要注意单位转换,避免统计错误
内容的提问来源于stack exchange,提问作者Haseeb Ali
相关产品推荐
相关产品推荐

