如何在Flutter中通过Stripe实现Apple Pay?已解决
Flutter + Stripe 实现Apple Pay完整支付流程
问题背景
已完成Flutter中Apple Pay按钮的布局与点击事件框架,按钮可正常显示,但不清楚后续支付流程的具体实现步骤。
已实现的初始代码
Apple Pay按钮布局
if (_selectedMethodIndex == 4) BottomAppBar( child: SizedBox( width: double.infinity, child: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: PlatformPayButton( onPressed: () { print('apple pay loading'); _handleApplePayPress(context); }, ), ), ), ), ),
按钮点击事件框架
void _handleApplePayPress(BuildContext context) async{ print('pay pressed'); try { if (await Stripe.instance.isPlatformPaySupported()) { print('apple pay is supported'); bool paymentSuccessful = await _payWithApplePay() ?? false; if (paymentSuccessful) { // 支付成功后的逻辑 print('payment successful'); } else { // 支付失败后的逻辑 print('payment failed'); } } else { ScaffoldMessenger.of(context).showSnackBar(const SnackBar( content: Text('Apple pay is not supported in this device'), )); } } catch (exception) { print(exception.toString()); } } Future<bool?> _payWithApplePay() async{ print("controller methods"); }
完整解决方案代码
以下是实现完整支付流程的核心代码,包含后端交互、Stripe支付确认及结果处理:
void _handleApplePayPress( BuildContext context, List<CartItem>? cartItem, String orderType, double orderTotalPrice, ) async { print('pay pressed'); try { // 1. 调用后端API创建订单,获取支付意图的clientSecret final SecretResponse response = await CustomerOrderRepository().submitOrder( cartItem: cartItem!, orderType: orderType, totalAmount: orderTotalPrice, publicVouchers: publicVouchers ?? [], privateVouchers: privateVouchers ?? [], ); if (response.clientSecret != null) { try { // 2. 通过Stripe唤起Apple Pay并确认支付 final paymentIntentResult = await Stripe.instance.confirmPlatformPayPaymentIntent( clientSecret: response.clientSecret!, confirmParams: PlatformPayConfirmParams.applePay( applePay: ApplePayParams( merchantCountryCode: 'AU', // 商家所在国家码 currencyCode: 'AUD', // 货币代码 cartItems: [ ApplePayCartSummaryItem.immediate( label: "Total Amount", amount: '${StorageManager().finalAmount}') ], ), ), ); // 3. 根据支付结果处理后续逻辑 if (paymentIntentResult.status == PaymentIntentsStatus.Succeeded) { // 支付成功,跳转到订单成功页面 _navigateToNextScreen( orderTotalPrice, response.customerOrderDTO?.orderNumber); } else { throw Exception( 'Payment failed with status: ${paymentIntentResult.status}'); } } catch (err) { // 处理支付过程中的错误 print('Error: $err'); String errorMessage = 'Error during payment'; if (err is StripeException) { errorMessage = err.error.localizedMessage!; } CommonMethods.showFailreToast(errorMessage); } } } catch (error) { // 处理订单创建等其他错误 print('Error: $error'); CommonMethods.showFailreToast('Something Went Wrong - $error'); } }
流程说明
- 获取支付意图ClientSecret:先调用后端接口创建订单,后端通过Stripe API生成Payment Intent并返回clientSecret,这是支付流程的核心凭证。
- 唤起Apple Pay并确认支付:使用
Stripe.instance.confirmPlatformPayPaymentIntent方法传入clientSecret和Apple Pay配置参数,系统会自动唤起Apple Pay支付界面。 - 支付结果处理:根据
paymentIntentResult.status判断支付是否成功,成功则跳转至订单完成页面,失败则展示错误提示。
内容的提问来源于stack exchange,提问作者D-Sibu
相关产品推荐
相关产品推荐

