调用stripe.customers.listPaymentMethods报非函数错误如何解决
报错根因
- 本地安装的Stripe Node.js SDK版本过低:
stripe.customers.listPaymentMethods方法在stripe-node v8.138.0及以上版本才提供,版本低于该值时调用就会抛出「不是函数」的类型错误。 - 代码存在语法错误:你贴出的实现中,异步逻辑外层缺失
try关键字,直接拼接catch块,即便API方法可用也会触发语法报错。 - 业务逻辑存在硬编码问题:代码中写死了测试客户ID
cus_M3nQBIvz9qykuG,没有使用请求体传入的customerId参数,正式运行会返回错误客户的支付数据,且当前逻辑只返回第一张卡的数据,不符合获取全部支付方式的需求。
修复方案
- 先升级服务端依赖的Stripe SDK到最新版本,在项目服务端目录执行命令:
npm install stripe@latest
如果使用yarn作为包管理工具,执行:
yarn add stripe@latest
- 修正代码语法和逻辑问题,补全try块、替换硬编码ID、调整返回值为全量支付方式:
app.post("/savedCards", cors(), async (req, res) => { try { const { customerId } = req.body; const paymentMethods = await stripe.customers.listPaymentMethods( customerId, { type: 'card' } ); console.log(paymentMethods); // 返回该客户名下所有卡类型支付方式 res.status(200).send(paymentMethods.data); } catch (err) { console.log(err); res.status(500).json({ message: "Internal server error" }); } });
如果暂时不方便升级SDK版本,可以直接用新旧版本全兼容的API写法,效果完全一致:
const paymentMethods = await stripe.paymentMethods.list({ customer: customerId, type: 'card' });
内容的提问来源于stack exchange,提问作者Pramodh
相关产品推荐
相关产品推荐

