User.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 != 1) {
  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. public function getUserinfo(){
  106. $info = $this->auth->getUserinfo();
  107. $this->success(1,$info);
  108. }
  109. /**
  110. * 注册会员
  111. *
  112. * @ApiMethod (POST)
  113. * @param string $username 用户名
  114. * @param string $password 密码
  115. * @param string $email 邮箱
  116. * @param string $mobile 手机号
  117. * @param string $code 验证码
  118. */
  119. public function register()
  120. {
  121. $username = $this->request->post('username');
  122. $password = $this->request->post('password');
  123. $email = $this->request->post('email');
  124. $mobile = $this->request->post('mobile');
  125. $code = $this->request->post('code');
  126. if (!$username || !$password) {
  127. $this->error(__('Invalid parameters'));
  128. }
  129. if ($email && !Validate::is($email, "email")) {
  130. $this->error(__('Email is incorrect'));
  131. }
  132. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  133. $this->error(__('Mobile is incorrect'));
  134. }
  135. $ret = Sms::check($mobile, $code, 'register');
  136. if (!$ret) {
  137. $this->error(__('Captcha is incorrect'));
  138. }
  139. $ret = $this->auth->register($username, $password, $email, $mobile, []);
  140. if ($ret) {
  141. $data = ['userinfo' => $this->auth->getUserinfo()];
  142. $this->success(__('Sign up successful'), $data);
  143. } else {
  144. $this->error($this->auth->getError());
  145. }
  146. }
  147. /**
  148. * 退出登录
  149. * @ApiMethod (POST)
  150. */
  151. public function logout()
  152. {
  153. if (!$this->request->isPost()) {
  154. $this->error(__('Invalid parameters'));
  155. }
  156. $this->auth->logout();
  157. $this->success(__('Logout successful'));
  158. }
  159. /**
  160. * 修改会员个人信息
  161. *
  162. * @ApiMethod (POST)
  163. * @param string $avatar 头像地址
  164. * @param string $username 用户名
  165. * @param string $nickname 昵称
  166. * @param string $bio 个人简介
  167. */
  168. public function profile()
  169. {
  170. $user = $this->auth->getUser();
  171. $nickname = $this->request->post('nickname');
  172. $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
  173. $user->nickname = $nickname;
  174. $user->avatar = $avatar;
  175. $user->save();
  176. $this->success();
  177. }
  178. /**
  179. * 修改邮箱
  180. *
  181. * @ApiMethod (POST)
  182. * @param string $email 邮箱
  183. * @param string $captcha 验证码
  184. */
  185. public function changeemail()
  186. {
  187. $user = $this->auth->getUser();
  188. $email = $this->request->post('email');
  189. $captcha = $this->request->post('captcha');
  190. if (!$email || !$captcha) {
  191. $this->error(__('Invalid parameters'));
  192. }
  193. if (!Validate::is($email, "email")) {
  194. $this->error(__('Email is incorrect'));
  195. }
  196. if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
  197. $this->error(__('Email already exists'));
  198. }
  199. $result = Ems::check($email, $captcha, 'changeemail');
  200. if (!$result) {
  201. $this->error(__('Captcha is incorrect'));
  202. }
  203. $verification = $user->verification;
  204. $verification->email = 1;
  205. $user->verification = $verification;
  206. $user->email = $email;
  207. $user->save();
  208. Ems::flush($email, 'changeemail');
  209. $this->success();
  210. }
  211. /**
  212. * 修改手机号
  213. *
  214. * @ApiMethod (POST)
  215. * @param string $mobile 手机号
  216. * @param string $captcha 验证码
  217. */
  218. public function changemobile()
  219. {
  220. $user = $this->auth->getUser();
  221. $mobile = $this->request->post('mobile');
  222. $captcha = $this->request->post('captcha');
  223. if (!$mobile || !$captcha) {
  224. $this->error(__('Invalid parameters'));
  225. }
  226. if (!Validate::regex($mobile, "^1\d{10}$")) {
  227. $this->error(__('Mobile is incorrect'));
  228. }
  229. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  230. $this->error(__('Mobile already exists'));
  231. }
  232. $result = Sms::check($mobile, $captcha, 'changemobile');
  233. if (!$result) {
  234. $this->error(__('Captcha is incorrect'));
  235. }
  236. $verification = $user->verification;
  237. $verification->mobile = 1;
  238. $user->verification = $verification;
  239. $user->mobile = $mobile;
  240. $user->save();
  241. Sms::flush($mobile, 'changemobile');
  242. $this->success();
  243. }
  244. /**
  245. * 第三方登录
  246. *
  247. * @ApiMethod (POST)
  248. * @param string $platform 平台名称
  249. * @param string $code Code码
  250. */
  251. public function third()
  252. {
  253. $url = url('user/index');
  254. $platform = $this->request->post("platform");
  255. $code = $this->request->post("code");
  256. $config = get_addon_config('third');
  257. if (!$config || !isset($config[$platform])) {
  258. $this->error(__('Invalid parameters'));
  259. }
  260. $app = new \addons\third\library\Application($config);
  261. //通过code换access_token和绑定会员
  262. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  263. if ($result) {
  264. $loginret = \addons\third\library\Service::connect($platform, $result);
  265. if ($loginret) {
  266. $data = [
  267. 'userinfo' => $this->auth->getUserinfo(),
  268. 'thirdinfo' => $result
  269. ];
  270. $this->success(__('Logged in successful'), $data);
  271. }
  272. }
  273. $this->error(__('Operation failed'), $url);
  274. }
  275. /**
  276. * 重置密码
  277. *
  278. * @ApiMethod (POST)
  279. * @param string $mobile 手机号
  280. * @param string $newpassword 新密码
  281. * @param string $captcha 验证码
  282. */
  283. public function resetpwd()
  284. {
  285. $type = $this->request->post("type");
  286. $mobile = $this->request->post("mobile");
  287. $email = $this->request->post("email");
  288. $newpassword = $this->request->post("newpassword");
  289. $captcha = $this->request->post("captcha");
  290. if (!$newpassword || !$captcha) {
  291. $this->error(__('Invalid parameters'));
  292. }
  293. //验证Token
  294. if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
  295. $this->error(__('Password must be 6 to 30 characters'));
  296. }
  297. if ($type == 'mobile') {
  298. if (!Validate::regex($mobile, "^1\d{10}$")) {
  299. $this->error(__('Mobile is incorrect'));
  300. }
  301. $user = \app\common\model\User::getByMobile($mobile);
  302. if (!$user) {
  303. $this->error(__('User not found'));
  304. }
  305. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  306. if (!$ret) {
  307. $this->error(__('Captcha is incorrect'));
  308. }
  309. Sms::flush($mobile, 'resetpwd');
  310. } else {
  311. if (!Validate::is($email, "email")) {
  312. $this->error(__('Email is incorrect'));
  313. }
  314. $user = \app\common\model\User::getByEmail($email);
  315. if (!$user) {
  316. $this->error(__('User not found'));
  317. }
  318. $ret = Ems::check($email, $captcha, 'resetpwd');
  319. if (!$ret) {
  320. $this->error(__('Captcha is incorrect'));
  321. }
  322. Ems::flush($email, 'resetpwd');
  323. }
  324. //模拟一次登录
  325. $this->auth->direct($user->id);
  326. $ret = $this->auth->changepwd($newpassword, '', true);
  327. if ($ret) {
  328. $this->success(__('Reset password successful'));
  329. } else {
  330. $this->error($this->auth->getError());
  331. }
  332. }
  333. /**
  334. * 获取用户openid
  335. */
  336. public function getUserOpenid() {
  337. // code值
  338. $code = $this->request->param('code');
  339. if (!$code) {
  340. $this->error(__('Invalid parameters'));
  341. }
  342. $config = config('wxMiniProgram');
  343. $getopenid = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appid'].'&secret='.$config['secret'].'&js_code='.$code.'&grant_type=authorization_code';
  344. $openidInfo = $this->getJson($getopenid);
  345. if(!isset($openidInfo['openid'])) {
  346. $this->error('用户openid获取失败',$openidInfo);
  347. }
  348. // 获取的结果存入数据库
  349. $find = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->find();
  350. if($find) {
  351. $update = [];
  352. $update['sessionkey'] = $openidInfo['session_key'];
  353. $update['createtime'] = time();
  354. $res = Db::name('user_sessionkey')->where(['openid'=>$openidInfo['openid']])->update($update);
  355. } else {
  356. $insert = [];
  357. $insert['sessionkey'] = $openidInfo['session_key'];
  358. $insert['openid'] = $openidInfo['openid'];
  359. $insert['unionid'] = isset($openidInfo['unionid']) ? $openidInfo['unionid'] : '';
  360. $insert['createtime'] = time();
  361. $res = Db::name('user_sessionkey')->insertGetId($insert);
  362. }
  363. if($res !== false) {
  364. $this->success('获取成功',$openidInfo);
  365. } else {
  366. $this->error('获取失败');
  367. }
  368. }
  369. /**
  370. * 微信小程序登录
  371. */
  372. public function wxMiniProgramLogin() {
  373. $openid = $this->request->request('openid');// openid值
  374. $encryptedData = $this->request->request('encryptedData');// 加密数据
  375. $iv = $this->request->request('iv');// 加密算法
  376. $signature = $this->request->request('signature');// 签名验证
  377. $rawData = $this->request->request('rawData');// 签名验证
  378. $logintype = 2;// 登录方式:1=手机号,2=微信授权openid
  379. if (!$openid || !$encryptedData || !$iv) {
  380. $this->error(__('Invalid parameters'));
  381. }
  382. // 获取openid和sessionkey
  383. $config = config('wxMiniProgram');
  384. $openidInfo = Db::name('user_sessionkey')->where(['openid'=>$openid])->find();
  385. $openid = $openidInfo['openid'];
  386. $session_key = $openidInfo['sessionkey'];
  387. // // 数据签名校验
  388. // $signature2 = sha1($rawData . $session_key);
  389. // if ($signature != $signature2) {
  390. // $this->error(__('数据签名验证失败'));
  391. // }
  392. // 根据加密数据和加密算法获取用户信息
  393. $pc = new WXBizDataCrypt($config['appid'], $session_key);
  394. $data = '';
  395. $errCode = $pc->decryptData(urldecode($encryptedData), $iv, $data);
  396. if ($errCode != 0) {
  397. $this->error('解密失败',['code'=>$errCode]);
  398. }
  399. $data = json_decode($data,true);
  400. // 用户登录逻辑 === 开始
  401. if($logintype == 1) { // 手机号登录
  402. /*$userInfo = Db::name('user')->where(["mobile"=>$data["purePhoneNumber"]])->find();
  403. // 用户信息不存在时使用
  404. $extend = ["mobile"=>$data["purePhoneNumber"]];*/
  405. } else { // 微信授权openid登录
  406. $userInfo = Db::name('user')->where(['mini_openid'=>$openid])->find();
  407. // 用户信息不存在时使用
  408. $extend = [
  409. 'mini_openid' => $openid,
  410. 'nickname' => $data['nickName'],
  411. 'avatar' => $data['avatarUrl'],
  412. //'gender' => $data['gender']==1 ? 1 : 0,
  413. 'mini_sessionkey'=> $session_key,
  414. 'unionid' => $openidInfo['unionid'],
  415. //'mobile' => $data['purePhoneNumber'],
  416. ];
  417. }
  418. // 判断用户是否已经存在
  419. if($userInfo) { // 登录
  420. Db::name('user')->where('id',$userInfo['id'])->update(['logintime'=>time()]);
  421. $res = $this->auth->direct($userInfo['id']);
  422. } else { // 注册
  423. // 先随机一个用户名,随后再变更为u+数字id
  424. $username = '';
  425. $password = '';
  426. /*Db::startTrans();
  427. try {*/
  428. // 默认注册一个会员
  429. $result = $this->auth->register($username, $password, '','', $extend);
  430. if (!$result) {
  431. $this->error("注册失败!");
  432. }
  433. /* Db::commit();
  434. } catch (PDOException $e) {
  435. Db::rollback();
  436. $this->auth->logout();
  437. return false;
  438. }*/
  439. // 写入登录Cookies和Token
  440. $res = $this->auth->direct($this->auth->id);
  441. }
  442. $userInfo = $this->userInfo('return');
  443. if($res) {
  444. $this->success("登录成功!",$userInfo);
  445. } else {
  446. $this->error("登录失败!");
  447. }
  448. }
  449. /**
  450. * json 请求
  451. * @param $url
  452. * @return mixed
  453. */
  454. private function getJson($url){
  455. $ch = curl_init();
  456. curl_setopt($ch, CURLOPT_URL, $url);
  457. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  458. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  459. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  460. $output = curl_exec($ch);
  461. curl_close($ch);
  462. return json_decode($output, true);
  463. }
  464. }