WechatUserServices.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. */
  188. public function getAuthUserInfo($openid, $user_type)
  189. {
  190. $user = [];
  191. //兼容老用户
  192. $uids = $this->dao->getColumn(['unionid|openid' => $openid, 'is_del' => 0], 'uid,user_type', 'user_type');
  193. if ($uids) {
  194. $uid = $uids[$user_type]['uid'] ?? 0;
  195. if (!$uid) {
  196. $ids = array_column($uids, 'uid');
  197. $uid = $ids[0];
  198. }
  199. /** @var UserServices $userServices */
  200. $userServices = app()->make(UserServices::class);
  201. $user = $userServices->getUserInfo($uid);
  202. }
  203. return $user;
  204. }
  205. /**
  206. * 更新微信用户信息
  207. * @param $event
  208. * @return bool
  209. */
  210. public function wechatUpdata($data)
  211. {
  212. [$uid, $userData] = $data;
  213. /** @var UserServices $userServices */
  214. $userServices = app()->make(UserServices::class);
  215. if (!$userInfo = $userServices->getUserInfo($uid)) {
  216. return false;
  217. }
  218. /** @var LoginServices $loginService */
  219. $loginService = app()->make(LoginServices::class);
  220. $loginService->updateUserInfo($userData, $userInfo);
  221. //更新用户信息
  222. /** @var WechatUserServices $wechatUser */
  223. $wechatUser = app()->make(WechatUserServices::class);
  224. $wechatUserInfo = [];
  225. if (isset($userData['nickname']) && $userData['nickname']) $wechatUserInfo['nickname'] = filter_emoji($userData['nickname'] ?? '');//姓名
  226. if (isset($userData['headimgurl']) && $userData['headimgurl']) $wechatUserInfo['headimgurl'] = $userData['avatarUrl'] ?? '';//头像
  227. if (isset($userData['sex']) && $userData['sex']) $wechatUserInfo['sex'] = $userData['gender'] ?? '';//性别
  228. if (isset($userData['language']) && $userData['language']) $wechatUserInfo['language'] = $userData['language'] ?? '';//语言
  229. if (isset($userData['city']) && $userData['city']) $wechatUserInfo['city'] = $userData['city'] ?? '';//城市
  230. if (isset($userData['province']) && $userData['province']) $wechatUserInfo['province'] = $userData['province'] ?? '';//省份
  231. if (isset($userData['country']) && $userData['country']) $wechatUserInfo['country'] = $userData['country'] ?? '';//国家
  232. if (isset($wechatUserInfo['nickname']) || isset($wechatUserInfo['headimgurl'])) $wechatUserInfo['is_complete'] = 1;
  233. if ($wechatUserInfo) {
  234. if (isset($userData['openid']) && $userData['openid'] && false === $wechatUser->update(['uid' => $userInfo['uid'], 'openid' => $userData['openid']], $wechatUserInfo)) {
  235. throw new ApiException(100013);
  236. }
  237. }
  238. return true;
  239. }
  240. /**
  241. * 微信授权成功后
  242. * @param $event
  243. * @throws \think\db\exception\DataNotFoundException
  244. * @throws \think\db\exception\ModelNotFoundException
  245. * @throws \think\exception\DbException
  246. */
  247. public function wechatOauthAfter(array $data)
  248. {
  249. [$openid, $wechatInfo, $spreadId, $login_type, $userType] = $data;
  250. /** @var UserServices $userServices */
  251. $userServices = app()->make(UserServices::class);
  252. $spreadInfo = $userServices->getUserInfo((int)$spreadId);
  253. if (!$spreadInfo) {
  254. $spreadId = 0;
  255. $wechatInfo['staff_id'] = 0;
  256. $wechatInfo['agent_id'] = 0;
  257. $wechatInfo['division_id'] = 0;
  258. } else {
  259. $wechatInfo['staff_id'] = $spreadInfo['staff_id'];
  260. $wechatInfo['agent_id'] = $spreadInfo['agent_id'];
  261. $wechatInfo['division_id'] = $spreadInfo['division_id'];
  262. }
  263. if (isset($wechatInfo['subscribe_scene'])) {
  264. unset($wechatInfo['subscribe_scene']);
  265. }
  266. if (isset($wechatInfo['qr_scene'])) {
  267. unset($wechatInfo['qr_scene']);
  268. }
  269. if (isset($wechatInfo['qr_scene_str'])) {
  270. unset($wechatInfo['qr_scene_str']);
  271. }
  272. if ($login_type) {
  273. $wechatInfo['login_type'] = $login_type;
  274. }
  275. if (!isset($wechatInfo['nickname'])) {
  276. if (isset($wechatInfo['phone']) && $wechatInfo['phone']) {
  277. $wechatInfo['nickname'] = substr_replace($wechatInfo['phone'], '****', 3, 4);
  278. } else {
  279. $wechatInfo['nickname'] = 'wx' . rand(100000, 999999);
  280. }
  281. } else {
  282. $wechatInfo['is_complete'] = 1;
  283. $wechatInfo['nickname'] = filter_emoji($wechatInfo['nickname']);
  284. }
  285. $userInfo = [];
  286. $uid = 0;
  287. if (isset($wechatInfo['phone']) && $wechatInfo['phone']) {
  288. $userInfo = $userServices->getOne(['phone' => $wechatInfo['phone'], 'is_del' => 0]);
  289. }
  290. if (!$userInfo) {
  291. if (isset($wechatInfo['unionid']) && $wechatInfo['unionid']) {
  292. $uid = $this->dao->value(['unionid' => $wechatInfo['unionid'], 'is_del' => 0], 'uid');
  293. if ($uid) {
  294. $userInfo = $userServices->getOne(['uid' => $uid, 'is_del' => 0]);
  295. }
  296. } else {
  297. $userInfo = $this->getAuthUserInfo($openid, $userType);
  298. }
  299. }
  300. if ($userInfo) {
  301. $uid = (int)$userInfo['uid'];
  302. $userInfo['new_user'] = 0;
  303. }
  304. $wechatInfo['user_type'] = $userType;
  305. //user表存在和wechat_user表同时存在
  306. if ($userInfo) {
  307. //更新用户表和wechat_user表
  308. //判断该类性用户在wechatUser中是否存在
  309. $wechatUser = $this->dao->getOne(['uid' => $uid, 'user_type' => $userType, 'is_del' => 0]);
  310. /** @var LoginServices $loginService */
  311. $loginService = app()->make(LoginServices::class);
  312. $this->transaction(function () use ($loginService, $wechatInfo, $userInfo, $uid, $userType, $spreadId, $wechatUser) {
  313. $wechatInfo['code'] = $spreadId;
  314. $loginService->updateUserInfo($wechatInfo, $userInfo);
  315. if ($wechatUser) {
  316. if (!$this->dao->update($wechatUser['id'], $wechatInfo, 'id')) {
  317. throw new ApiException(100007);
  318. }
  319. } else {
  320. $wechatInfo['uid'] = $uid;
  321. if (!$this->dao->save($wechatInfo)) {
  322. throw new ApiException(100007);
  323. }
  324. }
  325. });
  326. } else {
  327. //user表没有用户,wechat_user表没有用户创建新用户
  328. //不存在则创建用户
  329. $userInfo = $this->transaction(function () use ($userServices, $wechatInfo, $spreadId, $userType) {
  330. Log::error($wechatInfo);
  331. $userInfo = $userServices->setUserInfo($wechatInfo, (int)$spreadId, $userType);
  332. if (!$userInfo) {
  333. throw new AuthException(410083);
  334. }
  335. $wechatInfo['uid'] = $userInfo->uid;
  336. $wechatInfo['add_time'] = $userInfo->add_time;
  337. if (!$this->dao->save($wechatInfo)) {
  338. throw new AuthException(410083);
  339. }
  340. $userInfo['new_user'] = (int)sys_config('get_avatar', 0);
  341. return $userInfo;
  342. });
  343. }
  344. return $userInfo;
  345. }
  346. /**
  347. * 更新用户信息(同步)
  348. * @param array $openids
  349. * @return array
  350. * @throws \think\db\exception\DataNotFoundException
  351. * @throws \think\db\exception\DbException
  352. * @throws \think\db\exception\ModelNotFoundException
  353. */
  354. public function syncWechatUser(array $openids)
  355. {
  356. if (!$openids) {
  357. return [];
  358. }
  359. $wechatUser = $this->dao->getList([['openid', 'in', $openids]]);
  360. $noBeOpenids = $openids;
  361. if ($wechatUser) {
  362. $beOpenids = array_column($wechatUser, 'openid');
  363. $noBeOpenids = array_diff($openids, $beOpenids);
  364. // $beWechatUserInfo = WechatService::getUserInfo($beOpenids);
  365. if ($beOpenids) {
  366. $data = [];
  367. foreach ($beOpenids as $openid) {
  368. try {
  369. $info = WechatService::getUserInfo($openid);
  370. $info = is_object($info) ? $info->toArray() : $info;
  371. } catch (\Throwable $e) {
  372. $info = [];
  373. }
  374. if (!$info) continue;
  375. $data['subscribe'] = $info['subscribe'] ?? 1;
  376. if ($info['subscribe'] == 1) {
  377. $data['unionid'] = $info['unionid'] ?? '';
  378. $data['nickname'] = $info['nickname'] ?? '';
  379. $data['sex'] = $info['sex'] ?? 0;
  380. $data['language'] = $info['language'] ?? '';
  381. $data['city'] = $info['city'] ?? '';
  382. $data['province'] = $info['province'] ?? '';
  383. $data['country'] = $info['country'] ?? '';
  384. $data['headimgurl'] = $info['headimgurl'] ?? '';
  385. $data['subscribe_time'] = $info['subscribe_time'] ?? '';
  386. $data['groupid'] = $info['groupid'] ?? 0;
  387. $data['remark'] = $info['remark'] ?? '';
  388. $data['tagid_list'] = isset($info['tagid_list']) && $info['tagid_list'] ? implode(',', $info['tagid_list']) : '';
  389. }
  390. $this->dao->update(['openid' => $info['openid']], $data);
  391. }
  392. }
  393. }
  394. return $noBeOpenids;
  395. }
  396. /**
  397. * 用户关注
  398. * @param $openid
  399. * @return bool
  400. */
  401. public function subscribe($openid): bool
  402. {
  403. if (!$this->dao->update($openid, ['subscribe' => 1, 'subscribe_time' => time()], 'openid'))
  404. throw new AdminException(410084);
  405. return true;
  406. }
  407. }