stripe_service.dart 4.1 KB

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