User.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  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. $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
  161. if ($username) {
  162. $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
  163. if ($exists) {
  164. $this->error(__('Username already exists'));
  165. }
  166. $user->username = $username;
  167. }
  168. if ($nickname) {
  169. $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
  170. if ($exists) {
  171. $this->error(__('Nickname already exists'));
  172. }
  173. $user->nickname = $nickname;
  174. }
  175. $user->bio = $bio;
  176. $user->avatar = $avatar;
  177. $user->save();
  178. $this->success();
  179. }
  180. /**
  181. * 修改邮箱
  182. *
  183. * @ApiMethod (POST)
  184. * @param string $email 邮箱
  185. * @param string $captcha 验证码
  186. */
  187. public function changeemail()
  188. {
  189. $user = $this->auth->getUser();
  190. $email = $this->request->post('email');
  191. $captcha = $this->request->post('captcha');
  192. if (!$email || !$captcha) {
  193. $this->error(__('Invalid parameters'));
  194. }
  195. if (!Validate::is($email, "email")) {
  196. $this->error(__('Email is incorrect'));
  197. }
  198. if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
  199. $this->error(__('Email already exists'));
  200. }
  201. $result = Ems::check($email, $captcha, 'changeemail');
  202. if (!$result) {
  203. $this->error(__('Captcha is incorrect'));
  204. }
  205. $verification = $user->verification;
  206. $verification->email = 1;
  207. $user->verification = $verification;
  208. $user->email = $email;
  209. $user->save();
  210. Ems::flush($email, 'changeemail');
  211. $this->success();
  212. }
  213. /**
  214. * 修改手机号
  215. *
  216. * @ApiMethod (POST)
  217. * @param string $mobile 手机号
  218. * @param string $captcha 验证码
  219. */
  220. public function changemobile()
  221. {
  222. $user = $this->auth->getUser();
  223. $mobile = $this->request->post('mobile');
  224. $captcha = $this->request->post('captcha');
  225. if (!$mobile || !$captcha) {
  226. $this->error(__('Invalid parameters'));
  227. }
  228. if (!Validate::regex($mobile, "^1\d{10}$")) {
  229. $this->error(__('Mobile is incorrect'));
  230. }
  231. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  232. $this->error(__('Mobile already exists'));
  233. }
  234. $result = Sms::check($mobile, $captcha, 'changemobile');
  235. if (!$result) {
  236. $this->error(__('Captcha is incorrect'));
  237. }
  238. $verification = $user->verification;
  239. $verification->mobile = 1;
  240. $user->verification = $verification;
  241. $user->mobile = $mobile;
  242. $user->save();
  243. Sms::flush($mobile, 'changemobile');
  244. $this->success();
  245. }
  246. /**
  247. * 第三方登录
  248. *
  249. * @ApiMethod (POST)
  250. * @param string $platform 平台名称
  251. * @param string $code Code码
  252. */
  253. public function third()
  254. {
  255. $url = url('user/index');
  256. $platform = $this->request->post("platform");
  257. $code = $this->request->post("code");
  258. $config = get_addon_config('third');
  259. if (!$config || !isset($config[$platform])) {
  260. $this->error(__('Invalid parameters'));
  261. }
  262. $app = new \addons\third\library\Application($config);
  263. //通过code换access_token和绑定会员
  264. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  265. if ($result) {
  266. $loginret = \addons\third\library\Service::connect($platform, $result);
  267. if ($loginret) {
  268. $data = [
  269. 'userinfo' => $this->auth->getUserinfo(),
  270. 'thirdinfo' => $result
  271. ];
  272. $this->success(__('Logged in successful'), $data);
  273. }
  274. }
  275. $this->error(__('Operation failed'), $url);
  276. }
  277. /**
  278. * 重置密码
  279. *
  280. * @ApiMethod (POST)
  281. * @param string $mobile 手机号
  282. * @param string $newpassword 新密码
  283. * @param string $captcha 验证码
  284. */
  285. public function resetpwd()
  286. {
  287. $type = $this->request->post("type");
  288. $mobile = $this->request->post("mobile");
  289. $email = $this->request->post("email");
  290. $newpassword = $this->request->post("newpassword");
  291. $captcha = $this->request->post("captcha");
  292. if (!$newpassword || !$captcha) {
  293. $this->error(__('Invalid parameters'));
  294. }
  295. //验证Token
  296. if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
  297. $this->error(__('Password must be 6 to 30 characters'));
  298. }
  299. if ($type == 'mobile') {
  300. if (!Validate::regex($mobile, "^1\d{10}$")) {
  301. $this->error(__('Mobile is incorrect'));
  302. }
  303. $user = \app\common\model\User::getByMobile($mobile);
  304. if (!$user) {
  305. $this->error(__('User not found'));
  306. }
  307. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  308. if (!$ret) {
  309. $this->error(__('Captcha is incorrect'));
  310. }
  311. Sms::flush($mobile, 'resetpwd');
  312. } else {
  313. if (!Validate::is($email, "email")) {
  314. $this->error(__('Email is incorrect'));
  315. }
  316. $user = \app\common\model\User::getByEmail($email);
  317. if (!$user) {
  318. $this->error(__('User not found'));
  319. }
  320. $ret = Ems::check($email, $captcha, 'resetpwd');
  321. if (!$ret) {
  322. $this->error(__('Captcha is incorrect'));
  323. }
  324. Ems::flush($email, 'resetpwd');
  325. }
  326. //模拟一次登录
  327. $this->auth->direct($user->id);
  328. $ret = $this->auth->changepwd($newpassword, '', true);
  329. if ($ret) {
  330. $this->success(__('Reset password successful'));
  331. } else {
  332. $this->error($this->auth->getError());
  333. }
  334. }
  335. /**
  336. * 获取用户openid
  337. */
  338. public function getUserOpenid() {
  339. // code值
  340. $code = $this->request->param('code');
  341. if (!$code) {
  342. $this->error(__('Invalid parameters'));
  343. }
  344. $config = config('wxMiniProgram');
  345. $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  346. $openidInfo = $this->getJson($getopenid);
  347. if(!isset($openidInfo['openid'])) {
  348. $this->error('用户openid获取失败',$openidInfo);
  349. }
  350. // 获取的结果存入数据库
  351. $find = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->find();
  352. if($find) {
  353. $update = [];
  354. $update['sessionkey'] = $openidInfo['session_key'];
  355. $update['createtime'] = time();
  356. $res = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->update($update);
  357. } else {
  358. $insert = [];
  359. $insert['sessionkey'] = $openidInfo['session_key'];
  360. $insert['openid'] = $openidInfo['openid'];
  361. $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  362. $insert['createtime'] = time();
  363. $res = Db::name('user_sessionkey')->insertGetId($insert);
  364. }
  365. if($res !== false) {
  366. $this->success('获取成功',$openidInfo);
  367. } else {
  368. $this->error('获取失败');
  369. }
  370. }
  371. /**
  372. * 微信小程序登录
  373. */
  374. public function wxMiniProgramLogin() {
  375. $openid = $this->request->request('openid');// openid值
  376. $encryptedData = $this->request->request('encryptedData');// 加密数据
  377. $iv = $this->request->request('iv');// 加密算法
  378. $signature = $this->request->request('signature');// 签名验证
  379. $rawData = $this->request->request('rawData');// 签名验证
  380. $logintype = 2;// 登录方式:1=手机号,2=微信授权openid
  381. if (!$openid || !$encryptedData || !$iv) {
  382. $this->error(__('Invalid parameters'));
  383. }
  384. // 获取openid和sessionkey
  385. $config = config('wxMiniProgram');
  386. $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
  387. $openid = $openidInfo['openid'];
  388. $session_key = $openidInfo['sessionkey'];
  389. // // 数据签名校验
  390. // $signature2 = sha1($rawData . $session_key);
  391. // if ($signature != $signature2) {
  392. // $this->error(__('数据签名验证失败'));
  393. // }
  394. // 根据加密数据和加密算法获取用户信息
  395. $pc = new WXBizDataCrypt($config['appid'], $session_key);
  396. $data = '';
  397. $errCode = $pc->decryptData(urldecode($encryptedData), $iv, $data);
  398. if ($errCode != 0) {
  399. $this->error('解密失败',['code'=>$errCode]);
  400. }
  401. $data = json_decode($data,true);
  402. // 用户登录逻辑 === 开始
  403. if($logintype == 1) { // 手机号登录
  404. /*$userInfo = Db::name('user')->where(["mobile"=>$data["purePhoneNumber"]])->find();
  405. // 用户信息不存在时使用
  406. $extend = ["mobile"=>$data["purePhoneNumber"]];*/
  407. } else { // 微信授权openid登录
  408. $userInfo = Db::name('user')->where(['mini_openid'=>$openid])->find();
  409. // 用户信息不存在时使用
  410. $extend = [
  411. 'mini_openid' => $openid,
  412. 'nickname' => $data['nickName'],
  413. 'avatar' => $data['avatarUrl'],
  414. //'gender' => $data['gender']==1 ? 1 : 0,
  415. 'mini_sessionkey'=> $session_key,
  416. 'unionid' => $openidInfo['unionid'],
  417. //'mobile' => $data['purePhoneNumber'],
  418. ];
  419. }
  420. // 判断用户是否已经存在
  421. if($userInfo) { // 登录
  422. Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
  423. $res = $this->auth->direct($userInfo['id']);
  424. } else { // 注册
  425. // 先随机一个用户名,随后再变更为u+数字id
  426. $username = '';
  427. $password = '';
  428. /*Db::startTrans();
  429. try {*/
  430. // 默认注册一个会员
  431. $result = $this->auth->register($username, $password, '','', $extend);
  432. if (!$result) {
  433. $this->error("注册失败!");
  434. }
  435. /* Db::commit();
  436. } catch (PDOException $e) {
  437. Db::rollback();
  438. $this->auth->logout();
  439. return false;
  440. }*/
  441. // 写入登录Cookies和Token
  442. $res = $this->auth->direct($this->auth->id);
  443. }
  444. $userInfo = $this->userInfo('return');
  445. if($res) {
  446. $this->success("登录成功!",$userInfo);
  447. } else {
  448. $this->error("登录失败!");
  449. }
  450. }
  451. /**
  452. * json 请求
  453. * @param $url
  454. * @return mixed
  455. */
  456. private function getJson($url){
  457. $ch = curl_init();
  458. curl_setopt($ch, CURLOPT_URL, $url);
  459. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  460. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  461. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  462. $output = curl_exec($ch);
  463. curl_close($ch);
  464. return json_decode($output, true);
  465. }
  466. //获取openid
  467. public function getopenid() {
  468. //code
  469. $code = $this->request->post('code', '', 'trim');// code值
  470. if (!$code) {
  471. $this->error(__('Invalid parameters'));
  472. }
  473. $config = config('user_wxMiniProgram');
  474. $getopenid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['appsecret'].'&js_code='.$code.'&grant_type=authorization_code';
  475. $openidInfo = httpRequest($getopenid_url, 'GET');//$this->getJson($getopenid_url);
  476. $openidInfo = json_decode($openidInfo,true);
  477. if(!isset($openidInfo['openid'])) {
  478. $this->error('用户openid获取失败', $openidInfo);
  479. }
  480. $this->success('success', $openidInfo);
  481. }
  482. //获取手机号
  483. public function getPhoneNumber() {
  484. $code = $this->request->post('code', '', 'trim');
  485. if (!$code) {
  486. $this->error(__('Invalid parameters'));
  487. }
  488. $accessToken = getAccessToken();
  489. $getPhoneUrl = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$accessToken;
  490. $data = json_encode(['code'=>$code]);
  491. $info = httpRequest($getPhoneUrl, 'POST', $data);
  492. $phoneInfo = json_decode($info,true);
  493. if(isset($phoneInfo['errcode']) && $phoneInfo['errcode'] != 0) {
  494. $this->error('获取手机号失败', $phoneInfo['errmsg']);
  495. }
  496. $mobile = isset($phoneInfo['phone_info']['purePhoneNumber']) ? $phoneInfo['phone_info']['purePhoneNumber'] : '';
  497. $user = UserM::where(['mobile'=>$mobile])->find();
  498. if (!$user) {//未查到用户信息
  499. //微信登录注册
  500. $time = time();
  501. $ip = request()->ip();
  502. $userData = [
  503. 'mobile' => $mobile,
  504. 'register_time' => $time,
  505. 'joinip' => $ip,
  506. 'jointime' => $time,
  507. 'createtime'=> $time,
  508. ];
  509. $userAdd = Db::name('user')->insertGetId($userData);
  510. if (!$userAdd) {
  511. throw new Exception('注册失败');
  512. }
  513. $user = Userm::getById($userAdd);
  514. }
  515. $ret = $this->auth->direct($user->id);
  516. if (!$ret) {
  517. throw new Exception($this->auth->getError());
  518. }
  519. $result = [
  520. 'userinfo' => $this->auth->getUserinfo()
  521. ];
  522. $this->success('登录成功', $result);
  523. }
  524. //微信登录
  525. public function wxlogin() {
  526. try {
  527. $openid = input('openid', '', 'trim');
  528. $mobile = input('mobile','','trim');
  529. $nickName = input('nickname','');
  530. $avatar = input('avatar','');
  531. $sex = input('gender',0);
  532. if (!$openid) {
  533. throw new Exception('未获取到用户openid');
  534. }
  535. $user = UserM::where(['mini_openid'=>$openid])->find();
  536. if (!$user) {//未查到用户信息
  537. //用户手机号注册
  538. if (empty($mobile)) {
  539. throw new Exception('未获取到手机号');
  540. }
  541. $user = UserM::where(['mobile'=>$mobile])->find();
  542. if (empty($user)) {//微信登录注册
  543. $time = time();
  544. $ip = request()->ip();
  545. $userData = [
  546. 'nickname' => $nickName,
  547. 'avatar' => $avatar,
  548. 'gender' => $sex,
  549. 'mobile' => $mobile,
  550. 'register_time' => $time,
  551. 'joinip' => $ip,
  552. 'jointime' => $time,
  553. 'createtime'=> $time,
  554. 'mini_openid'=> $openid,
  555. ];
  556. $userAdd = Db::name('user')->insertGetId($userData);
  557. if (!$userAdd) {
  558. throw new Exception('注册失败');
  559. }
  560. $user = Userm::getById($userAdd);
  561. }
  562. if (empty($user->openid)) {//手机号绑定openid
  563. $user->mini_openid = $openid;
  564. $userRes = $user->save();
  565. if (!$userRes) {
  566. throw new Exception('绑定微信失败');
  567. }
  568. }
  569. } else {
  570. $userUpdate = [];
  571. if (!empty($nickName) && empty($user->nick_name)) {
  572. $userUpdate['nickname'] = $nickName;
  573. }
  574. if (!empty($avatar) && empty($user->avatar)) {
  575. $userUpdate['avatar'] = $avatar;
  576. }
  577. if (!empty($sex) && $sex != $user->sex) {
  578. $userUpdate['gender'] = $sex;
  579. }
  580. if (!empty($userUpdate)) {
  581. $userUpRes = Db::name('user')->where(['id'=>$user->id])->update($userUpdate);
  582. if (!$userUpRes) {
  583. throw new Exception('用户信息更新失败');
  584. }
  585. }
  586. }
  587. if ($user['status'] != 1) {
  588. throw new Exception(__('Account is locked'));
  589. }
  590. $ret = $this->auth->direct($user->id);
  591. if (!$ret) {
  592. throw new Exception($this->auth->getError());
  593. }
  594. $data = ['userinfo' => $this->auth->getUserinfo()];
  595. $this->success(__('Logged in successful'), $data);
  596. } catch (Exception $e) {
  597. $this->error($e->getMessage());
  598. }
  599. }
  600. }