Node.js调用Stripe接口查询用户订阅状态返回空数据及读取status报错咨询
问题原因定位
首先你遇到的Cannot read property 'status' of undefined报错是因为查询订阅返回的data是空数组,直接取下标0的属性必然触发异常。而传customer参数返回空数组的常见原因及解决方案如下:
解决方案
1. 优先校验customerID是否正确
这是90%以上同类问题的诱因:
- 先打印你代码中获取到的
customerID,和全量订阅结果里的customer字段值(你给出的示例中为cus_JEQIfxhiRu7qJh)做比对:- 如果值不一致:说明你通过邮箱查询客户的步骤出错了
- Stripe的邮箱查询是大小写敏感的,你查询用的
contact@Inderatech.com首字母大写,如果客户实际绑定的是全小写contact@inderatech.com就会匹配到错误的客户,甚至匹配不到。 - 同邮箱可能存在多个客户账号,你直接取
data[0]可能拿到的是没有订阅的无效客户账号,需要先判断customers.data长度,再遍历匹配正确的客户。
- Stripe的邮箱查询是大小写敏感的,你查询用的
- 如果值一致:参考下一步更换查询接口
- 如果值不一致:说明你通过邮箱查询客户的步骤出错了
2. 更换指定客户订阅查询接口
不要用全局stripe.subscriptions.list加customer参数过滤,直接调用Stripe官方提供的指定客户订阅查询接口,稳定性更高:stripe.customers.listSubscriptions(你的customerID)
3. 增加错误边界处理
避免空数组取值报错,所有列表取值前先判断长度。
修正后的代码示例
const customers = await stripe.customers.list({ // 建议统一转小写查询,避免大小写匹配问题 email: 'contact@Inderatech.com'.toLowerCase(), limit: 100 // 避免返回数据不全 }); // 先判断客户列表是否为空 if (customers.data.length === 0) { console.log('未找到对应邮箱的客户'); return; } const customerID = customers.data[0].id; console.log('查询到的客户ID:', customerID); // 直接查询指定客户的订阅 const subscriptions = await stripe.customers.listSubscriptions(customerID); console.log('订阅查询结果:', subscriptions); // 先判断订阅列表是否为空再取属性 if (subscriptions.data.length > 0) { console.log('订阅状态:', subscriptions.data[0].status); } else { console.log('该客户无有效订阅'); }
内容的提问来源于stack exchange,提问作者developerg1000
相关产品推荐
相关产品推荐

