stripe_service.dart 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import 'package:flutter/material.dart';
  2. import 'package:plugin_platform/engine/notify/notify_engine.dart';
  3. import 'package:plugin_platform/platform_export.dart';
  4. import 'package:shared/utils/log_utils.dart';
  5. //定义一个top-level(全局)变量,页面引入该文件后可以直接使用
  6. var stripeService = StripeService();
  7. class StripeService {
  8. StripeService._internal();
  9. //保存单例
  10. static final StripeService _singleton = StripeService._internal();
  11. //工厂构造函数
  12. factory StripeService() => _singleton;
  13. bool _isInitialized = false;
  14. //初始化 Stripe
  15. Future<void> _ensureInitialized() async {
  16. if (_isInitialized) return;
  17. Stripe.publishableKey = 'pk_test_51RMmxaRpg7SPAcNndAqMUMEOkRFsY5mL0JqJmdunL3vspxrYsGjGARQddaVu3ZQVEy1e1WTF8yalt0cYZCY8sK9R0005VIg5mC';
  18. await Stripe.instance.applySettings();
  19. Log.d("Stripe 初始化完成");
  20. _isInitialized = true;
  21. }
  22. ///执行支付
  23. Future<bool> executePayment({
  24. required String orderId,
  25. }) async {
  26. try {
  27. await _ensureInitialized();
  28. // 实际开发中应从服务端获取 clientSecret
  29. final clientSecret = await _fetchPaymentIntent(orderId);
  30. await _initializePaymentSheet(clientSecret);
  31. await Stripe.instance.presentPaymentSheet();
  32. Log.d("presentPaymentSheet 关闭,用户操作完成 !");
  33. return await _verifyPaymentResult(clientSecret);
  34. } on StripeException catch (e) {
  35. _handleStripeError(e);
  36. return false;
  37. } catch (e) {
  38. _handleGenericError(e);
  39. return false;
  40. }
  41. }
  42. ///调用网络请求
  43. Future<String> _fetchPaymentIntent(String orderId) async {
  44. // 实际开发中调用后端接口获取
  45. return "pi_3ROERGRpg7SPAcNn0sPDWCQI_secret_EZPly9t0IbKqaKA2CQwkUNIjd";
  46. }
  47. Future<void> _initializePaymentSheet(String clientSecret) async {
  48. await Stripe.instance.initPaymentSheet(
  49. paymentSheetParameters: SetupPaymentSheetParameters(
  50. customFlow: false,
  51. paymentIntentClientSecret: clientSecret,
  52. merchantDisplayName: 'Your App Demo',
  53. style: ThemeMode.light,
  54. allowsDelayedPaymentMethods: false,
  55. ),
  56. );
  57. }
  58. Future<bool> _verifyPaymentResult(String clientSecret) async {
  59. final paymentIntent = await Stripe.instance.retrievePaymentIntent(clientSecret);
  60. switch (paymentIntent.status) {
  61. case PaymentIntentsStatus.Succeeded:
  62. NotifyEngine.showSuccess('支付成功');
  63. return true;
  64. case PaymentIntentsStatus.RequiresPaymentMethod:
  65. NotifyEngine.showFailure('支付方式无效');
  66. return false;
  67. case PaymentIntentsStatus.Processing:
  68. return await _handleProcessingPayment(clientSecret);
  69. default:
  70. return false;
  71. }
  72. }
  73. Future<bool> _handleProcessingPayment(String clientSecret) async {
  74. // 处理需要等待的支付状态
  75. await Future.delayed(const Duration(seconds: 2));
  76. final updatedIntent = await Stripe.instance.retrievePaymentIntent(clientSecret);
  77. return updatedIntent.status == PaymentIntentsStatus.Succeeded;
  78. }
  79. void _handleStripeError(StripeException e) {
  80. final errorMessage = e.error.localizedMessage ?? '支付失败';
  81. Log.e('Stripe Error: ${e.error.code} - $errorMessage');
  82. NotifyEngine.showError(errorMessage);
  83. }
  84. void _handleGenericError(dynamic e) {
  85. Log.e('System Error: $e');
  86. NotifyEngine.showError('支付系统异常');
  87. }
  88. }