LoginLogic.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeshop开源商城系统
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | gitee下载:https://gitee.com/likeshop_gitee
  7. // | github下载:https://github.com/likeshop-github
  8. // | 访问官网:https://www.likeshop.cn
  9. // | 访问社区:https://home.likeshop.cn
  10. // | 访问手册:http://doc.likeshop.cn
  11. // | 微信公众号:likeshop技术社区
  12. // | likeshop系列产品在gitee、github等公开渠道开源版本可免费商用,未经许可不能去除前后端官方版权标识
  13. // | likeshop系列产品收费版本务必购买商业授权,购买去版权授权后,方可去除前后端官方版权标识
  14. // | 禁止对系统程序代码以任何目的,任何形式的再发布
  15. // | likeshop团队版权所有并拥有最终解释权
  16. // +----------------------------------------------------------------------
  17. // | author: likeshop.cn.team
  18. // +----------------------------------------------------------------------
  19. namespace app\api\logic;
  20. use app\admin\logic\user\LevelLogic;
  21. use app\api\server\UserServer;
  22. use app\common\basics\Logic;
  23. use app\common\enum\ClientEnum;
  24. use app\common\server\WeChatServer;
  25. use app\common\server\ConfigServer;
  26. use app\common\model\Client_;
  27. use app\common\model\user\User;
  28. use app\common\model\user\UserAuth;
  29. use app\common\model\Session as SessionModel;
  30. use EasyWeChat\Factory;
  31. use think\facade\Config;
  32. use think\facade\Cache;
  33. use think\facade\Db;
  34. use app\api\cache\TokenCache;
  35. use app\common\logic\AccountLogLogic;
  36. use app\common\model\AccountLog;
  37. use app\common\server\UrlServer;
  38. use think\Exception;
  39. use Requests;
  40. class LoginLogic extends Logic
  41. {
  42. /**
  43. * Notes: 旧用户登录
  44. * @param $post
  45. * @author 段誉(2021/4/19 16:57)
  46. * @return array
  47. * @throws \think\Exception
  48. * @throws \think\db\exception\DataNotFoundException
  49. * @throws \think\db\exception\ModelNotFoundException
  50. * @throws \think\exception\DbException
  51. * @throws \think\exception\PDOException
  52. */
  53. public static function silentLogin($post)
  54. {
  55. try {
  56. //通过code获取微信 openid
  57. $response = self::getWechatResByCode($post);
  58. //通过获取到的openID或unionid获取当前 系统 用户id
  59. $user_id = self::getUserByWechatResponse($response);
  60. } catch (\Exception $e) {
  61. self::$error = $e->getMessage();
  62. return false;
  63. }
  64. if (empty($user_id)) {
  65. //系统中没有用户-调用authlogin接口生成新用户
  66. return [];
  67. } else {
  68. $user_info = UserServer::updateUser($response, Client_::mnp, $user_id);
  69. }
  70. //验证用户信息
  71. $check_res = self::checkUserInfo($user_info);
  72. if (true !== $check_res) {
  73. self::$error = $check_res;
  74. return false;
  75. }
  76. //创建会话
  77. $user_info['token'] = self::createSession($user_info['id'], Client_::mnp);
  78. unset($user_info['id'], $user_info['disable']);
  79. return $user_info->toArray();
  80. }
  81. /**
  82. * Notes: 新用户登录
  83. * @param $post
  84. * @return array|false
  85. * @throws \think\Exception
  86. * @throws \think\db\exception\DataNotFoundException
  87. * @throws \think\db\exception\ModelNotFoundException
  88. * @throws \think\exception\DbException
  89. * @throws \think\exception\PDOException
  90. *@author 段誉(2021/4/19 16:57)
  91. */
  92. public static function authLogin($post)
  93. {
  94. try {
  95. //通过code获取微信 openid
  96. $response = self::getWechatResByCode($post);
  97. $response['headimgurl'] = $post['headimgurl'] ?? '';
  98. $response['nickname'] = $post['nickname'] ?? '';
  99. //通过获取到的openID或unionid获取当前 系统 用户id
  100. $user_id = self::getUserByWechatResponse($response);
  101. } catch (\Exception $e) {
  102. self::$error = $e->getMessage();
  103. return false;
  104. }
  105. if (empty($user_id)) {
  106. $user_info = UserServer::createUser($response, Client_::mnp);
  107. } else {
  108. $user_info = UserServer::updateUser($response, Client_::mnp, $user_id);
  109. }
  110. //验证用户信息
  111. $check_res = self::checkUserInfo($user_info);
  112. if (true !== $check_res) {
  113. self::$error = $check_res;
  114. return false;
  115. }
  116. //创建会话
  117. $user_info['token'] = self::createSession($user_info['id'], Client_::mnp);
  118. unset($user_info['id'], $user_info['disable']);
  119. return $user_info->toArray();
  120. }
  121. /**
  122. * Notes: 根据code 获取微信信息(openid, unionid)
  123. * @param $post
  124. * @author 段誉(2021/4/19 16:52)
  125. * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
  126. * @throws Exception
  127. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  128. */
  129. public static function getWechatResByCode($post)
  130. {
  131. $config = WeChatServer::getMnpConfig();
  132. $app = Factory::miniProgram($config);
  133. $response = $app->auth->session($post['code']);
  134. if (empty($response['openid'])) {
  135. throw new \think\Exception('获取openID失败');
  136. }
  137. return $response;
  138. }
  139. public static function getWechatOaResByCode($post)
  140. {
  141. $config = WeChatServer::getOaConfig();
  142. $app = Factory::officialAccount($config);
  143. $response = $app
  144. ->oauth
  145. ->scopes(['snsapi_userinfo'])
  146. ->getAccessToken($post['code']);
  147. if (empty($response['openid'])) {
  148. throw new \think\Exception('获取openID失败');
  149. }
  150. return $response;
  151. }
  152. /**
  153. * Notes: 根据微信返回信息查询当前用户id
  154. * @param $response
  155. * @author 段誉(2021/4/19 16:52)
  156. * @return mixed
  157. */
  158. public static function getUserByWechatResponse($response)
  159. {
  160. $user_id = UserAuth::alias('au')
  161. ->join('user u', 'au.user_id=u.id')
  162. ->where(['u.del' => 0])
  163. ->where(function ($query) use ($response) {
  164. $query->whereOr(['au.openid' => $response['openid']]);
  165. if(isset($response['unionid']) && !empty($response['unionid'])){
  166. $query->whereOr(['au.unionid' => $response['unionid']]);
  167. }
  168. })
  169. ->value('user_id');
  170. return $user_id;
  171. }
  172. /**
  173. * Notes: 检查用户信息
  174. * @param $user_info
  175. * @author 段誉(2021/4/19 16:54)
  176. * @return bool|string
  177. */
  178. public static function checkUserInfo($user_info)
  179. {
  180. if (empty($user_info)) {
  181. return '登录失败:user';
  182. }
  183. if ($user_info['disable']) {
  184. return '该用户被禁用';
  185. }
  186. return true;
  187. }
  188. /**
  189. * 创建会话
  190. * @param $user_id
  191. * @param $client
  192. * @return string
  193. * @throws \think\Exception
  194. * @throws \think\db\exception\DataNotFoundException
  195. * @throws \think\db\exception\ModelNotFoundException
  196. * @throws \think\exception\DbException
  197. * @throws \think\exception\PDOException
  198. */
  199. public static function createSession($user_id, $client)
  200. {
  201. //清除之前缓存
  202. $token = SessionModel::where(['user_id' => $user_id, 'client' => $client])
  203. ->value('token');
  204. if($token) {
  205. Cache::delete($token);
  206. }
  207. $result = SessionModel::where(['user_id' => $user_id, 'client' => $client])
  208. ->findOrEmpty();
  209. $time = time();
  210. $expire_time = $time + Config::get('project.token_expire_time');
  211. // 新token
  212. $token = md5($user_id . $client . $time);
  213. $data = [
  214. 'user_id' => $user_id,
  215. 'token' => $token,
  216. 'client' => $client,
  217. 'update_time' => $time,
  218. 'expire_time' => $expire_time,
  219. ];
  220. if ($result->isEmpty()) {
  221. SessionModel::create($data);
  222. } else {
  223. SessionModel::where(['user_id' => $user_id, 'client' => $client])
  224. ->update($data);
  225. }
  226. //更新登录信息
  227. $login_ip = $ip = request()->ip();
  228. User::where(['id' => $user_id])
  229. ->update(['login_time' => $time, 'login_ip' => $login_ip]);
  230. // 获取最新的用户信息
  231. $user_info = User::alias('u')
  232. ->join('session s', 'u.id=s.user_id')
  233. ->where(['s.token' => $token])
  234. ->field('u.*,s.token,s.client')
  235. ->find();
  236. $user_info = $user_info ? $user_info->toArray() : [];
  237. //创建新的缓存
  238. $ttl = 0 + Config::get('project.token_expire_time');
  239. Cache::set($token, $user_info, $ttl);
  240. return $token;
  241. }
  242. public static function register($post)
  243. {
  244. Db::startTrans();
  245. try{
  246. $time = time();
  247. $salt = substr(md5($time . $post['mobile']), 0, 4);//随机4位密码盐
  248. $password = create_password($post['password'], $salt);//生成密码
  249. $user_data = [
  250. 'avatar' => ConfigServer::get('website', 'user_image'),
  251. 'sn' => create_user_sn(),
  252. 'mobile' => $post['mobile'],
  253. 'salt' => $salt,
  254. 'password' => $password,
  255. 'create_time' => $time,
  256. 'distribution_code' => generate_invite_code(),//分销邀请码
  257. 'is_distribution' => DistributionLogic::isDistributionMember(),//是否为分销会员
  258. 'client' => $post['client']
  259. ];
  260. $user_data['nickname'] = '用户'.$user_data['sn'];
  261. $user = User::create($user_data);
  262. $token = self::createSession($user->id, $post['client']);
  263. //生成会员分销扩展表
  264. DistributionLogic::createUserDistribution($user->id);
  265. // 生成分销基础信息表
  266. \app\common\logic\DistributionLogic::add($user->id);
  267. //注册赠送
  268. self::registerAward($user->id);
  269. Db::commit();
  270. return ['token' => $token];
  271. }catch(\Exception $e){
  272. Db::rollback();
  273. self::$error = $e->getMessage();
  274. return false;
  275. }
  276. }
  277. public static function registerAward($user_id){
  278. // $register_award_integral_status = ConfigServer::get('marketing','register_award_integral_status',0);
  279. $register_award_coupon_status = ConfigServer::get('marketing','register_award_coupon_status',0);
  280. //赠送积分
  281. // if($register_award_integral_status){
  282. // $register_award_integral = ConfigServer::get('marketing','register_award_integral',0);
  283. // //赠送的积分
  284. // if($register_award_integral > 0){
  285. // $user = User::findOrEmpty($user_id);
  286. // $user->user_integral += $register_award_integral;
  287. // $user->save();
  288. // AccountLogLogic::AccountRecord($user_id,$register_award_integral,1,AccountLog::register_add_integral,'');
  289. // }
  290. // }
  291. //注册账号,首次进入首页时领取优惠券
  292. $register_award_coupon = ConfigServer::get('marketing','register_award_coupon','');
  293. if($register_award_coupon_status && $register_award_coupon){
  294. Cache::tag('register_coupon')->set('register_coupon_'.$user_id,$register_award_coupon);
  295. }
  296. // 赠送成长值
  297. $register_growth = ConfigServer::get('register', 'growth', 0);
  298. if($register_growth > 0) {
  299. $user = User::findOrEmpty($user_id);
  300. $user->user_growth += $register_growth;
  301. $user->save();
  302. AccountLogLogic::AccountRecord($user_id,$register_growth,1,AccountLog::register_give_growth,'');
  303. // 更新用户会员等级
  304. LevelLogic::updateUserLevel([$user]);
  305. }
  306. }
  307. /**
  308. * 手机号密码登录
  309. */
  310. public static function mpLogin($post)
  311. {
  312. $user = User::field(['id', 'nickname', 'avatar', 'level', 'disable', 'distribution_code'])
  313. ->where(['mobile' => $post['mobile']])
  314. ->findOrEmpty()->toArray();
  315. $user['token'] = self::createSession($user['id'], $post['client']);
  316. if (empty($user['avatar'])) {
  317. $user['avatar'] = UrlServer::getFileUrl(ConfigServer::get('website', 'user_image'));
  318. } else {
  319. $user['avatar'] = UrlServer::getFileUrl($user['avatar']);
  320. }
  321. return $user;
  322. }
  323. /**
  324. * 获取code的url
  325. * @param $url
  326. * @return string
  327. */
  328. public static function codeUrl($url)
  329. {
  330. $config = WeChatServer::getOaConfig();
  331. $app = Factory::officialAccount($config);
  332. $response = $app
  333. ->oauth
  334. ->scopes(['snsapi_userinfo'])
  335. ->redirect($url)
  336. ->getTargetUrl();
  337. return $response;
  338. }
  339. /***
  340. * Desc: 微信公众号登录
  341. * @param $post
  342. * @return array|string
  343. * @throws Exception
  344. * @throws \think\db\exception\DataNotFoundException
  345. * @throws \think\db\exception\ModelNotFoundException
  346. * @throws \think\exception\DbException
  347. * @throws \think\exception\PDOException
  348. */
  349. public static function oaLogin($post)
  350. {
  351. //微信调用
  352. try {
  353. $config = WeChatServer::getOaConfig();
  354. $app = Factory::officialAccount($config);
  355. $response = $app
  356. ->oauth
  357. ->scopes(['snsapi_userinfo'])
  358. ->getAccessToken($post['code']);
  359. if (!isset($response['openid']) || empty($response['openid'])) {
  360. throw new Exception();
  361. }
  362. $user = $app->oauth->user($response);
  363. $user = $user->getOriginal();
  364. } catch (Exception $e) {
  365. return $e->getMessage();
  366. }
  367. //添加或更新用户
  368. $user_id = UserAuth::alias('au')
  369. ->join('user u', 'au.user_id=u.id')
  370. ->where(['u.del' => 0])
  371. ->where(function ($query) use ($user) {
  372. $query->whereOr(['au.openid' => $user['openid']]);
  373. if(isset($user['unionid']) && !empty($user['unionid'])){
  374. $query->whereOr(['au.unionid' => $user['unionid']]);
  375. }
  376. })
  377. ->value('user_id');
  378. if (empty($user_id)) {
  379. $user_info = UserServer::createUser($user, Client_::oa);
  380. } else {
  381. $user_info = UserServer::updateUser($user, Client_::oa, $user_id);
  382. }
  383. if (empty($user_info)) {
  384. return '登录失败:user';
  385. }
  386. if ($user_info['disable']) {
  387. return '该用户被禁用';
  388. }
  389. //创建会话
  390. $user_info['token'] = self::createSession($user_info['id'], Client_::oa);
  391. unset($user_info['id']);
  392. unset($user_info['disable']);
  393. return $user_info->toArray();
  394. // return $user_info;
  395. }
  396. /***
  397. * app微信登录
  398. * @param $post
  399. * @return array|\PDOStatement|string|\think\Model|null
  400. * @throws Exception
  401. * @throws \think\db\exception\DataNotFoundException
  402. * @throws \think\db\exception\ModelNotFoundException
  403. * @throws \think\exception\DbException
  404. * @throws \think\exception\PDOException
  405. */
  406. public static function uinAppLogin($post)
  407. {
  408. //微信调用
  409. try {
  410. if (empty($post['openid']) || empty($post['access_token']) || empty($post['client'])){
  411. throw new Exception('参数缺失');
  412. }
  413. //sdk不支持app登录,直接调用微信接口
  414. $requests = Requests::get('https://api.weixin.qq.com/sns/userinfo?openid=' . 'openid=' . $post['openid'] . '&access_token=' . $post['access_token']);
  415. $user = json_decode($requests->body, true);
  416. } catch (Exception $e) {
  417. return $e->getMessage();
  418. }
  419. //添加或更新用户
  420. $user_id = UserAuth::alias('au')->join('user u', 'au.user_id=u.id')
  421. ->where(['u.del' => 0])
  422. ->where(function ($query) use ($user) {
  423. $query->whereOr(['au.openid' => $user['openid']])
  424. ->whereOr(['au.unionid' => $user['unionid']]);
  425. })
  426. ->value('user_id');
  427. if (empty($user_id)) {
  428. $user_info = UserServer::createUser($user, $post['client']);
  429. } else {
  430. $user_info = UserServer::updateUser($user, $post['client'], $user_id);
  431. }
  432. if (empty($user_info)) {
  433. return '登录失败:user';
  434. }
  435. if ($user_info['disable']) {
  436. return '该用户被禁用';
  437. }
  438. //创建会话
  439. $user_info['token'] = self::createSession($user_info['id'], $post['client']);
  440. unset($user_info['id']);
  441. unset($user_info['disable']);
  442. return $user_info;
  443. }
  444. //手机号密码登录
  445. public static function login($post)
  446. {
  447. $user_info = User::field(['id', 'nickname', 'avatar', 'level', 'disable', 'distribution_code'])
  448. ->where(['account|mobile' => $post['mobile']])
  449. ->find()->toArray();
  450. $user_info['token'] = self::createSession($user_info['id'], $post['client']);
  451. if (empty($user_info['avatar'])) {
  452. $user_info['avatar'] = UrlServer::getFileUrl(ConfigServer::get('website', 'user_image'));
  453. } else {
  454. $user_info['avatar'] = UrlServer::getFileUrl($user_info['avatar']);
  455. }
  456. return $user_info;
  457. }
  458. //退出登录
  459. public static function logout($user_id, $client)
  460. {
  461. return self::expirationSession($user_id, $client);
  462. }
  463. /**
  464. * 设置会话过期
  465. * @param $user_id
  466. * @param $client
  467. * @throws \think\Exception
  468. * @throws \think\exception\PDOException
  469. */
  470. public static function expirationSession($user_id, $client)
  471. {
  472. $time = time();
  473. $token = Db::name('session')
  474. ->where(['user_id' => $user_id, 'client' => $client])
  475. ->value('token');
  476. $token_cache = new TokenCache($token);
  477. $token_cache->del();
  478. return Db::name('session')
  479. ->where(['user_id' => $user_id, 'client' => $client])
  480. ->update(['update_time' => $time, 'expire_time' => $time]);
  481. }
  482. /**
  483. * @notes PC扫码登录, 二维码链接
  484. * @return false|string
  485. * @author 段誉
  486. * @date 2021/10/29 11:47
  487. */
  488. public static function scanCode()
  489. {
  490. try {
  491. $config = WeChatServer::getOpWebConfig();
  492. $appid = $config['app_id'];
  493. $domain = request()->domain();
  494. $url = $domain.'/pc/account/login';
  495. $redirect_uri = UrlEncode($url);
  496. $state = MD5(time().rand(10000, 99999));
  497. cache($state, $state, 600); //缓存600
  498. $url = "https://open.weixin.qq.com/connect/qrconnect?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_login&state=$state#wechat_redirect";
  499. return $url;
  500. } catch (\Exception $e) {
  501. self::$error = $e->getMessage();
  502. return false;
  503. }
  504. }
  505. /**
  506. * @notes PC端扫码登录
  507. * @param $params
  508. * @return array|false
  509. * @author 段誉
  510. * @date 2021/10/29 18:00
  511. */
  512. public static function scanLogin($params)
  513. {
  514. try {
  515. //验证参数
  516. if (empty($params['code']) || empty($params['state'])) {
  517. throw new \Exception('参数缺失');
  518. }
  519. //验证state
  520. $state = cache($params['state']);
  521. if (empty($state)) {
  522. throw new \Exception('二维码已失效或不存在,请重新扫码');
  523. }
  524. $config = WeChatServer::getOpWebConfig();
  525. $appid = $config['app_id'];
  526. $secret = $config['secret'];
  527. //通过code获取access_token,openid,unionid
  528. $requests = Requests::get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $params['code'] . '&grant_type=authorization_code');
  529. $user_auth = json_decode($requests->body, true);
  530. if (empty($user_auth['openid']) || empty($user_auth['access_token'])) {
  531. throw new \think\Exception('获取openID失败');
  532. }
  533. //获取用户信息
  534. $response = Requests::get('https://api.weixin.qq.com/sns/userinfo?access_token='. $user_auth['access_token'] . '&openid=' . $user_auth['openid']);
  535. $response = json_decode($response->body, true);
  536. //在系统中查找openid和unionid是否存在
  537. $user_id = self::getUserByWechatResponse($response);
  538. if (empty($user_id)) {
  539. $user_info = UserServer::createUser($response,ClientEnum::pc);
  540. } else {
  541. $user_info = UserServer::updateUser($response, ClientEnum::pc, $user_id);
  542. }
  543. //验证用户信息
  544. $check_res = self::checkUserInfo($user_info);
  545. if (true !== $check_res) {
  546. throw new \Exception($check_res);
  547. }
  548. //创建会话
  549. $user_info['token'] = self::createSession($user_info['id'], ClientEnum::pc);
  550. unset($user_info['id']);
  551. unset($user_info['disable']);
  552. return $user_info->toArray();
  553. } catch (\Exception $e) {
  554. self::$error = $e->getMessage();
  555. return false;
  556. }
  557. }
  558. /**
  559. * @notes 更新用户头像昵称
  560. * @param $post
  561. * @param $user_id
  562. * @return bool
  563. * @throws \think\db\exception\DbException
  564. * @author ljj
  565. * @date 2023/2/2 6:23 下午
  566. */
  567. public static function updateUser($post,$user_id)
  568. {
  569. // $user = Db::name('user')->where(['id'=>$user_id])->find();
  570. // if ($user['is_new_user'] == 0) {
  571. // return self::dataError('非新用户无法使用此接口更新用户信息');
  572. // }
  573. Db::name('user')->where(['id'=>$user_id])->update(['nickname'=>$post['nickname'],'avatar'=>UrlServer::setFileUrl($post['avatar']),'is_new_user'=>0]);
  574. return true;
  575. }
  576. /**
  577. * @notes 小程序端绑定微信
  578. * @param array $params
  579. * @return false
  580. * @author lbzy
  581. * @datetime 2023-10-30 11:18:27
  582. */
  583. public function mnpAuthLogin(array $params)
  584. {
  585. try {
  586. //通过code获取微信openid
  587. $response = self::getWechatResByCode($params);
  588. $where = [
  589. [ 'openid', '=', $response['openid'] ],
  590. ];
  591. $userAuth = UserAuth::where($where)->findOrEmpty();
  592. if (isset($userAuth['id'])) {
  593. if ($userAuth['user_id'] == $params['user_id']) {
  594. return true;
  595. }
  596. throw new \Exception('该微信已绑定其他用户');
  597. }
  598. UserAuth::create([
  599. 'user_id' => $params['user_id'],
  600. 'openid' => $response['openid'],
  601. 'create_time' => time(),
  602. 'unionid' => $response['unionid'] ?? '',
  603. 'client' => ClientEnum::mnp,
  604. ]);
  605. return true;
  606. } catch (\Exception $e) {
  607. self::$error = $e->getMessage();
  608. return false;
  609. }
  610. }
  611. /**
  612. * @notes 公众号端绑定微信
  613. * @param array $params
  614. * @return false
  615. * @author lbzy
  616. * @datetime 2023-10-30 11:18:20
  617. */
  618. public function oaAuthLogin(array $params)
  619. {
  620. try {
  621. //通过code获取微信openid
  622. $response = self::getWechatOaResByCode($params);
  623. $where = [
  624. [ 'openid', '=', $response['openid'] ],
  625. ];
  626. $userAuth = UserAuth::where($where)->findOrEmpty();
  627. if (isset($userAuth['id'])) {
  628. if ($userAuth['user_id'] == $params['user_id']) {
  629. return true;
  630. }
  631. throw new \Exception('该微信已绑定其他用户');
  632. }
  633. UserAuth::create([
  634. 'user_id' => $params['user_id'],
  635. 'openid' => $response['openid'],
  636. 'create_time' => time(),
  637. 'unionid' => $response['unionid'] ?? '',
  638. 'client' => ClientEnum::oa,
  639. ]);
  640. return true;
  641. } catch (\Exception $e) {
  642. self::$error = $e->getMessage();
  643. return false;
  644. }
  645. }
  646. }