WechatUserServices.php 16 KB

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