User.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. /**
  12. * 会员接口
  13. */
  14. class User extends Api
  15. {
  16. protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'getUserOpenid','wxMiniProgramLogin'];
  17. protected $noNeedRight = '*';
  18. public function _initialize()
  19. {
  20. parent::_initialize();
  21. if (!Config::get('fastadmin.usercenter')) {
  22. $this->error(__('User center already closed'));
  23. }
  24. }
  25. /**
  26. * 会员中心
  27. */
  28. public function index()
  29. {
  30. $this->success('', ['welcome' => $this->auth->nickname]);
  31. }
  32. /**
  33. * 会员登录
  34. *
  35. * @ApiMethod (POST)
  36. * @param string $account 账号
  37. * @param string $password 密码
  38. */
  39. public function login()
  40. {
  41. $account = $this->request->post('account');
  42. $password = $this->request->post('password');
  43. if (!$account || !$password) {
  44. $this->error(__('Invalid parameters'));
  45. }
  46. $ret = $this->auth->login($account, $password);
  47. if ($ret) {
  48. $data = ['userinfo' => $this->auth->getUserinfo()];
  49. $this->success(__('Logged in successful'), $data);
  50. } else {
  51. $this->error($this->auth->getError());
  52. }
  53. }
  54. /**
  55. * 手机验证码登录
  56. *
  57. * @ApiMethod (POST)
  58. * @param string $mobile 手机号
  59. * @param string $captcha 验证码
  60. */
  61. public function mobilelogin()
  62. {
  63. $mobile = $this->request->post('mobile');
  64. $captcha = $this->request->post('captcha');
  65. $introcode = $this->request->post('introcode','');
  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. //
  76. $intro_uid = 0;
  77. if(!empty($introcode)){
  78. $intro_uid = Db::name('user')->where('introcode',$introcode)->value('id');
  79. if(empty($intro_uid)){
  80. $this->error('请填写正确的邀请码或者不填');
  81. }
  82. }
  83. $user = \app\common\model\User::getByMobile($mobile);
  84. if ($user) {
  85. if ($user->status != 'normal') {
  86. $this->error(__('Account is locked'));
  87. }
  88. //如果已经有账号则直接登录
  89. $ret = $this->auth->direct($user->id);
  90. } else {
  91. // 用户信息不存在时使用
  92. $extend = [
  93. 'intro_uid' => $intro_uid,
  94. ];
  95. $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, $extend);
  96. }
  97. if ($ret) {
  98. Sms::flush($mobile, 'mobilelogin');
  99. $data = ['userinfo' => $this->auth->getUserinfo()];
  100. $this->success(__('Logged in successful'), $data);
  101. } else {
  102. $this->error($this->auth->getError());
  103. }
  104. }
  105. /**
  106. * 注册会员
  107. *
  108. * @ApiMethod (POST)
  109. * @param string $username 用户名
  110. * @param string $password 密码
  111. * @param string $email 邮箱
  112. * @param string $mobile 手机号
  113. * @param string $code 验证码
  114. */
  115. public function register()
  116. {
  117. $username = $this->request->post('username');
  118. $password = $this->request->post('password');
  119. $email = $this->request->post('email');
  120. $mobile = $this->request->post('mobile');
  121. $code = $this->request->post('code');
  122. if (!$username || !$password) {
  123. $this->error(__('Invalid parameters'));
  124. }
  125. if ($email && !Validate::is($email, "email")) {
  126. $this->error(__('Email is incorrect'));
  127. }
  128. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  129. $this->error(__('Mobile is incorrect'));
  130. }
  131. $ret = Sms::check($mobile, $code, 'register');
  132. if (!$ret) {
  133. $this->error(__('Captcha is incorrect'));
  134. }
  135. $ret = $this->auth->register($username, $password, $email, $mobile, []);
  136. if ($ret) {
  137. $data = ['userinfo' => $this->auth->getUserinfo()];
  138. $this->success(__('Sign up successful'), $data);
  139. } else {
  140. $this->error($this->auth->getError());
  141. }
  142. }
  143. /**
  144. * 退出登录
  145. * @ApiMethod (POST)
  146. */
  147. public function logout()
  148. {
  149. if (!$this->request->isPost()) {
  150. $this->error(__('Invalid parameters'));
  151. }
  152. $this->auth->logout();
  153. $this->success(__('Logout successful'));
  154. }
  155. /**
  156. * 修改会员个人信息
  157. *
  158. * @ApiMethod (POST)
  159. * @param string $avatar 头像地址
  160. * @param string $username 用户名
  161. * @param string $nickname 昵称
  162. * @param string $bio 个人简介
  163. */
  164. public function profile()
  165. {
  166. $user = $this->auth->getUser();
  167. $username = $this->request->post('username');
  168. $nickname = $this->request->post('nickname');
  169. $bio = $this->request->post('bio');
  170. $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
  171. if ($username) {
  172. $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
  173. if ($exists) {
  174. $this->error(__('Username already exists'));
  175. }
  176. $user->username = $username;
  177. }
  178. if ($nickname) {
  179. $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
  180. if ($exists) {
  181. $this->error(__('Nickname already exists'));
  182. }
  183. $user->nickname = $nickname;
  184. }
  185. $user->bio = $bio;
  186. $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. }