Stripe React Native订阅创建报错:客户无关联支付方式
问题分析
当创建无试用的Stripe订阅时,Stripe要求客户必须绑定支付方式或设置默认支付方式——因为无试用订阅会立即发起扣费。而开启trial_period_days: 3时,订阅处于试用状态,无需立即扣费,所以即使没有支付方式也能创建成功。
你当前的代码逻辑存在问题:创建订阅时未配置支付相关参数,导致直接触发报错,根本走不到后续更新订阅的步骤。
解决方案
要让新客户通过Payment Sheet使用所在国家、对应OS平台支持的所有支付方式,需要在创建订阅时就配置关键参数,而非事后更新。核心是让Stripe生成待完成的支付意向(Setup Intent),引导前端收集支付方式。
修改后的完整代码:
const stripe = require('stripe')(stripeSecretKey); const express = require('express'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.json()); app.get('/', (req, res) => { res.send('Test'); }); app.post('/payment-sheet-subscription', async (req, res) => { const {email = `test${Math.floor(Math.random() * 9999) + 1}@domain.com`} = req.body; const customer = await stripe.customers.create({email}); const ephemeralKey = await stripe.ephemeralKeys.create( {customer: customer.id}, {apiVersion: '2020-08-27'}, ); const PRICE_ID = 'price_1NQ4EnSBro6pGrG8ZYfdBX5x'; // 创建订阅时直接配置支付规则,生成待完成的支付意向 const subscription = await stripe.subscriptions.create({ customer: customer.id, items: [{price: PRICE_ID}], // 允许订阅处于待支付状态,生成Setup Intent用于前端收集支付方式 payment_behavior: 'default_incomplete', payment_settings: { // 留空不指定具体支付方式,Stripe会自动根据地区/平台展示所有可用选项 payment_method_types: [], }, // 直接展开返回pending_setup_intent,避免额外API查询 expand: ['pending_setup_intent'], }); if (subscription.pending_setup_intent) { return res.json({ setupIntent: subscription.pending_setup_intent.client_secret, ephemeralKey: ephemeralKey.secret, customer: customer.id, }); } else { throw new Error('Failed to generate pending setup intent for subscription'); } });
关键说明
payment_behavior: 'default_incomplete'是核心:无试用场景下必须设置该参数,否则Stripe会要求立即扣费,而新客户无支付方式就会触发报错- 不指定
payment_method_types或设为空数组,Stripe会自动根据客户所在地区(通过Payment Sheet的IP检测)和操作系统(iOS/Android)展示所有支持的支付方式,比如Apple Pay、Google Pay、本地银行转账等 - 通过
expand: ['pending_setup_intent']直接获取支付意向的密钥,减少一次API调用,提升接口效率
内容的提问来源于stack exchange,提问作者Piyush Chatterjee
相关产品推荐
相关产品推荐

