stripe_service.dart 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import 'package:domain/repository/payment_repository.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:plugin_basic/constants/app_constant.dart';
  4. import 'package:plugin_platform/engine/notify/notify_engine.dart';
  5. import 'package:plugin_platform/engine/toast/toast_engine.dart';
  6. import 'package:plugin_platform/platform_export.dart';
  7. import 'package:shared/utils/log_utils.dart';
  8. import 'package:hooks_riverpod/hooks_riverpod.dart';
  9. import 'package:riverpod_annotation/riverpod_annotation.dart';
  10. import 'package:shared/utils/util.dart';
  11. import 'package:shared/utils/event_bus.dart';
  12. part 'stripe_service.g.dart';
  13. @Riverpod(keepAlive: true)
  14. StripeService stripeService(Ref ref) {
  15. return StripeService(ref.read(paymentRepositoryProvider));
  16. }
  17. class StripeService {
  18. final PaymentRepository _paymentRepository;
  19. StripeService(this._paymentRepository); // 依赖注入 Dio 实例
  20. bool _isInitialized = false;
  21. // 4242 4242 4242 4242 – Visa (无需 3D)
  22. // 4000 0025 0000 3155 – 需要 3D Secure 验证
  23. //初始化 Stripe
  24. Future<void> _ensureInitialized() async {
  25. if (_isInitialized) return;
  26. Stripe.publishableKey = 'pk_test_51RMmxaRpg7SPAcNndAqMUMEOkRFsY5mL0JqJmdunL3vspxrYsGjGARQddaVu3ZQVEy1e1WTF8yalt0cYZCY8sK9R0005VIg5mC';
  27. await Stripe.instance.applySettings();
  28. Log.d("Stripe 初始化完成");
  29. _isInitialized = true;
  30. }
  31. ///执行支付
  32. Future<bool> executePayment({
  33. required String orderId,
  34. }) async {
  35. try {
  36. //尝试初始化 Stripe SDK
  37. await _ensureInitialized();
  38. //从服务端获取 clientSecret
  39. final clientSecret = await _fetchPaymentIntent(orderId);
  40. await _initializePaymentSheet(clientSecret);
  41. await Stripe.instance.presentPaymentSheet();
  42. Log.d("presentPaymentSheet 关闭,用户操作完成 !");
  43. return await _verifyPaymentResult(clientSecret);
  44. } on StripeException catch (e) {
  45. // Stripe SDK 出错
  46. _handleStripeError(e);
  47. return false;
  48. } catch (e) {
  49. // 其他的错误捕获
  50. _handleGenericError(e);
  51. return false;
  52. }
  53. }
  54. ///调用网络请求
  55. Future<String> _fetchPaymentIntent(String orderId) async {
  56. final result = await _paymentRepository.obtainPaymentIntent(orderId: orderId);
  57. if (result.isSuccess) {
  58. if (Utils.isNotEmpty(result.data?.clientSecret)) {
  59. return result.data!.clientSecret!;
  60. } else {
  61. throw Exception("Empty client secret");
  62. }
  63. } else {
  64. ToastEngine.show(result.errorMsg ?? "UnKnow Error");
  65. throw Exception("Failed to get payment intent");
  66. }
  67. }
  68. Future<void> _initializePaymentSheet(String clientSecret) async {
  69. await Stripe.instance.initPaymentSheet(
  70. paymentSheetParameters: SetupPaymentSheetParameters(
  71. customFlow: false,
  72. paymentIntentClientSecret: clientSecret,
  73. merchantDisplayName: 'Your App Demo',
  74. style: ThemeMode.light,
  75. allowsDelayedPaymentMethods: false,
  76. ),
  77. );
  78. }
  79. Future<bool> _verifyPaymentResult(String clientSecret) async {
  80. final paymentIntent = await Stripe.instance.retrievePaymentIntent(clientSecret);
  81. switch (paymentIntent.status) {
  82. case PaymentIntentsStatus.Succeeded:
  83. NotifyEngine.showSuccess('支付成功');
  84. //发送 EventBus 事件
  85. bus.emit(AppConstant.eventStripePaymentSuccess, true);
  86. return true;
  87. case PaymentIntentsStatus.RequiresPaymentMethod:
  88. NotifyEngine.showFailure('支付方式无效');
  89. return false;
  90. case PaymentIntentsStatus.Processing:
  91. return await _handleProcessingPayment(clientSecret);
  92. default:
  93. return false;
  94. }
  95. }
  96. Future<bool> _handleProcessingPayment(String clientSecret) async {
  97. // 处理需要等待的支付状态
  98. await Future.delayed(const Duration(seconds: 2));
  99. final updatedIntent = await Stripe.instance.retrievePaymentIntent(clientSecret);
  100. return updatedIntent.status == PaymentIntentsStatus.Succeeded;
  101. }
  102. void _handleStripeError(StripeException e) {
  103. final errorMessage = e.error.localizedMessage ?? '支付失败';
  104. Log.e('Stripe Error: ${e.error.code} - $errorMessage');
  105. NotifyEngine.showError(errorMessage);
  106. }
  107. void _handleGenericError(dynamic e) {
  108. Log.e('System Error: $e');
  109. NotifyEngine.showError('支付异常:$e');
  110. }
  111. }