WechatUserServices.php 15 KB

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