WechatUserServices.php 16 KB

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