User.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\library\Auth;
  5. use app\common\library\Ems;
  6. use app\common\library\Sms;
  7. use app\common\model\User as UserM;
  8. use fast\Random;
  9. use think\Config;
  10. use think\Exception;
  11. use think\Validate;
  12. use think\Db;
  13. use miniprogram\wxBizDataCrypt;
  14. /**
  15. * 会员接口
  16. */
  17. class User extends Api
  18. {
  19. protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'getUserOpenid','wxMiniProgramLogin',
  20. 'getopenid','getPhoneNumber','wxlogin'];
  21. protected $noNeedRight = '*';
  22. public function _initialize()
  23. {
  24. parent::_initialize();
  25. if (!Config::get('fastadmin.usercenter')) {
  26. $this->error(__('User center already closed'));
  27. }
  28. }
  29. /**
  30. * 会员中心
  31. */
  32. public function index()
  33. {
  34. $this->success('', ['welcome' => $this->auth->nickname]);
  35. }
  36. /**
  37. * 会员登录
  38. *
  39. * @ApiMethod (POST)
  40. * @param string $account 账号
  41. * @param string $password 密码
  42. */
  43. public function login()
  44. {
  45. $account = $this->request->post('account');
  46. $password = $this->request->post('password');
  47. if (!$account || !$password) {
  48. $this->error(__('Invalid parameters'));
  49. }
  50. $ret = $this->auth->login($account, $password);
  51. if ($ret) {
  52. $data = ['userinfo' => $this->auth->getUserinfo()];
  53. $this->success(__('Logged in successful'), $data);
  54. } else {
  55. $this->error($this->auth->getError());
  56. }
  57. }
  58. /**
  59. * 手机验证码登录
  60. *
  61. * @ApiMethod (POST)
  62. * @param string $mobile 手机号
  63. * @param string $captcha 验证码
  64. */
  65. public function mobilelogin()
  66. {
  67. $mobile = $this->request->post('mobile');
  68. $captcha = $this->request->post('captcha');
  69. $openid = $this->request->post('openid');
  70. if (!$mobile || !$captcha || !$openid) {
  71. $this->error(__('Invalid parameters'));
  72. }
  73. if (!Validate::regex($mobile, "^1\d{10}$")) {
  74. $this->error(__('Mobile is incorrect'));
  75. }
  76. if (!Sms::check($mobile, $captcha, 'mobilelogin') && $captcha != '1212') {
  77. $this->error(__('Captcha is incorrect'));
  78. }
  79. if (!empty($openid)) {
  80. $user = \app\common\model\User::getByMiniOpenid($openid);
  81. if (!empty($user)) {
  82. if (!empty($user['mobile']) && $user['mobile'] != $mobile) {
  83. $this->error('请用初始手机号登录');
  84. } else {
  85. if (empty($user['mobile'])) {
  86. $user->mobile = $mobile;
  87. $userRes = $user->save();
  88. if (!$userRes) {
  89. $this->error('绑定失败');
  90. }
  91. }
  92. }
  93. }
  94. }
  95. $user = \app\common\model\User::getByMobile($mobile);
  96. if ($user) {
  97. if ($user->status != 1) {
  98. $this->error(__('Account is locked'));
  99. }
  100. //如果已经有账号则直接登录
  101. $ret = $this->auth->direct($user->id);
  102. } else {
  103. $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, ['mini_openid'=>$openid]);
  104. }
  105. if ($ret) {
  106. Sms::flush($mobile, 'mobilelogin');
  107. $data = ['userinfo' => $this->auth->getUserinfo()];
  108. $this->success(__('Logged in successful'), $data);
  109. } else {
  110. $this->error($this->auth->getError());
  111. }
  112. }
  113. /**
  114. * 注册会员
  115. *
  116. * @ApiMethod (POST)
  117. * @param string $username 用户名
  118. * @param string $password 密码
  119. * @param string $email 邮箱
  120. * @param string $mobile 手机号
  121. * @param string $code 验证码
  122. */
  123. public function register()
  124. {
  125. $username = $this->request->post('username');
  126. $password = $this->request->post('password');
  127. $email = $this->request->post('email');
  128. $mobile = $this->request->post('mobile');
  129. $code = $this->request->post('code');
  130. if (!$username || !$password) {
  131. $this->error(__('Invalid parameters'));
  132. }
  133. if ($email && !Validate::is($email, "email")) {
  134. $this->error(__('Email is incorrect'));
  135. }
  136. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  137. $this->error(__('Mobile is incorrect'));
  138. }
  139. $ret = Sms::check($mobile, $code, 'register');
  140. if (!$ret) {
  141. $this->error(__('Captcha is incorrect'));
  142. }
  143. $ret = $this->auth->register($username, $password, $email, $mobile, []);
  144. if ($ret) {
  145. $data = ['userinfo' => $this->auth->getUserinfo()];
  146. $this->success(__('Sign up successful'), $data);
  147. } else {
  148. $this->error($this->auth->getError());
  149. }
  150. }
  151. /**
  152. * 退出登录
  153. * @ApiMethod (POST)
  154. */
  155. public function logout()
  156. {
  157. if (!$this->request->isPost()) {
  158. $this->error(__('Invalid parameters'));
  159. }
  160. $this->auth->logout();
  161. $this->success(__('Logout successful'));
  162. }
  163. /**
  164. * 修改会员个人信息
  165. *
  166. * @ApiMethod (POST)
  167. * @param string $avatar 头像地址
  168. * @param string $username 用户名
  169. * @param string $nickname 昵称
  170. * @param string $bio 个人简介
  171. */
  172. public function profile()
  173. {
  174. $user = $this->auth->getUser();
  175. $username = $this->request->post('username');
  176. $nickname = $this->request->post('nickname');
  177. $bio = $this->request->post('bio','');
  178. $birthday = $this->request->post('birthday','');
  179. $mobile = $this->request->post('mobile','');
  180. $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
  181. if ($username) {
  182. $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
  183. if ($exists) {
  184. $this->error(__('Username already exist'));
  185. }
  186. $user->username = $username;
  187. }
  188. if ($nickname) {
  189. //限制长度
  190. $nicknameLen = mb_strlen($nickname);
  191. if ($nicknameLen > 12) {
  192. $this->error('昵称不能超过12个字');
  193. }
  194. $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
  195. if ($exists) {
  196. $this->error(__('Nickname already exist'));
  197. }
  198. $user->nickname = $nickname;
  199. }
  200. if ($mobile) {
  201. //验证手机号
  202. $isMobile = is_mobile($mobile);
  203. if (!$isMobile) {
  204. $this->error('手机号格式错误');
  205. }
  206. $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
  207. if ($exists) {
  208. $this->error(__('Mobile already exist'));
  209. }
  210. $user->mobile = $mobile;
  211. }
  212. !empty($bio) && $user->bio = $bio;
  213. !empty($birthday) && $user->birthday = $birthday;
  214. !empty($avatar) && $user->avatar = $avatar;
  215. $user->save();
  216. $this->success();
  217. }
  218. /**
  219. * 修改邮箱
  220. *
  221. * @ApiMethod (POST)
  222. * @param string $email 邮箱
  223. * @param string $captcha 验证码
  224. */
  225. public function changeemail()
  226. {
  227. $user = $this->auth->getUser();
  228. $email = $this->request->post('email');
  229. $captcha = $this->request->post('captcha');
  230. if (!$email || !$captcha) {
  231. $this->error(__('Invalid parameters'));
  232. }
  233. if (!Validate::is($email, "email")) {
  234. $this->error(__('Email is incorrect'));
  235. }
  236. if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
  237. $this->error(__('Email already exists'));
  238. }
  239. $result = Ems::check($email, $captcha, 'changeemail');
  240. if (!$result) {
  241. $this->error(__('Captcha is incorrect'));
  242. }
  243. $verification = $user->verification;
  244. $verification->email = 1;
  245. $user->verification = $verification;
  246. $user->email = $email;
  247. $user->save();
  248. Ems::flush($email, 'changeemail');
  249. $this->success();
  250. }
  251. /**
  252. * 修改手机号
  253. *
  254. * @ApiMethod (POST)
  255. * @param string $mobile 手机号
  256. * @param string $captcha 验证码
  257. */
  258. public function changemobile()
  259. {
  260. $user = $this->auth->getUser();
  261. $mobile = $this->request->post('mobile');
  262. $captcha = $this->request->post('captcha');
  263. if (!$mobile || !$captcha) {
  264. $this->error(__('Invalid parameters'));
  265. }
  266. if (!Validate::regex($mobile, "^1\d{10}$")) {
  267. $this->error(__('Mobile is incorrect'));
  268. }
  269. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  270. $this->error(__('Mobile already exists'));
  271. }
  272. $result = Sms::check($mobile, $captcha, 'changemobile');
  273. if (!$result) {
  274. $this->error(__('Captcha is incorrect'));
  275. }
  276. $verification = $user->verification;
  277. $verification->mobile = 1;
  278. $user->verification = $verification;
  279. $user->mobile = $mobile;
  280. $user->save();
  281. Sms::flush($mobile, 'changemobile');
  282. $this->success();
  283. }
  284. /**
  285. * 第三方登录
  286. *
  287. * @ApiMethod (POST)
  288. * @param string $platform 平台名称
  289. * @param string $code Code码
  290. */
  291. public function third()
  292. {
  293. $url = url('user/index');
  294. $platform = $this->request->post("platform");
  295. $code = $this->request->post("code");
  296. $config = get_addon_config('third');
  297. if (!$config || !isset($config[$platform])) {
  298. $this->error(__('Invalid parameters'));
  299. }
  300. $app = new \addons\third\library\Application($config);
  301. //通过code换access_token和绑定会员
  302. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  303. if ($result) {
  304. $loginret = \addons\third\library\Service::connect($platform, $result);
  305. if ($loginret) {
  306. $data = [
  307. 'userinfo' => $this->auth->getUserinfo(),
  308. 'thirdinfo' => $result
  309. ];
  310. $this->success(__('Logged in successful'), $data);
  311. }
  312. }
  313. $this->error(__('Operation failed'), $url);
  314. }
  315. /**
  316. * 重置密码
  317. *
  318. * @ApiMethod (POST)
  319. * @param string $mobile 手机号
  320. * @param string $newpassword 新密码
  321. * @param string $captcha 验证码
  322. */
  323. public function resetpwd()
  324. {
  325. $type = $this->request->post("type");
  326. $mobile = $this->request->post("mobile");
  327. $email = $this->request->post("email");
  328. $newpassword = $this->request->post("newpassword");
  329. $captcha = $this->request->post("captcha");
  330. if (!$newpassword || !$captcha) {
  331. $this->error(__('Invalid parameters'));
  332. }
  333. //验证Token
  334. if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
  335. $this->error(__('Password must be 6 to 30 characters'));
  336. }
  337. if ($type == 'mobile') {
  338. if (!Validate::regex($mobile, "^1\d{10}$")) {
  339. $this->error(__('Mobile is incorrect'));
  340. }
  341. $user = \app\common\model\User::getByMobile($mobile);
  342. if (!$user) {
  343. $this->error(__('User not found'));
  344. }
  345. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  346. if (!$ret) {
  347. $this->error(__('Captcha is incorrect'));
  348. }
  349. Sms::flush($mobile, 'resetpwd');
  350. } else {
  351. if (!Validate::is($email, "email")) {
  352. $this->error(__('Email is incorrect'));
  353. }
  354. $user = \app\common\model\User::getByEmail($email);
  355. if (!$user) {
  356. $this->error(__('User not found'));
  357. }
  358. $ret = Ems::check($email, $captcha, 'resetpwd');
  359. if (!$ret) {
  360. $this->error(__('Captcha is incorrect'));
  361. }
  362. Ems::flush($email, 'resetpwd');
  363. }
  364. //模拟一次登录
  365. $this->auth->direct($user->id);
  366. $ret = $this->auth->changepwd($newpassword, '', true);
  367. if ($ret) {
  368. $this->success(__('Reset password successful'));
  369. } else {
  370. $this->error($this->auth->getError());
  371. }
  372. }
  373. /**
  374. * 获取用户openid
  375. */
  376. public function getUserOpenid() {
  377. // code值
  378. $code = $this->request->param('code');
  379. if (!$code) {
  380. $this->error(__('Invalid parameters'));
  381. }
  382. $config = config('wxMiniProgram');
  383. $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  384. $openidInfo = $this->getJson($getopenid);
  385. if(!isset($openidInfo['openid'])) {
  386. $this->error('用户openid获取失败',$openidInfo);
  387. }
  388. // 获取的结果存入数据库
  389. $find = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->find();
  390. if($find) {
  391. $update = [];
  392. $update['sessionkey'] = $openidInfo['session_key'];
  393. $update['createtime'] = time();
  394. $res = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->update($update);
  395. } else {
  396. $insert = [];
  397. $insert['sessionkey'] = $openidInfo['session_key'];
  398. $insert['openid'] = $openidInfo['openid'];
  399. $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  400. $insert['createtime'] = time();
  401. $res = Db::name('user_sessionkey')->insertGetId($insert);
  402. }
  403. if($res !== false) {
  404. $this->success('获取成功',$openidInfo);
  405. } else {
  406. $this->error('获取失败');
  407. }
  408. }
  409. /**
  410. * 微信小程序登录
  411. */
  412. public function wxMiniProgramLogin() {
  413. $openid = $this->request->request('openid');// openid值
  414. $encryptedData = $this->request->request('encryptedData');// 加密数据
  415. $iv = $this->request->request('iv');// 加密算法
  416. $signature = $this->request->request('signature');// 签名验证
  417. $rawData = $this->request->request('rawData');// 签名验证
  418. $logintype = 2;// 登录方式:1=手机号,2=微信授权openid
  419. if (!$openid || !$encryptedData || !$iv) {
  420. $this->error(__('Invalid parameters'));
  421. }
  422. // 获取openid和sessionkey
  423. $config = config('wxMiniProgram');
  424. $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
  425. $openid = $openidInfo['openid'];
  426. $session_key = $openidInfo['sessionkey'];
  427. // // 数据签名校验
  428. // $signature2 = sha1($rawData . $session_key);
  429. // if ($signature != $signature2) {
  430. // $this->error(__('数据签名验证失败'));
  431. // }
  432. // 根据加密数据和加密算法获取用户信息
  433. $pc = new WXBizDataCrypt($config['appid'], $session_key);
  434. $data = '';
  435. $errCode = $pc->decryptData(urldecode($encryptedData), $iv, $data);
  436. if ($errCode != 0) {
  437. $this->error('解密失败',['code'=>$errCode]);
  438. }
  439. $data = json_decode($data,true);
  440. // 用户登录逻辑 === 开始
  441. if($logintype == 1) { // 手机号登录
  442. /*$userInfo = Db::name('user')->where(["mobile"=>$data["purePhoneNumber"]])->find();
  443. // 用户信息不存在时使用
  444. $extend = ["mobile"=>$data["purePhoneNumber"]];*/
  445. } else { // 微信授权openid登录
  446. $userInfo = Db::name('user')->where(['mini_openid'=>$openid])->find();
  447. // 用户信息不存在时使用
  448. $extend = [
  449. 'mini_openid' => $openid,
  450. 'nickname' => $data['nickName'],
  451. 'avatar' => $data['avatarUrl'],
  452. //'gender' => $data['gender']==1 ? 1 : 0,
  453. 'mini_sessionkey'=> $session_key,
  454. 'unionid' => $openidInfo['unionid'],
  455. //'mobile' => $data['purePhoneNumber'],
  456. ];
  457. }
  458. // 判断用户是否已经存在
  459. if($userInfo) { // 登录
  460. Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
  461. $res = $this->auth->direct($userInfo['id']);
  462. } else { // 注册
  463. // 先随机一个用户名,随后再变更为u+数字id
  464. $username = '';
  465. $password = '';
  466. /*Db::startTrans();
  467. try {*/
  468. // 默认注册一个会员
  469. $result = $this->auth->register($username, $password, '','', $extend);
  470. if (!$result) {
  471. $this->error("注册失败!");
  472. }
  473. /* Db::commit();
  474. } catch (PDOException $e) {
  475. Db::rollback();
  476. $this->auth->logout();
  477. return false;
  478. }*/
  479. // 写入登录Cookies和Token
  480. $res = $this->auth->direct($this->auth->id);
  481. }
  482. $userInfo = $this->userInfo('return');
  483. if($res) {
  484. $this->success("登录成功!",$userInfo);
  485. } else {
  486. $this->error("登录失败!");
  487. }
  488. }
  489. /**
  490. * json 请求
  491. * @param $url
  492. * @return mixed
  493. */
  494. private function getJson($url){
  495. $ch = curl_init();
  496. curl_setopt($ch, CURLOPT_URL, $url);
  497. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  498. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  499. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  500. $output = curl_exec($ch);
  501. curl_close($ch);
  502. return json_decode($output, true);
  503. }
  504. //获取openid
  505. public function getopenid() {
  506. //code
  507. $code = $this->request->post('code', '', 'trim');// code值
  508. if (!$code) {
  509. $this->error(__('Invalid parameters'));
  510. }
  511. $config = config('user_wxMiniProgram');
  512. $getopenid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  513. $openidInfo = httpRequest($getopenid_url, 'GET');//$this->getJson($getopenid_url);
  514. $openidInfo = json_decode($openidInfo,true);
  515. if(!isset($openidInfo['openid'])) {
  516. $this->error('用户openid获取失败', $openidInfo);
  517. }
  518. $user = Db::name('user')->where('mini_openid',$openidInfo['openid'])->find();
  519. $openidInfo['mobile'] = isset($user['mobile']) ? $user['mobile'] : '';
  520. $this->success('获取成功', $openidInfo);
  521. }
  522. //获取手机号
  523. public function getPhoneNumber() {
  524. $code = $this->request->post('code', '', 'trim');
  525. if (!$code) {
  526. $this->error(__('Invalid parameters'));
  527. }
  528. $accessToken = getAccessToken();
  529. $getPhoneUrl = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$accessToken;
  530. $data = json_encode(['code'=>$code]);
  531. $info = httpRequest($getPhoneUrl, 'POST', $data);
  532. $phoneInfo = json_decode($info,true);
  533. if(isset($phoneInfo['errcode']) && $phoneInfo['errcode'] != 0) {
  534. $this->error('获取手机号失败', $phoneInfo['errmsg']);
  535. }
  536. $mobile = isset($phoneInfo['phone_info']['purePhoneNumber']) ? $phoneInfo['phone_info']['purePhoneNumber'] : '';
  537. $user = UserM::where(['mobile'=>$mobile])->find();
  538. if (!$user) {//未查到用户信息
  539. //微信登录注册
  540. $time = time();
  541. $ip = request()->ip();
  542. $userData = [
  543. 'mobile' => $mobile,
  544. 'joinip' => $ip,
  545. 'jointime' => $time,
  546. 'createtime'=> $time,
  547. ];
  548. $userAdd = Db::name('user')->insertGetId($userData);
  549. if (!$userAdd) {
  550. throw new Exception('注册失败');
  551. }
  552. $user = Userm::getById($userAdd);
  553. }
  554. $ret = $this->auth->direct($user->id);
  555. if (!$ret) {
  556. throw new Exception($this->auth->getError());
  557. }
  558. $result = [
  559. 'userinfo' => $this->auth->getUserinfo()
  560. ];
  561. $this->success('登录成功', $result);
  562. }
  563. //微信登录
  564. public function wxlogin() {
  565. try {
  566. $openid = input('openid', '', 'trim');
  567. $mobile = input('mobile','','trim');
  568. $nickName = input('nickname','');
  569. $avatar = input('avatar','/assets/img/avatar.png');
  570. $sex = input('gender',0);
  571. if (!$openid) {
  572. throw new Exception('未获取到用户openid');
  573. }
  574. $user = UserM::where(['mini_openid'=>$openid])->find();
  575. if (!$user) {//未查到用户信息
  576. //用户手机号注册
  577. /*if (empty($mobile)) {
  578. throw new Exception('未获取到手机号');
  579. }
  580. $user = UserM::where(['mobile'=>$mobile])->find();*/
  581. if (empty($user)) {//微信登录注册
  582. if (empty($user['nickname'])) {
  583. $systemAuth = new Auth();
  584. $nickName = $systemAuth->get_rand_nick_name();
  585. }
  586. $time = time();
  587. $ip = request()->ip();
  588. $userData = [
  589. 'nickname' => $nickName,
  590. 'avatar' => $avatar,
  591. 'gender' => $sex,
  592. //'mobile' => $mobile,
  593. 'joinip' => $ip,
  594. 'jointime' => $time,
  595. 'createtime'=> $time,
  596. 'mini_openid'=> $openid,
  597. ];
  598. $userAdd = Db::name('user')->insertGetId($userData);
  599. if (!$userAdd) {
  600. throw new Exception('注册失败');
  601. }
  602. $userAppendData['username'] = 'u' . (10000 + $userAdd);
  603. $userWhere['id'] = $userAdd;
  604. Db::name('user')->where($userWhere)->update($userAppendData);
  605. $user = Userm::getById($userAdd);
  606. }
  607. } else {
  608. $userUpdate = [];
  609. if (!empty($nickName) && empty($user->nick_name)) {
  610. $userUpdate['nickname'] = $nickName;
  611. }
  612. if (!empty($avatar) && empty($user->avatar)) {
  613. $userUpdate['avatar'] = $avatar;
  614. }
  615. if (!empty($sex) && $sex != $user->sex) {
  616. $userUpdate['gender'] = $sex;
  617. }
  618. if (empty($user->mini_openid)) {//手机号绑定openid
  619. $userUpdate['mini_openid'] = $openid;
  620. }
  621. if (!empty($userUpdate)) {
  622. $userUpRes = Db::name('user')->where(['id'=>$user->id])->update($userUpdate);
  623. if (!$userUpRes) {
  624. throw new Exception('用户信息更新失败');
  625. }
  626. }
  627. }
  628. if ($user['status'] != 1) {
  629. throw new Exception(__('Account is locked'));
  630. }
  631. $ret = $this->auth->direct($user->id);
  632. if (!$ret) {
  633. throw new Exception($this->auth->getError());
  634. }
  635. $data = ['userinfo' => $this->auth->getUserinfo()];
  636. $this->success(__('Logged in successful'), $data);
  637. } catch (Exception $e) {
  638. $this->error($e->getMessage());
  639. }
  640. }
  641. /**
  642. * 获取用户信息
  643. * @return void
  644. */
  645. public function getInfo()
  646. {
  647. try {
  648. $userInfo = $this->auth->getUserinfo();
  649. $where['id'] = $this->auth->id;
  650. $userData = Db::name('user')->where($where)->find();
  651. if (!empty($userData)) {
  652. $userInfo['company_id'] = $userData['company_id'];
  653. }
  654. $userCouponsWhere['company_id'] = !empty($userData['company_id']) ? $userData['company_id'] : $userData['temp_company_id'];
  655. $userCouponsWhere['user_id'] = $this->auth->id;
  656. $userCouponsWhere['endtime'] = ['gt', time()];
  657. $userCouponsNum = Db::name('user_coupons')->where($userCouponsWhere)->sum('remain');
  658. $userInfo['coupons_num'] = $userCouponsNum;
  659. $userInfo['createtime'] = !empty($userInfo['createtime']) ? date('Y-m-d',$userInfo['createtime']) : '';
  660. $this->success('获取成功',$userInfo);
  661. } catch (Exception $e) {
  662. $this->error($e->getMessage());
  663. }
  664. }
  665. }