WechatUserServices.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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\jobs\user\UserJob;
  14. use app\services\BaseServices;
  15. use app\dao\wechat\WechatUserDao;
  16. use app\services\user\LoginServices;
  17. use app\services\user\UserServices;
  18. use crmeb\exceptions\AdminException;
  19. use crmeb\exceptions\AuthException;
  20. use crmeb\services\wechat\OfficialAccount;
  21. use think\exception\ValidateException;
  22. /**
  23. *
  24. * Class WechatUserServices
  25. * @package app\services\wechat
  26. * @mixin WechatUserDao
  27. */
  28. class WechatUserServices extends BaseServices
  29. {
  30. /**
  31. * WechatUserServices constructor.
  32. * @param WechatUserDao $dao
  33. */
  34. public function __construct(WechatUserDao $dao)
  35. {
  36. $this->dao = $dao;
  37. }
  38. public function getColumnUser($user_ids, $column, $key, string $user_type = 'wechat')
  39. {
  40. return $this->dao->getColumn([['uid', 'IN', $user_ids], ['user_type', '=', $user_type]], $column, $key);
  41. }
  42. /**
  43. * 获取单个微信用户
  44. * @param array $where
  45. * @param string $field
  46. * @return array
  47. * @throws \think\db\exception\DataNotFoundException
  48. * @throws \think\db\exception\DbException
  49. * @throws \think\db\exception\ModelNotFoundException
  50. */
  51. public function getWechatUserInfo(array $where, $field = '*')
  52. {
  53. return $this->dao->getOne($where, $field);
  54. }
  55. /**
  56. * 用uid获得 微信openid
  57. * @param $uid
  58. * @return mixed
  59. */
  60. public function uidToOpenid(int $uid, string $userType = 'wechat')
  61. {
  62. return $this->dao->value(['uid' => $uid, 'user_type' => $userType], 'openid');
  63. }
  64. /**
  65. * 用openid获得uid
  66. * @param $openid
  67. * @param string $openidType
  68. * @return mixed
  69. */
  70. public function openidTouid($openid, $openidType = 'openid')
  71. {
  72. $uid = $this->dao->value([[$openidType, '=', $openid], ['user_type', '<>', 'h5']], 'uid');
  73. if (!$uid)
  74. throw new AdminException('对应的uid不存在');
  75. return $uid;
  76. }
  77. /**
  78. * 用户取消关注
  79. * @param $openid
  80. * @return bool
  81. */
  82. public function unSubscribe($openid)
  83. {
  84. if (!$this->dao->update($openid, ['subscribe' => 0, 'subscribe_time' => time()], 'openid'))
  85. throw new AdminException('取消关注失败');
  86. return true;
  87. }
  88. /**
  89. * 更新微信用户信息
  90. * @param $message
  91. * @return bool
  92. * @throws \think\db\exception\DataNotFoundException
  93. * @throws \think\db\exception\DbException
  94. * @throws \think\db\exception\ModelNotFoundException
  95. */
  96. public function saveUserV1($message)
  97. {
  98. $openid = $message->FromUserName;
  99. if ($this->getWechatUserInfo(['openid' => $openid])) {
  100. $this->updateWecahtUser($openid);
  101. } else {
  102. $this->setWecahtUser($openid);
  103. }
  104. return true;
  105. }
  106. /**
  107. * 用户存在就更新 不存在就添加
  108. * @param $openid
  109. * @param int $spread_uid
  110. * @param string $phone
  111. * @return \app\services\user\User|array|\think\Model|null
  112. * @throws \think\db\exception\DataNotFoundException
  113. * @throws \think\db\exception\DbException
  114. * @throws \think\db\exception\ModelNotFoundException
  115. */
  116. public function saveUser($openid, $spread_uid = 0, $phone = '')
  117. {
  118. $is_new = false;
  119. /** @var UserServices $userServices */
  120. $userServices = app()->make(UserServices::class);
  121. $wechatUser = $this->getWechatUserInfo(['openid' => $openid]);
  122. if ($wechatUser && $wechatUser['uid']) {
  123. $userInfo = $userServices->getUserInfo((int)$wechatUser['uid']);
  124. //无关注只是授权生成用户
  125. if (!$wechatUser['subscribe_time'] && $wechatUser['uid']) {
  126. $is_new = true;
  127. $spread_uid = $userInfo['spread_uid'] ?? 0;
  128. }
  129. $this->updateWecahtUser($openid);
  130. } else {
  131. $userInfo = $this->setNewUser($openid, $spread_uid, ['phone' => $phone]);
  132. $is_new = true;
  133. }
  134. if ($is_new) {
  135. UserJob::dispatchDo('subscribeSpreadLottery', [(int)$userInfo['uid'], $openid, (int)$spread_uid]);
  136. }
  137. return $userInfo;
  138. }
  139. /**
  140. * 更新用户信息
  141. * @param $openid
  142. * @param string $phone
  143. * @return bool
  144. */
  145. public function updateWecahtUser($openid)
  146. {
  147. try {
  148. $userInfo = OfficialAccount::getUserInfo($openid);
  149. } catch (\Throwable $e) {
  150. $userInfo = [];
  151. }
  152. if (isset($userInfo['nickname']) && $userInfo['nickname']) {
  153. $userInfo['nickname'] = filter_emoji($userInfo['nickname']);
  154. } else {
  155. if (isset($userInfo['nickname'])) unset($userInfo['nickname']);
  156. }
  157. if (isset($userInfo['tagid_list'])) {
  158. $userInfo['tagid_list'] = implode(',', $userInfo['tagid_list']);
  159. }
  160. if ($userInfo && !$this->dao->update($openid, $userInfo, 'openid'))
  161. throw new AdminException('更新失败');
  162. return true;
  163. }
  164. /**
  165. * 写入微信用户信息
  166. * @param $openid
  167. * @param int $uid
  168. * @return bool
  169. */
  170. public function setWecahtUser($openid, int $uid = 0)
  171. {
  172. try {
  173. $wechatInfo = OfficialAccount::getUserInfo($openid);
  174. } catch (\Throwable $e) {
  175. $wechatInfo = [];
  176. }
  177. if (!isset($wechatInfo['openid']))
  178. throw new ValidateException('请关注公众号!');
  179. if (isset($wechatInfo['nickname']) && $wechatInfo['nickname']) {
  180. $wechatInfo['nickname'] = filter_emoji($wechatInfo['nickname']);
  181. } else {
  182. mt_srand();
  183. $wechatInfo['nickname'] = 'wx' . rand(100000, 999999);
  184. }
  185. if (isset($wechatInfo['tagid_list'])) {
  186. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  187. }
  188. $wechatInfo['user_type'] = 'wechat';
  189. $wechatInfo['uid'] = $uid;
  190. $wechatInfo['add_time'] = time();
  191. if ($wechatInfo && !$this->dao->save($wechatInfo)) {
  192. throw new AdminException('用户储存失败!');
  193. }
  194. return true;
  195. }
  196. /**
  197. * 添加新用户
  198. * @param $openid
  199. * @param int $spread_uid
  200. * @param array $append 追加字段
  201. * @return \app\services\user\User|\think\Model
  202. * @throws \think\db\exception\DataNotFoundException
  203. * @throws \think\db\exception\DbException
  204. * @throws \think\db\exception\ModelNotFoundException
  205. */
  206. public function setNewUser($openid, $spread_uid = 0, array $append = [])
  207. {
  208. try {
  209. $wechatInfo = OfficialAccount::getUserInfo($openid);
  210. } catch (\Throwable $e) {
  211. $wechatInfo = [];
  212. }
  213. if (!isset($wechatInfo['openid']))
  214. throw new ValidateException('请关注公众号!');
  215. if (isset($wechatInfo['nickname']) && $wechatInfo['nickname']) {
  216. $wechatInfo['nickname'] = $wechatInfo['nickname'];
  217. $wechatInfo['is_complete'] = 1;
  218. } else {
  219. //昵称不存在的信息不完整
  220. $wechatInfo['is_complete'] = 0;
  221. mt_srand();
  222. $wechatInfo['nickname'] = 'wx' . rand(100000, 999999);
  223. }
  224. if (isset($wechatInfo['tagid_list'])) {
  225. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  226. }
  227. $uid = 0;
  228. $userType = 'wechat';
  229. $userInfo = [];
  230. /** @var UserServices $userServices */
  231. $userServices = app()->make(UserServices::class);
  232. if (isset($append['phone']) && $append['phone']) {
  233. $userInfo = $userServices->getOne(['phone' => $append['phone']]);
  234. $wechatInfo['phone'] = $append['phone'];
  235. }
  236. if (!$userInfo) {
  237. if (isset($wechatInfo['unionid']) && $wechatInfo['unionid']) {
  238. $uid = $this->dao->value(['unionid' => $wechatInfo['unionid']], 'uid');
  239. if ($uid) {
  240. $userInfo = $userServices->getOne(['uid' => $uid]);
  241. }
  242. } else {
  243. $userInfo = $this->getAuthUserInfo($openid, $userType);
  244. }
  245. }
  246. if ($userInfo) {
  247. $uid = (int)$userInfo['uid'];
  248. if (isset($userInfo['status']) && !$userInfo['status'])
  249. throw new ValidateException('您已被禁止登录,请联系管理员');
  250. }
  251. $wechatInfo['user_type'] = $userType;
  252. if ($userInfo) {
  253. //更新用户表和wechat_user表
  254. //判断该类性用户在wechatUser中是否存在
  255. $wechatUser = $this->dao->getOne(['uid' => $uid, 'user_type' => $userType]);
  256. if ($wechatUser) {
  257. $wechatUser = $this->dao->getOne(['openid' => $openid]);
  258. }
  259. /** @var LoginServices $loginService */
  260. $loginService = app()->make(LoginServices::class);
  261. $this->transaction(function () use ($openid, $loginService, $wechatInfo, $userInfo, $uid, $userType, $spread_uid, $wechatUser) {
  262. $wechatInfo['code'] = $spread_uid;
  263. $wechatInfo['uid'] = $uid;
  264. $loginService->updateUserInfo($wechatInfo, $userInfo);
  265. if ($wechatUser) {
  266. //更换微信登录情况
  267. // if (isset($append['phone']) && $append['phone'] && $wechatUser['openid'] != $openid) {
  268. // throw new ValidateException('该手机号已被注册');
  269. // }
  270. if (!$this->dao->update($wechatUser['id'], $wechatInfo, 'id')) {
  271. throw new ValidateException('更新数据失败');
  272. }
  273. } else {
  274. if (!$this->dao->save($wechatInfo)) {
  275. throw new ValidateException('写入信息失败');
  276. }
  277. }
  278. });
  279. } else {
  280. //user表没有用户,wechat_user表没有用户创建新用户
  281. //不存在则创建用户
  282. $userInfo = $this->transaction(function () use ($openid, $userServices, $wechatInfo, $spread_uid, $userType) {
  283. $userInfo = $userServices->setUserInfo($wechatInfo, (int)$spread_uid, $userType);
  284. if (!$userInfo) {
  285. throw new AuthException('生成User用户失败!');
  286. }
  287. $wechatInfo['uid'] = $userInfo->uid;
  288. $wechatInfo['add_time'] = $userInfo->add_time;
  289. $wechatUser = $this->dao->getOne(['openid' => $openid]);
  290. if ($wechatUser) {
  291. if (!$this->dao->update($wechatUser['id'], $wechatInfo, 'id')) {
  292. throw new ValidateException('更新数据失败');
  293. }
  294. } else {
  295. if (!$this->dao->save($wechatInfo)) {
  296. throw new AuthException('生成微信用户失败!');
  297. }
  298. }
  299. return $userInfo;
  300. });
  301. }
  302. return $userInfo;
  303. }
  304. /**
  305. * 授权后获取用户信息
  306. * @param $openid
  307. * @param $user_type
  308. */
  309. public function getAuthUserInfo($openid, $user_type)
  310. {
  311. $user = [];
  312. //兼容老用户
  313. $uids = $this->dao->getColumn(['unionid|openid' => $openid, 'is_del' => 0], 'uid,user_type', 'user_type');
  314. if ($uids) {
  315. $uid = $uids[$user_type]['uid'] ?? 0;
  316. if (!$uid) {
  317. $ids = array_column($uids, 'uid');
  318. $uid = $ids[0];
  319. }
  320. /** @var UserServices $userServices */
  321. $userServices = app()->make(UserServices::class);
  322. $user = $userServices->getUserInfo($uid);
  323. if (isset($user['status']) && !$user['status'])
  324. throw new AuthException('您已被禁止登录,请联系管理员', 410020);
  325. }
  326. return $user;
  327. }
  328. /**
  329. * 更新微信用户信息
  330. * @param $event
  331. * @return bool
  332. */
  333. public function wechatUpdata($data)
  334. {
  335. [$uid, $userData] = $data;
  336. /** @var UserServices $userServices */
  337. $userServices = app()->make(UserServices::class);
  338. if (!$userInfo = $userServices->getUserInfo($uid)) {
  339. return false;
  340. }
  341. /** @var LoginServices $loginService */
  342. $loginService = app()->make(LoginServices::class);
  343. $loginService->updateUserInfo($userData, $userInfo);
  344. //更新用户信息
  345. /** @var WechatUserServices $wechatUser */
  346. $wechatUser = app()->make(WechatUserServices::class);
  347. $wechatUserInfo = [];
  348. if (isset($userData['nickname']) && $userData['nickname']) $wechatUserInfo['nickname'] = filter_emoji($userData['nickname'] ?? '');//姓名
  349. if (isset($userData['headimgurl']) && $userData['headimgurl']) $wechatUserInfo['headimgurl'] = $userData['headimgurl'] ?? '';//头像
  350. if (isset($userData['sex']) && $userData['sex']) $wechatUserInfo['sex'] = $userData['gender'] ?? '';//性别
  351. if (isset($userData['language']) && $userData['language']) $wechatUserInfo['language'] = $userData['language'] ?? '';//语言
  352. if (isset($userData['city']) && $userData['city']) $wechatUserInfo['city'] = $userData['city'] ?? '';//城市
  353. if (isset($userData['province']) && $userData['province']) $wechatUserInfo['province'] = $userData['province'] ?? '';//省份
  354. if (isset($userData['country']) && $userData['country']) $wechatUserInfo['country'] = $userData['country'] ?? '';//国家
  355. if (!empty($wechatUserInfo['nickname']) || !empty($wechatUserInfo['headimgurl'])) {
  356. $wechatUserInfo['is_complete'] = 1;
  357. } else {
  358. $wechatUserInfo['is_complete'] = 0;
  359. }
  360. if ($wechatUserInfo) {
  361. if (isset($userData['openid']) && $userData['openid'] && false === $wechatUser->update(['uid' => $userInfo['uid'], 'openid' => $userData['openid']], $wechatUserInfo)) {
  362. throw new ValidateException('更新失败');
  363. }
  364. }
  365. return true;
  366. }
  367. /**
  368. * 微信授权成功后
  369. * @param $event
  370. * @throws \think\db\exception\DataNotFoundException
  371. * @throws \think\db\exception\ModelNotFoundException
  372. * @throws \think\exception\DbException
  373. */
  374. public function wechatOauthAfter(array $data)
  375. {
  376. [$openid, $wechatInfo, $spread_uid, $login_type, $userType] = $data;
  377. /** @var UserServices $userServices */
  378. $userServices = app()->make(UserServices::class);
  379. if ($spread_uid && !$userServices->userExist((int)$spread_uid)) {
  380. $spread_uid = 0;
  381. }
  382. //删除多余字段
  383. unset($wechatInfo['subscribe_scene'], $wechatInfo['qr_scene'], $wechatInfo['qr_scene_str']);
  384. if ($login_type) {
  385. $wechatInfo['login_type'] = $login_type;
  386. }
  387. if (!isset($wechatInfo['nickname']) || !$wechatInfo['nickname']) {
  388. if (isset($wechatInfo['phone']) && $wechatInfo['phone']) {
  389. $wechatInfo['nickname'] = substr_replace($wechatInfo['phone'], '****', 3, 4);
  390. } else {
  391. mt_srand();
  392. $wechatInfo['nickname'] = 'wx' . rand(100000, 999999);
  393. }
  394. } else {
  395. $wechatInfo['is_complete'] = 1;
  396. $wechatInfo['nickname'] = filter_emoji($wechatInfo['nickname']);
  397. }
  398. //统一用户处理:1:同一手机号用户 2:开放平台 3:openid
  399. $userInfo = [];
  400. if (isset($wechatInfo['phone']) && $wechatInfo['phone']) {
  401. $userInfo = $userServices->getOne(['phone' => $wechatInfo['phone']]);
  402. }
  403. if (!$userInfo) {
  404. if (isset($wechatInfo['unionid']) && $wechatInfo['unionid']) {
  405. $uid = $this->dao->value(['unionid' => $wechatInfo['unionid'], 'is_del' => 0], 'uid');
  406. if ($uid) {
  407. $userInfo = $userServices->getOne(['uid' => $uid]);
  408. }
  409. } else {
  410. $userInfo = $this->getAuthUserInfo($openid, $userType);
  411. }
  412. }
  413. $uid = (int)($userInfo['uid'] ?? 0);
  414. $wechatInfo['user_type'] = $userType;
  415. //user表存在和wechat_user表同时存在
  416. return $this->transaction(function () use ($openid, $uid, $userInfo, $wechatInfo, $userServices, $spread_uid, $userType) {
  417. $wechatInfo['spread_uid'] = $spread_uid;
  418. $wechatInfo['uid'] = $uid;
  419. if ($userInfo) {
  420. if (isset($userInfo['status']) && !$userInfo['status'])
  421. throw new ValidateException('您已被禁止登录,请联系管理员');
  422. //更新用户表
  423. /** @var LoginServices $loginService */
  424. $loginService = app()->make(LoginServices::class);
  425. $loginService->updateUserInfo($wechatInfo, $userInfo);
  426. } else {
  427. //新增用户表
  428. $userInfo = $userServices->setUserInfo($wechatInfo, (int)$spread_uid, $userType);
  429. if (!$userInfo) {
  430. throw new AuthException('生成User用户失败!');
  431. }
  432. //用户绑定客户事件
  433. if (!empty($wechatInfo['unionid'])) {
  434. event('user.client', [$userInfo['uid'], $wechatInfo['unionid']]);
  435. }
  436. //用户绑定成员事件
  437. if (!empty($userInfo['phone'])) {
  438. event('user.work', [$userInfo['uid'], $userInfo['phone']]);
  439. }
  440. }
  441. $uid = $userInfo['uid'];
  442. $wechatInfo['uid'] = $userInfo->uid;
  443. $wechatInfo['add_time'] = $userInfo->add_time;
  444. //判断该类性用户在wechatUser中是否存在
  445. $wechatUser = $this->dao->getOne(['uid' => $uid, 'user_type' => $userType, 'is_del' => 0]);
  446. if (!$wechatUser) {
  447. $wechatUser = $this->dao->getOne(['openid' => $openid, 'is_del' => 0]);
  448. }
  449. if ($wechatUser) {
  450. //更换微信登录情况
  451. // if (isset($wechatInfo['phone']) && $wechatInfo['phone'] && $wechatUser['openid'] != $openid) {
  452. // throw new ValidateException('该手机号已被注册');
  453. // }
  454. if (!$this->dao->update($wechatUser['id'], $wechatInfo, 'id')) {
  455. throw new ValidateException('更新数据失败');
  456. }
  457. } else {
  458. if (!$this->dao->save($wechatInfo)) {
  459. throw new AuthException('生成微信用户失败!');
  460. }
  461. }
  462. return $userInfo;
  463. });
  464. }
  465. /**
  466. * 更新用户信息(同步)
  467. * @param array $openids
  468. * @return array
  469. * @throws \think\db\exception\DataNotFoundException
  470. * @throws \think\db\exception\DbException
  471. * @throws \think\db\exception\ModelNotFoundException
  472. */
  473. public function syncWechatUser(array $openids)
  474. {
  475. if (!$openids) {
  476. return [];
  477. }
  478. $wechatUser = $this->dao->getList([['openid', 'in', $openids]]);
  479. $noBeOpenids = $openids;
  480. if ($wechatUser) {
  481. $beOpenids = array_column($wechatUser, 'openid');
  482. $noBeOpenids = array_diff($openids, $beOpenids);
  483. if ($beOpenids) {
  484. $data = [];
  485. foreach ($beOpenids as $openid) {
  486. try {
  487. $info = OfficialAccount::getUserInfo($openid);
  488. } catch (\Throwable $e) {
  489. $info = [];
  490. }
  491. if (!$info) continue;
  492. $data['subscribe'] = $info['subscribe'] ?? 1;
  493. if (($info['subscribe'] ?? 1) == 1) {
  494. $data['unionid'] = $info['unionid'] ?? '';
  495. $data['nickname'] = $info['nickname'] ?? '';
  496. $data['sex'] = $info['sex'] ?? 0;
  497. $data['language'] = $info['language'] ?? '';
  498. $data['city'] = $info['city'] ?? '';
  499. $data['province'] = $info['province'] ?? '';
  500. $data['country'] = $info['country'] ?? '';
  501. $data['headimgurl'] = $info['headimgurl'] ?? '';
  502. $data['subscribe_time'] = $info['subscribe_time'] ?? '';
  503. $data['groupid'] = $info['groupid'] ?? 0;
  504. $data['remark'] = $info['remark'] ?? '';
  505. $data['tagid_list'] = isset($info['tagid_list']) && $info['tagid_list'] ? implode(',', $info['tagid_list']) : '';
  506. }
  507. $this->dao->update(['openid' => $info['openid']], $data);
  508. }
  509. }
  510. }
  511. return $noBeOpenids;
  512. }
  513. }