wechat_pay.dart 2.6 KB

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