User.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 fast\Random;
  7. use think\Config;
  8. use think\Validate;
  9. use think\Db;
  10. use miniprogram\wxBizDataCrypt;
  11. use app\common\library\Wechat;
  12. /**
  13. * 会员接口
  14. */
  15. class User extends Api
  16. {
  17. protected $noNeedLogin = ['login','getuserphonenumber', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'getUserOpenid','wxMiniProgramLogin'];
  18. protected $noNeedRight = '*';
  19. public function _initialize()
  20. {
  21. parent::_initialize();
  22. if (!Config::get('fastadmin.usercenter')) {
  23. $this->error(__('User center already closed'));
  24. }
  25. }
  26. /**
  27. * 会员中心
  28. */
  29. public function index()
  30. {
  31. $this->success('', ['welcome' => $this->auth->nickname]);
  32. }
  33. /**
  34. * 会员登录
  35. *
  36. * @ApiMethod (POST)
  37. * @param string $account 账号
  38. * @param string $password 密码
  39. */
  40. public function login()
  41. {
  42. $account = $this->request->post('account');
  43. $password = $this->request->post('password');
  44. if (!$account || !$password) {
  45. $this->error(__('Invalid parameters'));
  46. }
  47. $ret = $this->auth->login($account, $password);
  48. if ($ret) {
  49. $data = ['userinfo' => $this->auth->getUserinfo()];
  50. $this->success(__('Logged in successful'), $data);
  51. } else {
  52. $this->error($this->auth->getError());
  53. }
  54. }
  55. /**
  56. * 手机验证码登录
  57. *
  58. * @ApiMethod (POST)
  59. * @param string $mobile 手机号
  60. * @param string $captcha 验证码
  61. */
  62. public function mobilelogin()
  63. {
  64. $mobile = $this->request->post('mobile');
  65. $captcha = $this->request->post('captcha');
  66. if (!$mobile || !$captcha) {
  67. $this->error(__('Invalid parameters'));
  68. }
  69. if (!Validate::regex($mobile, "^1\d{10}$")) {
  70. $this->error(__('Mobile is incorrect'));
  71. }
  72. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  73. $this->error(__('Captcha is incorrect'));
  74. }
  75. $user = \app\common\model\User::getByMobile($mobile);
  76. if ($user) {
  77. if ($user->status != 'normal') {
  78. $this->error(__('Account is locked'));
  79. }
  80. //如果已经有账号则直接登录
  81. $ret = $this->auth->direct($user->id);
  82. } else {
  83. $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
  84. }
  85. if ($ret) {
  86. Sms::flush($mobile, 'mobilelogin');
  87. $data = ['userinfo' => $this->auth->getUserinfo()];
  88. $this->success(__('Logged in successful'), $data);
  89. } else {
  90. $this->error($this->auth->getError());
  91. }
  92. }
  93. /**
  94. * 注册会员
  95. *
  96. * @ApiMethod (POST)
  97. * @param string $username 用户名
  98. * @param string $password 密码
  99. * @param string $email 邮箱
  100. * @param string $mobile 手机号
  101. * @param string $code 验证码
  102. */
  103. public function register()
  104. {
  105. $username = $this->request->post('username');
  106. $password = $this->request->post('password');
  107. $email = $this->request->post('email');
  108. $mobile = $this->request->post('mobile');
  109. $code = $this->request->post('code');
  110. if (!$username || !$password) {
  111. $this->error(__('Invalid parameters'));
  112. }
  113. if ($email && !Validate::is($email, "email")) {
  114. $this->error(__('Email is incorrect'));
  115. }
  116. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  117. $this->error(__('Mobile is incorrect'));
  118. }
  119. $ret = Sms::check($mobile, $code, 'register');
  120. if (!$ret) {
  121. $this->error(__('Captcha is incorrect'));
  122. }
  123. $ret = $this->auth->register($username, $password, $email, $mobile, []);
  124. if ($ret) {
  125. $data = ['userinfo' => $this->auth->getUserinfo()];
  126. $this->success(__('Sign up successful'), $data);
  127. } else {
  128. $this->error($this->auth->getError());
  129. }
  130. }
  131. /**
  132. * 退出登录
  133. * @ApiMethod (POST)
  134. */
  135. public function logout()
  136. {
  137. if (!$this->request->isPost()) {
  138. $this->error(__('Invalid parameters'));
  139. }
  140. $this->auth->logout();
  141. $this->success(__('Logout successful'));
  142. }
  143. /**
  144. * 修改会员个人信息
  145. *
  146. * @ApiMethod (POST)
  147. * @param string $avatar 头像地址
  148. * @param string $username 用户名
  149. * @param string $nickname 昵称
  150. * @param string $bio 个人简介
  151. */
  152. public function profile()
  153. {
  154. $nickname = input('nickname','','trim');
  155. $avatar = input('avatar', '', 'trim,strip_tags,htmlspecialchars');
  156. $update = [];
  157. if(!empty($nickname)){
  158. $update['nickname'] = $nickname;
  159. }
  160. if(!empty($avatar)){
  161. $update['avatar'] = $avatar;
  162. }
  163. if(!empty($update)){
  164. Db::name('user')->where('id',$this->auth->id)->update($update);
  165. }
  166. $this->success('修改成功');
  167. }
  168. /**
  169. * 修改邮箱
  170. *
  171. * @ApiMethod (POST)
  172. * @param string $email 邮箱
  173. * @param string $captcha 验证码
  174. */
  175. public function changeemail()
  176. {
  177. $user = $this->auth->getUser();
  178. $email = $this->request->post('email');
  179. $captcha = $this->request->post('captcha');
  180. if (!$email || !$captcha) {
  181. $this->error(__('Invalid parameters'));
  182. }
  183. if (!Validate::is($email, "email")) {
  184. $this->error(__('Email is incorrect'));
  185. }
  186. if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
  187. $this->error(__('Email already exists'));
  188. }
  189. $result = Ems::check($email, $captcha, 'changeemail');
  190. if (!$result) {
  191. $this->error(__('Captcha is incorrect'));
  192. }
  193. $verification = $user->verification;
  194. $verification->email = 1;
  195. $user->verification = $verification;
  196. $user->email = $email;
  197. $user->save();
  198. Ems::flush($email, 'changeemail');
  199. $this->success();
  200. }
  201. /**
  202. * 修改手机号
  203. *
  204. * @ApiMethod (POST)
  205. * @param string $mobile 手机号
  206. * @param string $captcha 验证码
  207. */
  208. public function changemobile()
  209. {
  210. $user = $this->auth->getUser();
  211. $mobile = $this->request->post('mobile');
  212. $captcha = $this->request->post('captcha');
  213. if (!$mobile || !$captcha) {
  214. $this->error(__('Invalid parameters'));
  215. }
  216. if (!Validate::regex($mobile, "^1\d{10}$")) {
  217. $this->error(__('Mobile is incorrect'));
  218. }
  219. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  220. $this->error(__('Mobile already exists'));
  221. }
  222. $result = Sms::check($mobile, $captcha, 'changemobile');
  223. if (!$result) {
  224. $this->error(__('Captcha is incorrect'));
  225. }
  226. $verification = $user->verification;
  227. $verification->mobile = 1;
  228. $user->verification = $verification;
  229. $user->mobile = $mobile;
  230. $user->save();
  231. Sms::flush($mobile, 'changemobile');
  232. $this->success();
  233. }
  234. /**
  235. * 第三方登录
  236. *
  237. * @ApiMethod (POST)
  238. * @param string $platform 平台名称
  239. * @param string $code Code码
  240. */
  241. public function third()
  242. {
  243. $url = url('user/index');
  244. $platform = $this->request->post("platform");
  245. $code = $this->request->post("code");
  246. $config = get_addon_config('third');
  247. if (!$config || !isset($config[$platform])) {
  248. $this->error(__('Invalid parameters'));
  249. }
  250. $app = new \addons\third\library\Application($config);
  251. //通过code换access_token和绑定会员
  252. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  253. if ($result) {
  254. $loginret = \addons\third\library\Service::connect($platform, $result);
  255. if ($loginret) {
  256. $data = [
  257. 'userinfo' => $this->auth->getUserinfo(),
  258. 'thirdinfo' => $result
  259. ];
  260. $this->success(__('Logged in successful'), $data);
  261. }
  262. }
  263. $this->error(__('Operation failed'), $url);
  264. }
  265. /**
  266. * 重置密码
  267. *
  268. * @ApiMethod (POST)
  269. * @param string $mobile 手机号
  270. * @param string $newpassword 新密码
  271. * @param string $captcha 验证码
  272. */
  273. public function resetpwd()
  274. {
  275. $type = $this->request->post("type");
  276. $mobile = $this->request->post("mobile");
  277. $email = $this->request->post("email");
  278. $newpassword = $this->request->post("newpassword");
  279. $captcha = $this->request->post("captcha");
  280. if (!$newpassword || !$captcha) {
  281. $this->error(__('Invalid parameters'));
  282. }
  283. //验证Token
  284. if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
  285. $this->error(__('Password must be 6 to 30 characters'));
  286. }
  287. if ($type == 'mobile') {
  288. if (!Validate::regex($mobile, "^1\d{10}$")) {
  289. $this->error(__('Mobile is incorrect'));
  290. }
  291. $user = \app\common\model\User::getByMobile($mobile);
  292. if (!$user) {
  293. $this->error(__('User not found'));
  294. }
  295. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  296. if (!$ret) {
  297. $this->error(__('Captcha is incorrect'));
  298. }
  299. Sms::flush($mobile, 'resetpwd');
  300. } else {
  301. if (!Validate::is($email, "email")) {
  302. $this->error(__('Email is incorrect'));
  303. }
  304. $user = \app\common\model\User::getByEmail($email);
  305. if (!$user) {
  306. $this->error(__('User not found'));
  307. }
  308. $ret = Ems::check($email, $captcha, 'resetpwd');
  309. if (!$ret) {
  310. $this->error(__('Captcha is incorrect'));
  311. }
  312. Ems::flush($email, 'resetpwd');
  313. }
  314. //模拟一次登录
  315. $this->auth->direct($user->id);
  316. $ret = $this->auth->changepwd($newpassword, '', true);
  317. if ($ret) {
  318. $this->success(__('Reset password successful'));
  319. } else {
  320. $this->error($this->auth->getError());
  321. }
  322. }
  323. //用户详细资料
  324. public function getUserinfo($type = 1){
  325. $info = $this->auth->getUserinfo();
  326. if($type == 'return'){
  327. return $info;
  328. }
  329. $this->success(__('success'),$info);
  330. }
  331. public function getuserphonenumber(){
  332. $code = input('code');
  333. if (!$code) {
  334. $this->error(__('Invalid parameters'));
  335. }
  336. $config = config('wxMiniProgram');
  337. $wechat = new Wechat($config['appid'],$config['secret']);
  338. $getuserphonenumber = $wechat->getuserphonenumber($code);
  339. if(!isset($getuserphonenumber['phone_info']['purePhoneNumber'])){
  340. $this->error('授权获取手机号失败');
  341. }
  342. $mobile = $getuserphonenumber['phone_info']['purePhoneNumber'];
  343. //$mobile = 18560505277;
  344. $userInfo = Db::name('user')->where('mobile',$mobile)->find();
  345. // 判断用户是否已经存在
  346. if($userInfo) { // 登录
  347. Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
  348. $res = $this->auth->direct($userInfo['id']);
  349. } else {
  350. // 注册
  351. // 用户信息不存在时使用
  352. $extend = [
  353. /* 'mini_openid' => $openid,
  354. 'mini_sessionkey'=> $session_key,
  355. 'unionid' => $openidInfo['unionid'],*/
  356. ];
  357. // 默认注册一个会员
  358. $result = $this->auth->register('', '', '',$mobile, $extend);
  359. if (!$result) {
  360. $this->error("注册失败!");
  361. }
  362. $res = $this->auth->direct($this->auth->id);
  363. }
  364. $userInfo = $this->getUserinfo('return');
  365. if($res) {
  366. $this->success("登录成功!",$userInfo);
  367. } else {
  368. $this->error("登录失败!");
  369. }
  370. }
  371. /**
  372. * 获取用户openid
  373. */
  374. public function getUserOpenid() {
  375. // code值
  376. $code = $this->request->param('code');
  377. if (!$code) {
  378. $this->error(__('Invalid parameters'));
  379. }
  380. $config = config('wxMiniProgram');
  381. $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  382. $openidInfo = $this->getJson($getopenid);
  383. if(!isset($openidInfo['openid'])) {
  384. $this->error('用户openid获取失败',$openidInfo);
  385. }
  386. // 获取的结果存入数据库
  387. $find = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->find();
  388. if($find) {
  389. $update = [];
  390. $update['sessionkey'] = $openidInfo['session_key'];
  391. $update['createtime'] = time();
  392. $res = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->update($update);
  393. } else {
  394. $insert = [];
  395. $insert['sessionkey'] = $openidInfo['session_key'];
  396. $insert['openid'] = $openidInfo['openid'];
  397. $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  398. $insert['createtime'] = time();
  399. $res = Db::name('user_sessionkey')->insertGetId($insert);
  400. }
  401. if($res !== false) {
  402. $this->success('获取成功',$openidInfo);
  403. } else {
  404. $this->error('获取失败');
  405. }
  406. }
  407. /**
  408. * 微信小程序登录
  409. */
  410. public function wxMiniProgramLogin_old() {
  411. $openid = $this->request->request('openid');// openid值
  412. $avatar = $this->request->request('avatar');
  413. $nickname = $this->request->request('nickname');
  414. $mobile = $this->request->request('mobile');
  415. //学生信息
  416. $field = ['realname','gender','school_id','grade_id','classes_id','stu_mobile','idcard'];
  417. $stu_data = request_post_hub($field);
  418. //学生信息
  419. if (!$openid) {
  420. $this->error(__('Invalid parameters'));
  421. }
  422. // 获取openid和sessionkey
  423. $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
  424. $session_key = $openidInfo['sessionkey'];
  425. // 微信授权openid登录
  426. $userInfo = Db::name('user')->where(['mini_openid'=>$openid])->find();
  427. // 用户信息不存在时使用
  428. $extend = [
  429. 'mini_openid' => $openid,
  430. 'nickname' => $nickname,
  431. 'avatar' => $avatar,
  432. 'mini_sessionkey'=> $session_key,
  433. 'unionid' => $openidInfo['unionid'],
  434. 'mobile' => $mobile,
  435. ];
  436. // 判断用户是否已经存在
  437. if($userInfo) { // 登录
  438. Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
  439. $res = $this->auth->direct($userInfo['id']);
  440. } else {
  441. // 注册
  442. $username = '';
  443. $password = '';
  444. // 默认注册一个会员
  445. $result = $this->auth->register($username, $password, '','', $extend);
  446. if (!$result) {
  447. $this->error("注册失败!");
  448. }
  449. //学生入库
  450. $stu_data['user_id'] = $this->auth->id;
  451. $stu_data['is_default'] = 1;
  452. Db::name('user_student')->insertGetId($stu_data);
  453. //从学生库找人,放到注册人名下
  454. Db::name('user_student')->where('user_id',0)->where('mobile',$mobile)->update(['user_id'=>$this->auth->id]);
  455. $res = $this->auth->direct($this->auth->id);
  456. }
  457. $userInfo = $this->getUserinfo('return');
  458. if($res) {
  459. $this->success("登录成功!",$userInfo);
  460. } else {
  461. $this->error("登录失败!");
  462. }
  463. }
  464. /**
  465. * 微信小程序登录
  466. */
  467. public function wxMiniProgramLogin() {
  468. $openid = $this->request->request('openid');// openid值
  469. if (!$openid) {
  470. $this->error(__('Invalid parameters'));
  471. }
  472. // 获取openid和sessionkey
  473. $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
  474. $session_key = $openidInfo['sessionkey'];
  475. // 微信授权openid登录
  476. $userInfo = Db::name('user')->where(['mini_openid'=>$openid])->find();
  477. // 判断用户是否已经存在
  478. if($userInfo) { // 登录
  479. Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
  480. $res = $this->auth->direct($userInfo['id']);
  481. } else {
  482. // 注册
  483. // 用户信息不存在时使用
  484. $extend = [
  485. 'mini_openid' => $openid,
  486. 'mini_sessionkey'=> $session_key,
  487. 'unionid' => $openidInfo['unionid'],
  488. ];
  489. // 默认注册一个会员
  490. $result = $this->auth->register('', '', '','', $extend);
  491. if (!$result) {
  492. $this->error("注册失败!");
  493. }
  494. $res = $this->auth->direct($this->auth->id);
  495. }
  496. $userInfo = $this->getUserinfo('return');
  497. if($res) {
  498. $this->success("登录成功!",$userInfo);
  499. } else {
  500. $this->error("登录失败!");
  501. }
  502. }
  503. /**
  504. * json 请求
  505. * @param $url
  506. * @return mixed
  507. */
  508. private function getJson($url){
  509. $ch = curl_init();
  510. curl_setopt($ch, CURLOPT_URL, $url);
  511. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  512. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  513. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  514. $output = curl_exec($ch);
  515. curl_close($ch);
  516. return json_decode($output, true);
  517. }
  518. }