wechat_pay.dart 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import 'dart:async';
  2. import 'package:electronic_assistant/sdk/pay/wxpay/wechat_pay_info.dart';
  3. import 'package:flutter/widgets.dart';
  4. import 'package:wechat_kit/wechat_kit.dart';
  5. import '../assist/agile_pay_state_info.dart';
  6. import '../code/agile_pay_code.dart';
  7. import '../listener/i_agile_pay.dart';
  8. class WechatPay extends AgilePayStateInfo implements IAgilePay {
  9. late final StreamSubscription<WechatResp> _respSubs;
  10. final WechatPayInfo _payInfo;
  11. WechatPay(this._payInfo) {
  12. _respSubs = WechatKitPlatform.instance.respStream().listen(_listenResp);
  13. }
  14. void _listenResp(WechatResp resp) {
  15. if (resp is WechatPayResp) {
  16. final String content = 'pay: ${resp.errorCode} ${resp.errorMsg}';
  17. debugPrint('agilePay-wechat---> $content');
  18. if (!_respSubs.isPaused) {
  19. sendError(AgilePayCode.payCodeCancelError,
  20. AgilePayCode.getMessageByCode(AgilePayCode.payCodeCancelError));
  21. return;
  22. }
  23. if (resp.errorCode == WechatResp.kErrorCodeSuccess) {
  24. sendPaySuccess(resp.returnKey);
  25. } else if (resp.errorCode == WechatResp.kErrorCodeUserCancel) {
  26. sendError(AgilePayCode.payCodeCancelError,
  27. AgilePayCode.getMessageByCode(AgilePayCode.payCodeCancelError));
  28. } else {
  29. sendError(resp.errorCode, resp.errorMsg);
  30. }
  31. }
  32. }
  33. Future<bool> isInstalled() {
  34. return WechatKitPlatform.instance.isInstalled();
  35. }
  36. @override
  37. void pay() async {
  38. sendPayBefore();
  39. try {
  40. if (await check()) {
  41. if (await isInstalled()) {
  42. await WechatKitPlatform.instance.registerApp(
  43. appId: _payInfo.appId, universalLink: _payInfo.universalLink);
  44. try {
  45. WechatKitPlatform.instance.pay(
  46. appId: _payInfo.appId,
  47. partnerId: _payInfo.partnerId,
  48. prepayId: _payInfo.prepayId,
  49. package: _payInfo.package,
  50. nonceStr: _payInfo.noncestr,
  51. timeStamp: _payInfo.timestamp,
  52. sign: _payInfo.sign);
  53. } catch (e) {
  54. sendError(AgilePayCode.payCodePayError,
  55. AgilePayCode.getMessageByCode(AgilePayCode.payCodePayError));
  56. }
  57. } else {
  58. sendError(AgilePayCode.payCodeWxEnvError,
  59. AgilePayCode.getMessageByCode(AgilePayCode.payCodeWxEnvError));
  60. }
  61. } else {
  62. sendError(AgilePayCode.payCodeWxEnvError,
  63. AgilePayCode.getMessageByCode(AgilePayCode.payCodeWxEnvError));
  64. }
  65. } catch (e) {
  66. sendError(AgilePayCode.payCodeOtherError,
  67. AgilePayCode.getMessageByCode(AgilePayCode.payCodeOtherError));
  68. }
  69. }
  70. Future<bool> check() async {
  71. return WechatKitPlatform.instance.isSupportApi();
  72. }
  73. @override
  74. void dispose() {
  75. _respSubs.cancel();
  76. }
  77. }