WechatUserServices.php 15 KB

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