/// Stripe 流程封装(flutter_stripe 11.x) /// /// 覆盖三种入口: /// 1. PaymentSheet(标准卡支付) /// 2. Apple Pay(confirmPlatformPayPaymentIntent) /// 3. Google Pay(confirmPlatformPayPaymentIntent) library; import 'package:flutter_stripe/flutter_stripe.dart'; import '../../models/payment.dart'; /// Stripe 封装:初始化 + PaymentSheet + Apple/Google Pay class StripeFlow { StripeFlow._(); static final StripeFlow instance = StripeFlow._(); /// 设置发布密钥(App 启动时调用;真实接入以后端下发为准) void init(String publishableKey) { Stripe.publishableKey = publishableKey; } /// 是否 Mock 模式(后端下发 pk_test_mock 时,无法弹原生面板) static bool isMock(StripePaymentCreatedResponse created) => created.publishableKey.startsWith('pk_test_mock'); /// 初始化并展示 PaymentSheet /// [created] 后端 createStripePayment 响应 Future presentPaymentSheet(StripePaymentCreatedResponse created) async { // 真实密钥由后端下发时动态更新 if (created.publishableKey.isNotEmpty) { Stripe.publishableKey = created.publishableKey; } await Stripe.instance.initPaymentSheet( paymentSheetParameters: SetupPaymentSheetParameters( merchantDisplayName: 'flutter_paydemo 演示商店', customerId: created.customer, paymentIntentClientSecret: created.paymentIntent, customerEphemeralKeySecret: created.ephemeralKey, // Apple / Google Pay 开关见对应方法 applePay: const PaymentSheetApplePay(merchantCountryCode: 'US'), googlePay: const PaymentSheetGooglePay( merchantCountryCode: 'US', testEnv: true, ), ), ); await Stripe.instance.presentPaymentSheet(); } /// 探测 Apple Pay 是否可用(iOS/Safari) Future isApplePaySupported() { return Stripe.instance.isPlatformPaySupported(); } /// 探测 Google Pay 是否可用(Android/Chrome) Future isGooglePaySupported() { return Stripe.instance.isPlatformPaySupported( googlePay: const IsGooglePaySupportedParams(testEnv: true), ); } /// 确认 Apple Pay 支付 Future confirmApplePay( StripePaymentCreatedResponse created, String productName, int amountUsdCents, ) async { await Stripe.instance.confirmPlatformPayPaymentIntent( clientSecret: created.paymentIntent, confirmParams: PlatformPayConfirmParams.applePay( applePay: ApplePayParams( cartItems: [ ApplePayCartSummaryItem.immediate( label: productName, amount: (amountUsdCents / 100).toStringAsFixed(2), ), ], merchantCountryCode: 'US', currencyCode: 'USD', ), ), ); } /// 确认 Google Pay 支付 Future confirmGooglePay( StripePaymentCreatedResponse created, String productName, int amountUsdCents, ) async { await Stripe.instance.confirmPlatformPayPaymentIntent( clientSecret: created.paymentIntent, confirmParams: PlatformPayConfirmParams.googlePay( googlePay: GooglePayParams( testEnv: true, merchantName: productName, merchantCountryCode: 'US', currencyCode: 'USD', ), ), ); } }