使用Stripe创建Charge时返回‘Must provide source or customer’错误排查
问题分析与解决
你遇到的这个错误,本质是你指定的customer对象没有关联任何可用的支付方式——哪怕你传了customer参数,Stripe也找不到扣款的来源,所以会提示需要source或customer(这里的customer特指已绑定支付方式的客户)。
解决步骤
- 先确认
cus_NDylKcn97g7OD4这个客户是否存在,并且已添加支付方式(如信用卡、借记卡)。你可以登录Stripe后台,在客户列表里找到该ID对应的客户,查看其支付方式列表。 - 如果客户没有支付方式,需要先完成绑定:
- 可以通过Stripe Dashboard手动添加测试支付方式(比如用4242开头的测试卡号);
- 或者在代码中调用Stripe API为客户关联支付方式,比如用
paymentMethods.attach接口把已创建的支付方式绑定到客户,之后再创建Charge。
- 若不想预先给客户绑定支付方式,也可以在创建Charge时直接指定
payment_method参数(推荐)或旧版source参数,替代customer参数来指定扣款来源。
代码示例
直接指定支付方式创建Charge
(async () => { try { const charge = await stripe.charges.create({ amount: 2000, currency: "usd", payment_method: "pm_123456789", // 替换为实际的支付方式ID confirm: true, // 需启用支付确认 }); console.log("Charge created"); } catch (error) { console.log(error); } })();
验证客户支付方式后创建Charge
(async () => { try { // 先校验客户是否有默认支付方式 const customer = await stripe.customers.retrieve("cus_NDylKcn97g7OD4"); if (!customer.invoice_settings.default_payment_method) { throw new Error("客户未设置默认支付方式"); } const charge = await stripe.charges.create({ amount: 2000, currency: "usd", customer: "cus_NDylKcn97g7OD4", }); console.log("Charge created"); } catch (error) { console.log(error); } })();
另外提醒:Stripe目前更推荐使用Payment Intents API处理支付流程,Charges API属于旧版,新集成项目建议迁移至Payment Intents以避免兼容性问题。
内容的提问来源于stack exchange,提问作者Gwhyyy
相关产品推荐
相关产品推荐

