User.php 22 KB

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