如何通过PaymentIntent ID获取Stripe中支付失败的最新时间戳?
获取PaymentIntent的最新支付失败时间戳
你需要通过关联的Charge记录来获取支付失败的时间戳,因为paymentIntent.last_error只包含错误的类型、描述等信息,本身并不附带时间戳。具体实现方式如下:
解决方案代码
调用paymentIntents.retrieve时,需要**展开charges.data**来获取所有关联的支付尝试记录,然后筛选出失败的Charge,取最新的那条的created字段(该字段是Unix时间戳,单位为秒):
const paymentIntent = await stripe.paymentIntents.retrieve(paymentIntentId, { expand: ['charges.data'] // 必须展开charges才能拿到完整的支付尝试数据 }); // 筛选出所有失败的支付记录,并按创建时间倒序排序 const failedCharges = paymentIntent.charges.data .filter(charge => charge.status === 'failed') .sort((a, b) => b.created - a.created); // 获取最新的失败时间戳 let latestFailureTimestamp = null; if (failedCharges.length > 0) { latestFailureTimestamp = failedCharges[0].created; // 如需转成可读日期:new Date(latestFailureTimestamp * 1000) }
说明
每次支付尝试都会生成一条Charge记录,失败的Charge会标记status: 'failed',它的created字段就是该次支付失败发生的时间戳。通过筛选并排序这些失败记录,就能拿到最新的失败时间。
内容的提问来源于stack exchange,提问作者user24602006
相关产品推荐
相关产品推荐

