wechat_flow.dart 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /// 微信支付流程封装(fluwx 5.3.1)
  2. library;
  3. import 'package:fluwx/fluwx.dart' as fluwx;
  4. import '../../constants.dart';
  5. import '../../models/payment.dart';
  6. /// fluwx 回调结果码
  7. class WechatPayResultCode {
  8. WechatPayResultCode._();
  9. static const int success = 0; // 支付成功
  10. static const int failed = -1; // 支付失败
  11. static const int cancelled = -2; // 用户取消
  12. }
  13. /// 微信支付封装:注册 + 拉起支付 + 结果回调
  14. class WechatFlow {
  15. WechatFlow._() : _fluwx = fluwx.Fluwx();
  16. static final WechatFlow _instance = WechatFlow._();
  17. /// 获取单例
  18. static WechatFlow get instance => _instance;
  19. final fluwx.Fluwx _fluwx;
  20. /// 支付结果回调(由 pay_service 注册,errCode: 0 成功)
  21. void Function(int errCode, String errStr)? onPayResult;
  22. /// 注册微信 SDK(App 启动时调用一次;Web 为空实现,安全跳过)
  23. Future<bool> init() async {
  24. return _fluwx.registerApi(
  25. appId: kWechatAppId,
  26. universalLink: kWechatUniversalLink,
  27. doOnAndroid: true,
  28. doOnIOS: true,
  29. );
  30. }
  31. /// 是否已安装微信 App
  32. Future<bool> isInstalled() async {
  33. try {
  34. return await _fluwx.isWeChatInstalled;
  35. } catch (_) {
  36. return false;
  37. }
  38. }
  39. /// 注册支付结果订阅(App 启动时调用一次)
  40. void subscribe() {
  41. _fluwx.addSubscriber((response) {
  42. if (response is fluwx.WeChatPaymentResponse) {
  43. onPayResult?.call(response.errCode ?? 0, response.errStr ?? '');
  44. }
  45. });
  46. }
  47. /// 拉起微信支付
  48. /// [created] 来自后端统一下单响应
  49. Future<bool> payWith(
  50. WechatPaymentCreatedResponse created,
  51. ) {
  52. return _fluwx.pay(
  53. which: fluwx.Payment(
  54. appId: created.appId!,
  55. partnerId: created.partnerId!,
  56. prepayId: created.prepayId!,
  57. packageValue: created.package ?? 'Sign=WXPay',
  58. nonceStr: created.noncestr!,
  59. timestamp: int.parse(created.timestamp!),
  60. sign: created.sign!,
  61. ),
  62. );
  63. }
  64. }