Flutter Stripe iOS端崩溃:NSNull转NSDictionary失败求助
iOS上flutter_stripe 9.4.0崩溃:NSNull转NSDictionary失败的解决办法
问题原因
崩溃的核心原因是SetupPaymentSheetParameters中传入的customerId或customerEphemeralKeySecret为null,iOS平台的Stripe SDK无法将NSNull类型转换为预期的类型,进而触发崩溃。
你的createPaymentIntent方法仅调用Stripe API创建了基础的Payment Intent,并未关联Stripe Customer资源,因此返回的paymentIntentData中不存在customer和ephemeralKey字段,直接强制取值会得到null——Android平台的Stripe SDK可能兼容处理了这种情况,但iOS平台会触发类型转换错误。
解决办法
方案1:无需关联Stripe Customer(快速修复)
如果业务不需要绑定Stripe Customer,直接移除customerId和customerEphemeralKeySecret参数即可,Payment Sheet仅通过Payment Intent的client_secret就能正常工作:
await Stripe.instance.initPaymentSheet( paymentSheetParameters: SetupPaymentSheetParameters( customFlow: false, paymentIntentClientSecret: paymentIntentData!['client_secret'], merchantDisplayName: 'Body and mind', googlePay: null, applePay: null, style: ThemeMode.system, // 移除以下两个无效参数 // customerId: paymentIntentData!['customer'], // customerEphemeralKeySecret: paymentIntentData!['ephemeralKey'], ), );
方案2:关联Stripe Customer(需后端配合)
如果业务需要绑定Stripe Customer,需补充以下流程:
- 后端创建/获取Stripe Customer:调用Stripe API创建Customer(或根据用户ID查询已有Customer)。
- 后端生成Ephemeral Key:基于Customer ID生成短期有效的Ephemeral Key,用于前端访问Customer资源。
- 后端创建Payment Intent时关联Customer:调用Payment Intents API时,在请求体中加入
customer: "cus_xxxxxx"参数。 - 前端接收完整参数:将后端返回的
customerId、ephemeralKey和Payment Intent的client_secret一起传入SetupPaymentSheetParameters。
额外检查项
- 确保
paymentIntentData中的client_secret不为空,可在调用initPaymentSheet前增加判断:if (paymentIntentData == null || paymentIntentData!['client_secret'] == null) { print("Payment Intent 获取失败"); return; } - 确认iOS项目配置正确:
Info.plist中已添加Apple Pay所需权限(若使用),且执行过pod install同步最新依赖。
内容的提问来源于stack exchange,提问作者Muhammad Zain
相关产品推荐
相关产品推荐

