import 'package:flutter/material.dart'; import 'package:plugin_platform/engine/notify/notify_engine.dart'; import 'package:plugin_platform/platform_export.dart'; import 'package:shared/utils/log_utils.dart'; //定义一个top-level(全局)变量,页面引入该文件后可以直接使用 var stripeService = StripeService(); class StripeService { StripeService._internal(); //保存单例 static final StripeService _singleton = StripeService._internal(); //工厂构造函数 factory StripeService() => _singleton; bool _isInitialized = false; //初始化 Stripe Future _ensureInitialized() async { if (_isInitialized) return; Stripe.publishableKey = 'pk_test_51RMmxaRpg7SPAcNndAqMUMEOkRFsY5mL0JqJmdunL3vspxrYsGjGARQddaVu3ZQVEy1e1WTF8yalt0cYZCY8sK9R0005VIg5mC'; await Stripe.instance.applySettings(); Log.d("Stripe 初始化完成"); _isInitialized = true; } ///执行支付 Future executePayment({ required String orderId, }) async { try { await _ensureInitialized(); // 实际开发中应从服务端获取 clientSecret final clientSecret = await _fetchPaymentIntent(orderId); await _initializePaymentSheet(clientSecret); await Stripe.instance.presentPaymentSheet(); Log.d("presentPaymentSheet 关闭,用户操作完成 !"); return await _verifyPaymentResult(clientSecret); } on StripeException catch (e) { _handleStripeError(e); return false; } catch (e) { _handleGenericError(e); return false; } } ///调用网络请求 Future _fetchPaymentIntent(String orderId) async { // 实际开发中调用后端接口获取 return "pi_3ROERGRpg7SPAcNn0sPDWCQI_secret_EZPly9t0IbKqaKA2CQwkUNIjd"; } Future _initializePaymentSheet(String clientSecret) async { await Stripe.instance.initPaymentSheet( paymentSheetParameters: SetupPaymentSheetParameters( customFlow: false, paymentIntentClientSecret: clientSecret, merchantDisplayName: 'Your App Demo', style: ThemeMode.light, allowsDelayedPaymentMethods: false, ), ); } Future _verifyPaymentResult(String clientSecret) async { final paymentIntent = await Stripe.instance.retrievePaymentIntent(clientSecret); switch (paymentIntent.status) { case PaymentIntentsStatus.Succeeded: NotifyEngine.showSuccess('支付成功'); return true; case PaymentIntentsStatus.RequiresPaymentMethod: NotifyEngine.showFailure('支付方式无效'); return false; case PaymentIntentsStatus.Processing: return await _handleProcessingPayment(clientSecret); default: return false; } } Future _handleProcessingPayment(String clientSecret) async { // 处理需要等待的支付状态 await Future.delayed(const Duration(seconds: 2)); final updatedIntent = await Stripe.instance.retrievePaymentIntent(clientSecret); return updatedIntent.status == PaymentIntentsStatus.Succeeded; } void _handleStripeError(StripeException e) { final errorMessage = e.error.localizedMessage ?? '支付失败'; Log.e('Stripe Error: ${e.error.code} - $errorMessage'); NotifyEngine.showError(errorMessage); } void _handleGenericError(dynamic e) { Log.e('System Error: $e'); NotifyEngine.showError('支付系统异常'); } }