wechat_pay.dart 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. try {
  16. if (resp is WechatPayResp) {
  17. final String content = 'pay: ${resp.errorCode} ${resp.errorMsg}';
  18. debugPrint('agilePay-wechat---> $content');
  19. if (resp.errorCode == WechatResp.kErrorCodeSuccess) {
  20. sendPaySuccess(resp.returnKey);
  21. } else if (resp.errorCode == WechatResp.kErrorCodeUserCancel) {
  22. sendError(AgilePayCode.payCodeCancelError,
  23. AgilePayCode.getMessageByCode(AgilePayCode.payCodeCancelError));
  24. } else {
  25. sendError(resp.errorCode, resp.errorMsg);
  26. }
  27. }
  28. } catch (e) {
  29. sendError(AgilePayCode.payCodeOtherError,
  30. AgilePayCode.getMessageByCode(AgilePayCode.payCodeOtherError));
  31. } finally {
  32. dispose();
  33. }
  34. }
  35. Future<bool> isInstalled() {
  36. return WechatKitPlatform.instance.isInstalled();
  37. }
  38. @override
  39. void pay() async {
  40. sendPayBefore();
  41. try {
  42. await WechatKitPlatform.instance.registerApp(
  43. appId: _payInfo.appId, universalLink: _payInfo.universalLink);
  44. if (await check()) {
  45. if (await isInstalled()) {
  46. try {
  47. WechatKitPlatform.instance.pay(
  48. appId: _payInfo.appId,
  49. partnerId: _payInfo.partnerId,
  50. prepayId: _payInfo.prepayId,
  51. package: _payInfo.package,
  52. nonceStr: _payInfo.noncestr,
  53. timeStamp: _payInfo.timestamp,
  54. sign: _payInfo.sign);
  55. } catch (e) {
  56. sendError(AgilePayCode.payCodePayError,
  57. AgilePayCode.getMessageByCode(AgilePayCode.payCodePayError));
  58. }
  59. } else {
  60. sendError(AgilePayCode.payCodeWxEnvError,
  61. AgilePayCode.getMessageByCode(AgilePayCode.payCodeWxEnvError));
  62. }
  63. } else {
  64. sendError(AgilePayCode.payCodeWxEnvError,
  65. AgilePayCode.getMessageByCode(AgilePayCode.payCodeWxEnvError));
  66. }
  67. } catch (e) {
  68. sendError(AgilePayCode.payCodeOtherError,
  69. AgilePayCode.getMessageByCode(AgilePayCode.payCodeOtherError));
  70. }
  71. }
  72. Future<bool> check() async {
  73. return WechatKitPlatform.instance.isSupportApi();
  74. }
  75. void dispose() {
  76. _respSubs.cancel();
  77. }
  78. }