WechatServices.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\services\wechat;
  13. use app\services\BaseServices;
  14. use app\dao\wechat\WechatUserDao;
  15. use app\services\user\UserServices;
  16. use app\services\user\UserVisitServices;
  17. use crmeb\services\CacheService;
  18. use crmeb\services\CacheService as Cache;
  19. use crmeb\services\wechat\OfficialAccount;
  20. use crmeb\services\wechat\Work;
  21. use crmeb\utils\Canvas;
  22. use EasyWeChat\Kernel\Exceptions\BadRequestException;
  23. use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
  24. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  25. use GuzzleHttp\Exception\GuzzleException;
  26. use think\db\exception\DataNotFoundException;
  27. use think\db\exception\ModelNotFoundException;
  28. use think\exception\ValidateException;
  29. /**
  30. *
  31. * Class WechatServices
  32. * @package app\services\wechat
  33. * @mixin WechatUserDao
  34. */
  35. class WechatServices extends BaseServices
  36. {
  37. /**
  38. * WechatServices constructor.
  39. * @param WechatUserDao $dao
  40. */
  41. public function __construct(WechatUserDao $dao)
  42. {
  43. $this->dao = $dao;
  44. }
  45. /**
  46. * 微信公众号服务
  47. * @return \think\Response
  48. * @throws BadRequestException
  49. * @throws InvalidArgumentException
  50. * @throws InvalidConfigException
  51. * @throws \ReflectionException
  52. */
  53. public function serve()
  54. {
  55. ob_clean();
  56. return OfficialAccount::serve();
  57. }
  58. /**
  59. * 企业微信服务
  60. * @return \think\Response
  61. * @throws BadRequestException
  62. * @throws InvalidArgumentException
  63. * @throws InvalidConfigException
  64. * @throws \ReflectionException
  65. */
  66. public function workServe()
  67. {
  68. ob_clean();
  69. return Work::serve();
  70. }
  71. /**
  72. * 公众号权限配置信息获取
  73. * @param $url
  74. * @return mixed
  75. * @throws GuzzleException
  76. * @throws \Psr\SimpleCache\InvalidArgumentException
  77. */
  78. public function config($url)
  79. {
  80. return json_decode(OfficialAccount::jsSdk($url), true);
  81. }
  82. /**
  83. * 获取授权信息
  84. * @param string $code
  85. * @return array
  86. */
  87. public function getAuthWechatInfo()
  88. {
  89. try {
  90. $userInfoConfig = OfficialAccount::tokenFromCode();
  91. } catch (\Throwable $e) {
  92. \think\facade\Log::error([
  93. 'error' => '授权失败:' . $e->getMessage(),
  94. 'file' => $e->getFile(),
  95. 'line' => $e->getLine()
  96. ]);
  97. throw new ValidateException('授权失败');
  98. }
  99. if (!isset($userInfoConfig['openid']) || !$userInfoConfig['openid']) {
  100. throw new ValidateException('openid获取失败');
  101. }
  102. return $userInfoConfig;
  103. }
  104. /**
  105. * 获取返回信息
  106. * @param $user
  107. * @param string $userType
  108. * @return array
  109. */
  110. public function getReturnInfo($user, string $userType = 'wechat')
  111. {
  112. if (!$user || !isset($user['uid']) || !$user['uid']) {
  113. throw new ValidateException('获取用户信息失败');
  114. }
  115. $token = $this->createToken((int)$user['uid'], $userType, $user['pwd'] ?? '');
  116. if (!$token) {
  117. throw new ValidateException('登录失败!');
  118. }
  119. /** @var UserVisitServices $visitServices */
  120. $visitServices = app()->make(UserVisitServices::class);
  121. $visitServices->loginSaveVisit($user);
  122. $token['store_user_avatar'] = 0;
  123. $token['userInfo'] = is_object($user) && method_exists($user, 'toArray') ? $user->toArray() : $user;
  124. $token['expires_time'] = $token['params']['exp'] ?? 0;
  125. return $token;
  126. }
  127. /**
  128. * 公众号授权登录,返回是否需要绑定手机号token
  129. * @param $spread_uid
  130. * @return array
  131. * @throws DataNotFoundException
  132. * @throws InvalidConfigException
  133. * @throws ModelNotFoundException
  134. * @throws \think\db\exception\DbException
  135. */
  136. public function authLogin($spread_uid = '')
  137. {
  138. $wechatInfo = OfficialAccount::userFromCode();
  139. if (!isset($wechatInfo['nickname'])) {
  140. $wechatInfo = OfficialAccount::userService()->get($wechatInfo['openid']);
  141. if (!isset($wechatInfo['nickname']))
  142. throw new ValidateException('授权失败');
  143. if (isset($wechatInfo['tagid_list']))
  144. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  145. } else {
  146. if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
  147. }
  148. $wechatInfo['user_type'] = 'wechat';
  149. $openid = $wechatInfo['openid'];
  150. /** @var WechatUserServices $wechatUserServices */
  151. $wechatUserServices = app()->make(WechatUserServices::class);
  152. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  153. $createData = [$openid, $wechatInfo, $spread_uid, 'wechat', 'wechat'];
  154. //获取是否强制绑定手机号
  155. $storeUserMobile = sys_config('store_user_mobile');
  156. if ($storeUserMobile && (($user && $user['phone'] == '') || !$user)) {
  157. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  158. CacheService::set($userInfoKey, $createData, 7200);
  159. return ['bindPhone' => true, 'key' => $userInfoKey];
  160. }
  161. if (!$user) {
  162. $user = $wechatUserServices->wechatOauthAfter($createData);
  163. } else {
  164. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  165. }
  166. return $this->getReturnInfo($user);
  167. }
  168. /**
  169. * @param $spread_uid
  170. * @param $login_type
  171. * @return array
  172. * @throws DataNotFoundException
  173. * @throws InvalidConfigException
  174. * @throws ModelNotFoundException
  175. * @throws \think\db\exception\DbException
  176. */
  177. public function auth($spread_uid, $login_type)
  178. {
  179. $wechatInfo = $this->getAuthWechatInfo();
  180. if (!isset($wechatInfo['nickname'])) {
  181. $wechatInfo = OfficialAccount::userService()->get($wechatInfo['openid']);
  182. if (!isset($wechatInfo['nickname']))
  183. throw new ValidateException('授权失败');
  184. if (isset($wechatInfo['tagid_list']))
  185. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  186. } else {
  187. if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
  188. /** @var WechatUserServices $wechatUser */
  189. $wechatUser = app()->make(WechatUserServices::class);
  190. if (!$wechatUser->getOne(['openid' => $wechatInfo['openid']])) {
  191. $wechatInfo['subscribe'] = 0;
  192. }
  193. }
  194. $wechatInfo['user_type'] = 'wechat';
  195. $openid = $wechatInfo['openid'];
  196. /** @var WechatUserServices $wechatUserServices */
  197. $wechatUserServices = app()->make(WechatUserServices::class);
  198. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  199. $createData = [$openid, $wechatInfo, $spread_uid, $login_type, 'wechat'];
  200. if (!$user) {
  201. $user = $wechatUserServices->wechatOauthAfter($createData);
  202. } else {
  203. //更新用户信息
  204. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  205. }
  206. return $this->getReturnInfo($user);
  207. }
  208. /**
  209. * 新公众号授权登录
  210. * @param $spread_uid
  211. * @param $login_type
  212. * @return mixed
  213. * @throws DataNotFoundException
  214. * @throws InvalidConfigException
  215. * @throws ModelNotFoundException
  216. */
  217. public function newAuth($spread_uid, $login_type)
  218. {
  219. $wechatInfo = OfficialAccount::userFromCode();
  220. if (!isset($wechatInfo['nickname'])) {
  221. $wechatInfo = OfficialAccount::userService()->get($wechatInfo['openid']);
  222. if (!isset($wechatInfo['nickname']))
  223. throw new ValidateException('授权失败');
  224. if (isset($wechatInfo['tagid_list']))
  225. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  226. } else {
  227. if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
  228. }
  229. $wechatInfo['user_type'] = 'wechat';
  230. $openid = $wechatInfo['openid'];
  231. /** @var WechatUserServices $wechatUserServices */
  232. $wechatUserServices = app()->make(WechatUserServices::class);
  233. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  234. $createData = [$openid, $wechatInfo, $spread_uid, $login_type, 'wechat'];
  235. //获取是否强制绑定手机号
  236. $storeUserMobile = sys_config('store_user_mobile');
  237. if ($storeUserMobile && !$user) {
  238. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  239. Cache::setTokenBucket($userInfoKey, $createData, 7200);
  240. return ['key' => $userInfoKey];
  241. } else if (!$user) {
  242. $user = $wechatUserServices->wechatOauthAfter($createData);
  243. } else {
  244. //更新用户信息
  245. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  246. }
  247. return $this->getReturnInfo($user);
  248. }
  249. public function follow()
  250. {
  251. $canvas = Canvas::instance();
  252. $path = 'uploads/follow/';
  253. $imageType = 'jpg';
  254. $name = 'follow';
  255. $siteUrl = sys_config('site_url');
  256. $imageUrl = $path . $name . '.' . $imageType;
  257. $canvas->setImageUrl(public_path() . 'statics/qrcode/follow.png')->setImageHeight(720)->setImageWidth(500)->pushImageValue();
  258. $wechatQrcode = sys_config('wechat_qrcode');
  259. if (($strlen = stripos($wechatQrcode, 'uploads')) !== false) {
  260. $wechatQrcode = substr($wechatQrcode, $strlen);
  261. }
  262. if (!$wechatQrcode)
  263. throw new ValidateException('请上传二维码');
  264. $canvas->setImageUrl($wechatQrcode)->setImageHeight(344)->setImageWidth(344)->setImageLeft(76)->setImageTop(76)->pushImageValue();
  265. $image = $canvas->setFileName($name)->setImageType($imageType)->setPath($path)->setBackgroundWidth(500)->setBackgroundHeight(720)->starDrawChart();
  266. return ['path' => $image ? $siteUrl . '/' . $image : ''];
  267. }
  268. /**
  269. * 微信公众号静默授权
  270. * @param $spread
  271. * @param bool $notLogin
  272. * @return array
  273. * @throws DataNotFoundException
  274. * @throws ModelNotFoundException
  275. */
  276. public function silenceAuth($spread, bool $notLogin = false, string $snsapi = '')
  277. {
  278. if ($snsapi) {
  279. $wechatInfoConfig = $this->getAuthWechatInfo();
  280. } else {
  281. $wechatInfoConfig = OfficialAccount::userFromCode();
  282. }
  283. $openid = $wechatInfoConfig['openid'];
  284. try {
  285. $wechatInfo = OfficialAccount::userService()->get($wechatInfoConfig['openid']);
  286. } catch (\Throwable $e) {
  287. $createData = [$openid, [], $spread, '', 'wechat'];
  288. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  289. Cache::setTokenBucket($userInfoKey, $createData, 7200);
  290. return ['auth_login' => 1, 'key' => $userInfoKey];
  291. }
  292. /** @var WechatUserServices $wechatUserServices */
  293. $wechatUserServices = app()->make(WechatUserServices::class);
  294. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  295. if (!$user) {
  296. $wechatInfo['headimgurl'] = isset($wechatInfo['headimgurl']) && $wechatInfo['headimgurl'] != '' ? $wechatInfo['headimgurl'] : sys_config('h5_avatar');
  297. $createData = [$openid, $wechatInfo, $spread, '', 'wechat'];
  298. //获取是否强制绑定手机号
  299. $storeUserMobile = sys_config('store_user_mobile');
  300. if ($notLogin || $storeUserMobile) {
  301. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  302. Cache::setTokenBucket($userInfoKey, $createData, 7200);
  303. return ['auth_login' => 1, 'key' => $userInfoKey];
  304. } else {
  305. //写入用户信息
  306. $user = $wechatUserServices->wechatOauthAfter($createData);
  307. }
  308. } else {
  309. //更新用户信息
  310. $wechatUserServices->wechatUpdata([$user['uid'], ['spread_uid' => $spread]]);
  311. }
  312. return $this->getReturnInfo($user);
  313. }
  314. /**
  315. * 微信公众号静默授权
  316. * @param $spread
  317. * @param $phone
  318. * @return array
  319. * @throws DataNotFoundException
  320. * @throws ModelNotFoundException|\Psr\SimpleCache\InvalidArgumentException
  321. */
  322. public function silenceAuthBindingPhone($key, $phone)
  323. {
  324. if (!$key) {
  325. throw new ValidateException('请刷新页面或者重新授权');
  326. }
  327. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = $createData = CacheService::getTokenBucket($key);
  328. if (!$createData) {
  329. throw new ValidateException('请刷新页面或者重新授权');
  330. }
  331. $wechatInfo['phone'] = $phone;
  332. /** @var WechatUserServices $wechatUser */
  333. $wechatUser = app()->make(WechatUserServices::class);
  334. //更新用户信息
  335. $user = $wechatUser->wechatOauthAfter([$openid, $wechatInfo, $spread_uid, $login_type, $userType]);
  336. return $this->getReturnInfo($user);
  337. }
  338. /**
  339. * @param array $userData
  340. * @param string $phone
  341. * @param string $userType
  342. * @return array
  343. * @throws DataNotFoundException
  344. * @throws ModelNotFoundException
  345. */
  346. public function appAuth(array $userData, string $phone, string $userType = 'app')
  347. {
  348. $openid = $userData['openId'] ?? "";
  349. $userInfo = [
  350. 'phone' => $phone,
  351. 'unionid' => $userData['unionId'] ?? '',
  352. 'headimgurl' => $userData['avatarUrl'] ?? '',
  353. 'nickname' => $userData['nickName'] ?? '',
  354. 'province' => $userData['province'] ?? '',
  355. 'country' => $userData['country'] ?? '',
  356. 'city' => $userData['city'] ?? '',
  357. 'openid' => $openid,
  358. ];
  359. $login_type = $userType;
  360. $spread_uid = $userInfo['spreadId'] ?? "";
  361. if (!$phone) {
  362. //获取是否强制绑定手机号
  363. $storeUserMobile = sys_config('store_user_mobile');
  364. if ($userInfo['unionid'] && $storeUserMobile) {
  365. /** @var UserServices $userServices */
  366. $userServices = app()->make(UserServices::class);
  367. $uid = $this->dao->value(['unionid' => $userInfo['unionid'], 'is_del' => 0], 'uid');
  368. $res = $userServices->value(['uid' => $uid], 'phone');
  369. if (!$uid && !$res) {
  370. return false;
  371. }
  372. }
  373. if ($openid && $storeUserMobile) {
  374. /** @var UserServices $userServices */
  375. $userServices = app()->make(UserServices::class);
  376. $uid = $this->dao->value(['openid' => $openid, 'is_del' => 0], 'uid');
  377. $res = $userServices->value(['uid' => $uid], 'phone');
  378. if (!$uid && !$res) {
  379. return false;
  380. }
  381. }
  382. }
  383. /** @var WechatUserServices $wechatUser */
  384. $wechatUser = app()->make(WechatUserServices::class);
  385. //更新用户信息
  386. $user = $wechatUser->wechatOauthAfter([$openid, $userInfo, $spread_uid, $login_type, $userType]);
  387. $token = $this->getReturnInfo($user);
  388. $token['isbind'] = false;
  389. return $token;
  390. }
  391. /**
  392. * 是否关注
  393. * @param int $uid
  394. * @return bool
  395. */
  396. public function isSubscribe(int $uid)
  397. {
  398. if ($uid) {
  399. $subscribe = (bool)$this->dao->value(['uid' => $uid], 'subscribe');
  400. } else {
  401. $subscribe = true;
  402. }
  403. return $subscribe;
  404. }
  405. /**
  406. * 更新公众号用户信息
  407. * @param int $uid
  408. * @return array
  409. */
  410. public function updateUserInfo(int $uid)
  411. {
  412. $wechatInfoConfig = OfficialAccount::userFromCode();
  413. $openid = $wechatInfoConfig['openid'] ?? null;
  414. try {
  415. $wechatInfo = OfficialAccount::userService()->get($wechatInfoConfig['openid']);
  416. } catch (\Throwable $e) {
  417. throw new ValidateException('更新公众号用户信息失败:' . $e->getMessage());
  418. }
  419. if (!$openid) {
  420. throw new ValidateException('更新公众号用户信息失败:没有获取到openid');
  421. }
  422. $wechatInfo['nickname'] = $wechatInfoConfig['nickname'] ?? $wechatInfo['nickname'];
  423. $wechatInfo['headimgurl'] = $wechatInfoConfig['headimgurl'] ?? $wechatInfo['headimgurl'];
  424. /** @var WechatUserServices $wechatUserServices */
  425. $wechatUserServices = app()->make(WechatUserServices::class);
  426. $id = $wechatUserServices->value(['openid' => $openid, 'uid' => $uid, 'user_type' => 'wechat'], 'id');
  427. if (!$id) {
  428. throw new ValidateException('没有查到用户信息');
  429. }
  430. /** @var UserServices $userService */
  431. $userService = app()->make(UserServices::class);
  432. $user = $userService->getUserInfo($uid);
  433. if (isset($user['status']) && !$user['status']) {
  434. throw new ValidateException('您已被禁止登录,请联系管理员');
  435. }
  436. if ($user) {
  437. //更新用户信息
  438. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  439. }
  440. return [
  441. 'nickname' => $wechatInfo['nickname'],
  442. 'avatar' => $wechatInfo['headimgurl'],
  443. 'is_complete' => 1
  444. ];
  445. }
  446. }