WechatUserService.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <?php
  2. namespace api\services;
  3. use api\models\user\UserInfo;
  4. use EasyWeChat\Factory;
  5. use Yii;
  6. /**
  7. * 微信会员信息
  8. * @package api\services
  9. */
  10. class WechatUserService extends BaseService
  11. {
  12. /**
  13. * @var \EasyWeChat\OfficialAccount\Application
  14. */
  15. protected $app;
  16. public function __construct($config = [])
  17. {
  18. parent::__construct($config);
  19. if (empty($this->mall_id)) return $this->error('未设置Mall-Id');
  20. // 获取微信配置
  21. $wechat = Yii::$app->services->setting->mall->get($this->mall_id, 'wechat');
  22. if (!($wechat['app_id'] && $wechat['secret'])) return $this->error('未配置微信公众号');
  23. $options = [
  24. 'app_id' => $wechat['app_id'],
  25. 'secret' => $wechat['secret'],
  26. 'log' => [
  27. 'level' => 'debug',
  28. 'file' => '/tmp/easywechat.log',
  29. ],
  30. ];
  31. $this->app = Factory::officialAccount($options);
  32. }
  33. /**
  34. * 用户是否订阅
  35. *
  36. * @param integer $user_id
  37. * @return boolean
  38. */
  39. public function isSubscribe(int $user_id)
  40. {
  41. // 查询用户openid
  42. $openid = UserInfo::getWechatOpenid($this->mall_id, $user_id);
  43. if (empty($openid)) return $this->error('未找到用户公众号信息');
  44. // 查询微信信息
  45. $wechat_info = $this->info($openid);
  46. if (empty($wechat_info)) return $this->error($this->getError());
  47. return boolval($wechat_info['subscribe']);
  48. }
  49. /**
  50. * 会员详情
  51. *
  52. * @param string $openid
  53. * @return array|false
  54. */
  55. public function info(string $openid)
  56. {
  57. $info = $this->app->user->get($openid);
  58. if (isset($info['errcode'])) return $this->error($info['errmsg']);
  59. return $info;
  60. }
  61. }