WechatUserServices.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 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\LoginServices;
  16. use app\services\user\UserServices;
  17. use crmeb\exceptions\AdminException;
  18. use crmeb\exceptions\ApiException;
  19. use crmeb\exceptions\AuthException;
  20. use crmeb\services\app\WechatService;
  21. use think\facade\Log;
  22. /**
  23. *
  24. * Class WechatUserServices
  25. * @package app\services\wechat
  26. * @method delete($id, ?string $key = null) 删除
  27. * @method update($id, array $data, ?string $key = null) 更新数据
  28. * @method getColumn(array $where, string $field, string $key = '') 获取某个字段数组
  29. * @method get($id, ?array $field = []) 用主键获取一条数据
  30. * @method getOne(array $where, ?string $field = '*', array $with = []) 获得一条数据
  31. * @method value(array $value, string $key) 获取一条数据
  32. * @method getWechatTrendData($time, $where, $timeType, $key)
  33. * @method getWechatOpenid(int $uid, string $userType = 'wechat') 获取微信公众号openid
  34. */
  35. class WechatUserServices extends BaseServices
  36. {
  37. /**
  38. * WechatUserServices constructor.
  39. * @param WechatUserDao $dao
  40. */
  41. public function __construct(WechatUserDao $dao)
  42. {
  43. $this->dao = $dao;
  44. }
  45. public function getColumnUser($user_ids, $column, $key, string $user_type = 'wechat')
  46. {
  47. return $this->dao->getColumn([['uid', 'IN', $user_ids], ['user_type', '=', $user_type]], $column, $key);
  48. }
  49. /**
  50. * 获取单个微信用户
  51. * @param array $where
  52. * @param string $field
  53. * @return array
  54. * @throws \think\db\exception\DataNotFoundException
  55. * @throws \think\db\exception\DbException
  56. * @throws \think\db\exception\ModelNotFoundException
  57. */
  58. public function getWechatUserInfo(array $where, $field = '*')
  59. {
  60. return $this->dao->getOne($where, $field);
  61. }
  62. /**
  63. * 用uid获得 微信openid
  64. * @param int $uid
  65. * @param string $userType
  66. * @return mixed
  67. * @author: 吴汐
  68. * @email: 442384644@qq.com
  69. * @date: 2023/8/17
  70. */
  71. public function uidToOpenid(int $uid, string $userType = 'wechat')
  72. {
  73. return $this->dao->value(['uid' => $uid, 'user_type' => $userType], 'openid');
  74. }
  75. /**
  76. * TODO 用openid获得uid
  77. * @param $openid
  78. * @param string $openidType
  79. * @return mixed
  80. */
  81. public function openidToUid($openid, string $openidType = 'openid')
  82. {
  83. $uid = $this->dao->value([$openidType => $openid, 'is_del' => 0], 'uid');
  84. if (!$uid)
  85. throw new AdminException(400710);
  86. return $uid;
  87. }
  88. /**
  89. * 用户取消关注
  90. * @param $openid
  91. * @return bool
  92. */
  93. public function unSubscribe($openid)
  94. {
  95. if (!$this->dao->update($openid, ['subscribe' => 0, 'subscribe_time' => time()], 'openid'))
  96. throw new AdminException(400711);
  97. return true;
  98. }
  99. /**
  100. * 用户存在就更新 不存在就添加
  101. * @param $openid
  102. * @return bool
  103. * @throws \think\db\exception\DataNotFoundException
  104. * @throws \think\db\exception\DbException
  105. * @throws \think\db\exception\ModelNotFoundException
  106. */
  107. public function saveUser($openid)
  108. {
  109. if ($this->getWechatUserInfo(['openid' => $openid])) {
  110. $this->updateUser($openid);
  111. return false;
  112. } else {
  113. $this->setNewUser($openid);
  114. return true;
  115. }
  116. }
  117. /**
  118. * 更新用户信息
  119. * @param $openid
  120. * @return bool
  121. */
  122. public function updateUser($openid)
  123. {
  124. $userInfo = WechatService::getUserInfo($openid);
  125. $userInfo = is_object($userInfo) ? $userInfo->toArray() : $userInfo;
  126. if (isset($userInfo['nickname']) && $userInfo['nickname']) {
  127. $userInfo['nickname'] = filter_emoji($userInfo['nickname']);
  128. } else {
  129. mt_srand();
  130. $userInfo['nickname'] = 'wx' . rand(100000, 999999);
  131. $userInfo['avatar'] = sys_config('h5_avatar');
  132. }
  133. if (isset($userInfo['tagid_list'])) {
  134. $userInfo['tagid_list'] = implode(',', $userInfo['tagid_list']);
  135. }
  136. if (!$this->dao->update($openid, $userInfo, 'openid'))
  137. throw new AdminException(100013);
  138. return true;
  139. }
  140. /**
  141. * .添加新用户
  142. * @param $openid
  143. * @return object
  144. */
  145. public function setNewUser($openid)
  146. {
  147. $userInfo = WechatService::getUserInfo($openid);
  148. if (!isset($userInfo['openid']))
  149. throw new AdminException(410082);
  150. $userInfo = is_object($userInfo) ? $userInfo->toArray() : $userInfo;
  151. if (isset($userInfo['nickname']) && $userInfo['nickname']) {
  152. $userInfo['nickname'] = filter_emoji($userInfo['nickname']);
  153. } else {
  154. mt_srand();
  155. $userInfo['nickname'] = 'wx' . rand(100000, 999999);
  156. $userInfo['headimgurl'] = sys_config('h5_avatar');
  157. }
  158. if (isset($userInfo['tagid_list'])) {
  159. $userInfo['tagid_list'] = implode(',', $userInfo['tagid_list']);
  160. }
  161. $wechatInfo = [];
  162. $uid = 0;
  163. $userInfoData = null;
  164. if (isset($userInfo['unionid'])) {
  165. $wechatInfo = $this->getWechatUserInfo(['unionid' => $userInfo['unionid']]);
  166. }
  167. if (!$wechatInfo) {
  168. /** @var UserServices $userServices */
  169. $userServices = app()->make(UserServices::class);
  170. $userInfoData = $userServices->setUserInfo($userInfo);
  171. if (!$userInfoData) {
  172. throw new AdminException(400703);
  173. }
  174. $uid = $userInfoData->uid;
  175. } else {
  176. $uid = $wechatInfo['uid'];
  177. }
  178. $userInfo['user_type'] = 'wechat';
  179. $userInfo['add_time'] = time();
  180. $userInfo['uid'] = $uid;
  181. if (!$this->dao->save($userInfo)) {
  182. throw new AdminException(400703);
  183. }
  184. //TODO 这个返回值待完善
  185. return $userInfoData;
  186. }
  187. /**
  188. * 授权后获取用户信息
  189. * @param $openid
  190. * @param $user_type
  191. * @return array|\think\Model|null
  192. * @author 吴汐
  193. * @email 442384644@qq.com
  194. * @date 2023/02/24
  195. */
  196. public function getAuthUserInfo($openid, $user_type)
  197. {
  198. $user = [];
  199. //兼容老用户
  200. $uids = $this->dao->getColumn(['unionid|openid' => $openid, 'is_del' => 0], 'uid,user_type', 'user_type');
  201. if ($uids) {
  202. $uid = $uids[$user_type]['uid'] ?? 0;
  203. if (!$uid) {
  204. $ids = array_column($uids, 'uid');
  205. $uid = $ids[0];
  206. }
  207. /** @var UserServices $userServices */
  208. $userServices = app()->make(UserServices::class);
  209. $user = $userServices->getUserInfo($uid);
  210. }
  211. return $user;
  212. }
  213. /**
  214. * 更新微信用户信息
  215. * @param $event
  216. * @return bool
  217. */
  218. public function wechatUpdata($data)
  219. {
  220. [$uid, $userData] = $data;
  221. /** @var UserServices $userServices */
  222. $userServices = app()->make(UserServices::class);
  223. if (!$userInfo = $userServices->getUserInfo($uid)) {
  224. return false;
  225. }
  226. /** @var LoginServices $loginService */
  227. $loginService = app()->make(LoginServices::class);
  228. $loginService->updateUserInfo($userData, $userInfo);
  229. //更新用户信息
  230. /** @var WechatUserServices $wechatUser */
  231. $wechatUser = app()->make(WechatUserServices::class);
  232. $wechatUserInfo = [];
  233. if (isset($userData['nickname']) && $userData['nickname']) $wechatUserInfo['nickname'] = filter_emoji($userData['nickname'] ?? '');//姓名
  234. if (isset($userData['headimgurl']) && $userData['headimgurl']) $wechatUserInfo['headimgurl'] = $userData['headimgurl'] ?? '';//头像
  235. if (isset($userData['sex']) && $userData['sex']) $wechatUserInfo['sex'] = $userData['gender'] ?? '';//性别
  236. if (isset($userData['language']) && $userData['language']) $wechatUserInfo['language'] = $userData['language'] ?? '';//语言
  237. if (isset($userData['city']) && $userData['city']) $wechatUserInfo['city'] = $userData['city'] ?? '';//城市
  238. if (isset($userData['province']) && $userData['province']) $wechatUserInfo['province'] = $userData['province'] ?? '';//省份
  239. if (isset($userData['country']) && $userData['country']) $wechatUserInfo['country'] = $userData['country'] ?? '';//国家
  240. if (isset($wechatUserInfo['nickname']) || isset($wechatUserInfo['headimgurl'])) $wechatUserInfo['is_complete'] = 1;
  241. if ($wechatUserInfo) {
  242. if (isset($userData['openid']) && $userData['openid'] && false === $wechatUser->update(['uid' => $userInfo['uid'], 'openid' => $userData['openid']], $wechatUserInfo)) {
  243. throw new ApiException(100013);
  244. }
  245. }
  246. return true;
  247. }
  248. /**
  249. * 微信授权成功后
  250. * @param $data
  251. * @return array|mixed|\think\Model|null
  252. * @throws \think\db\exception\DataNotFoundException
  253. * @throws \think\db\exception\DbException
  254. * @throws \think\db\exception\ModelNotFoundException
  255. * @author 吴汐
  256. * @email 442384644@qq.com
  257. * @date 2023/02/24
  258. */
  259. public function wechatOauthAfter($data)
  260. {
  261. if (!$data) throw new ApiException('用户信息获取失败,请刷新页面重试');
  262. [$openid, $wechatInfo, $spreadId, $login_type, $userType] = $data;
  263. /** @var UserServices $userServices */
  264. $userServices = app()->make(UserServices::class);
  265. $spreadInfo = $userServices->getUserInfo((int)$spreadId);
  266. if (!$spreadInfo) {
  267. $spreadId = 0;
  268. $wechatInfo['staff_id'] = 0;
  269. $wechatInfo['agent_id'] = 0;
  270. $wechatInfo['division_id'] = 0;
  271. } else {
  272. $wechatInfo['staff_id'] = $spreadInfo['staff_id'];
  273. $wechatInfo['agent_id'] = $spreadInfo['agent_id'];
  274. $wechatInfo['division_id'] = $spreadInfo['division_id'];
  275. }
  276. if (isset($wechatInfo['subscribe_scene'])) {
  277. unset($wechatInfo['subscribe_scene']);
  278. }
  279. if (isset($wechatInfo['qr_scene'])) {
  280. unset($wechatInfo['qr_scene']);
  281. }
  282. if (isset($wechatInfo['qr_scene_str'])) {
  283. unset($wechatInfo['qr_scene_str']);
  284. }
  285. if ($login_type) {
  286. $wechatInfo['login_type'] = $login_type;
  287. }
  288. if (!isset($wechatInfo['nickname'])) {
  289. if (isset($wechatInfo['phone']) && $wechatInfo['phone']) {
  290. $wechatInfo['nickname'] = substr_replace($wechatInfo['phone'], '****', 3, 4);
  291. } else {
  292. $wechatInfo['nickname'] = 'wx' . rand(100000, 999999);
  293. }
  294. } else {
  295. $wechatInfo['is_complete'] = 1;
  296. $wechatInfo['nickname'] = filter_emoji($wechatInfo['nickname']);
  297. }
  298. $userInfo = [];
  299. $uid = 0;
  300. if (isset($wechatInfo['phone']) && $wechatInfo['phone']) {
  301. $userInfo = $userServices->getOne(['phone' => $wechatInfo['phone'], 'is_del' => 0]);
  302. }
  303. if (!$userInfo) {
  304. if (isset($wechatInfo['unionid']) && $wechatInfo['unionid']) {
  305. $uid = $this->dao->value(['unionid' => $wechatInfo['unionid'], 'is_del' => 0], 'uid');
  306. if ($uid) {
  307. $userInfo = $userServices->getOne(['uid' => $uid, 'is_del' => 0]);
  308. }
  309. } else {
  310. $userInfo = $this->getAuthUserInfo($openid, $userType);
  311. }
  312. }
  313. if ($userInfo) {
  314. $uid = (int)$userInfo['uid'];
  315. $userInfo['new_user'] = 0;
  316. }
  317. $wechatInfo['user_type'] = $userType;
  318. //user表存在和wechat_user表同时存在
  319. if ($userInfo) {
  320. //更新用户表和wechat_user表
  321. //判断该类性用户在wechatUser中是否存在
  322. $wechatUser = $this->dao->getOne(['uid' => $uid, 'user_type' => $userType, 'is_del' => 0]);
  323. /** @var LoginServices $loginService */
  324. $loginService = app()->make(LoginServices::class);
  325. $this->transaction(function () use ($loginService, $wechatInfo, $userInfo, $uid, $userType, $spreadId, $wechatUser) {
  326. $wechatInfo['code'] = $spreadId;
  327. $loginService->updateUserInfo($wechatInfo, $userInfo);
  328. if ($wechatUser) {
  329. if (!$this->dao->update($wechatUser['id'], $wechatInfo, 'id')) {
  330. throw new ApiException(100007);
  331. }
  332. } else {
  333. $wechatInfo['uid'] = $uid;
  334. if (!$this->dao->save($wechatInfo)) {
  335. throw new ApiException(100007);
  336. }
  337. }
  338. });
  339. } else {
  340. //user表没有用户,wechat_user表没有用户创建新用户
  341. //不存在则创建用户
  342. $userInfo = $this->transaction(function () use ($userServices, $wechatInfo, $spreadId, $userType) {
  343. Log::error($wechatInfo);
  344. $userInfo = $userServices->setUserInfo($wechatInfo, (int)$spreadId, $userType);
  345. if (!$userInfo) {
  346. throw new AuthException(410083);
  347. }
  348. $wechatInfo['uid'] = $userInfo->uid;
  349. $wechatInfo['add_time'] = $userInfo->add_time;
  350. if (!$this->dao->save($wechatInfo)) {
  351. throw new AuthException(410083);
  352. }
  353. $userInfo['new_user'] = (int)sys_config('get_avatar', 0);
  354. return $userInfo;
  355. });
  356. }
  357. return $userInfo;
  358. }
  359. /**
  360. * 更新用户信息(同步)
  361. * @param array $openids
  362. * @return array
  363. * @throws \think\db\exception\DataNotFoundException
  364. * @throws \think\db\exception\DbException
  365. * @throws \think\db\exception\ModelNotFoundException
  366. */
  367. public function syncWechatUser(array $openids)
  368. {
  369. if (!$openids) {
  370. return [];
  371. }
  372. $wechatUser = $this->dao->getList([['openid', 'in', $openids]]);
  373. $noBeOpenids = $openids;
  374. if ($wechatUser) {
  375. $beOpenids = array_column($wechatUser, 'openid');
  376. $noBeOpenids = array_diff($openids, $beOpenids);
  377. // $beWechatUserInfo = WechatService::getUserInfo($beOpenids);
  378. if ($beOpenids) {
  379. $data = [];
  380. foreach ($beOpenids as $openid) {
  381. try {
  382. $info = WechatService::getUserInfo($openid);
  383. $info = is_object($info) ? $info->toArray() : $info;
  384. } catch (\Throwable $e) {
  385. $info = [];
  386. }
  387. if (!$info) continue;
  388. $data['subscribe'] = $info['subscribe'] ?? 1;
  389. if ($info['subscribe'] == 1) {
  390. $data['unionid'] = $info['unionid'] ?? '';
  391. $data['nickname'] = $info['nickname'] ?? '';
  392. $data['sex'] = $info['sex'] ?? 0;
  393. $data['language'] = $info['language'] ?? '';
  394. $data['city'] = $info['city'] ?? '';
  395. $data['province'] = $info['province'] ?? '';
  396. $data['country'] = $info['country'] ?? '';
  397. $data['headimgurl'] = $info['headimgurl'] ?? '';
  398. $data['subscribe_time'] = $info['subscribe_time'] ?? '';
  399. $data['groupid'] = $info['groupid'] ?? 0;
  400. $data['remark'] = $info['remark'] ?? '';
  401. $data['tagid_list'] = isset($info['tagid_list']) && $info['tagid_list'] ? implode(',', $info['tagid_list']) : '';
  402. }
  403. $this->dao->update(['openid' => $info['openid']], $data);
  404. }
  405. }
  406. }
  407. return $noBeOpenids;
  408. }
  409. /**
  410. * 用户关注
  411. * @param $openid
  412. * @return bool
  413. */
  414. public function subscribe($openid): bool
  415. {
  416. if (!$this->dao->update($openid, ['subscribe' => 1, 'subscribe_time' => time()], 'openid'))
  417. throw new AdminException(410084);
  418. return true;
  419. }
  420. }