Flutter集成Stripe订阅支付:如何捕获支付取消引发的未处理异常?
Stripe PaymentSheet取消支付崩溃问题解决
问题详情
开发订阅制平台时集成了Stripe订阅支付,用户完成卡片支付的流程正常,但点击PaymentSheet的关闭按钮取消支付时会触发错误:
- 当
customFlow设为true时,错误提示:支付选项选择流程已取消 - 当
customFlow设为false时,错误提示:支付已取消
最关键的是,就算加了try-catch语句,这个错误还是会抛出并导致应用崩溃。
现有代码片段
支付Sheet展示逻辑
try { await Stripe.instance.presentPaymentSheet(); } on StripeException catch (e) { print('Error is:---> $e'); String ss = "exception 3 :$e"; } catch (e) { print(e); }
PaymentSheet初始化代码
await Stripe.instance.initPaymentSheet( paymentSheetParameters: SetupPaymentSheetParameters( customFlow: false, //returnURL: 'flutterstripe://redirect', primaryButtonLabel: 'Añadir tarjeta', style: ThemeMode.light, merchantDisplayName: 'BitMasters', customerId: customerId, setupIntentClientSecret: paymentIntentClientSecret, allowsDelayedPaymentMethods: true), );
解决方案
1. 升级flutter_stripe SDK版本
部分旧版本的flutter_stripe存在取消支付时未正确封装异常的bug,导致try-catch无法捕获。直接升级到最新稳定版:
在pubspec.yaml中更新依赖:
dependencies: flutter_stripe: ^最新稳定版号
执行flutter pub get完成更新。
2. 用runZonedGuarded全局捕获异步异常
如果升级后还是崩溃,可能是异步异常没被当前try-catch捕获,用runZonedGuarded包裹支付逻辑,全局兜底:
runZonedGuarded(() async { try { await Stripe.instance.presentPaymentSheet(); } on StripeException catch (e) { print('Stripe异常:---> $e'); // 这里可以加取消支付后的提示,比如给用户弹个"支付已取消"的Toast } catch (e) { print('其他异常: $e'); } }, (error, stackTrace) { print('全局捕获异常: $error'); // 这里处理崩溃前的收尾,比如隐藏加载框 });
3. 配置正确的Return URL
部分平台(尤其是iOS)需要配置URL Scheme才能让PaymentSheet的取消流程正常回调。
- iOS配置:在
Info.plist中添加
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLSchemes</key> <array> <string>flutterstripe</string> </array> </dict> </array>
- Android配置:在
AndroidManifest.xml的主Activity标签内添加
<intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="flutterstripe" /> </intent-filter>
然后取消初始化代码里的returnURL: 'flutterstripe://redirect'注释。
4. 检查后端Setup Intent状态处理
取消支付时,Stripe的Setup Intent会变成canceled状态,确保后端不会因为这个状态抛出未处理的异常,导致前端崩溃。
验证方式
测试取消支付流程,看控制台能不能捕获到取消异常,同时应用不再崩溃。如果还有问题,可以去flutter_stripe的GitHub仓库看Issues,确认是不是已知问题,拿官方解决方案。
内容的提问来源于stack exchange,提问作者PlanasMarc04
相关产品推荐
相关产品推荐

