User.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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\library\WxPublic;
  7. use app\common\model\Area;
  8. use app\common\model\Guest;
  9. use app\common\model\User as U;
  10. use app\common\model\UserSign;
  11. use app\common\service\ScoreSend;
  12. use EasyWeChat\Kernel\Exceptions\DecryptException;
  13. use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
  14. use fast\Mini;
  15. use fast\Random;
  16. use think\Config;
  17. use think\Db;
  18. use think\Log;
  19. use think\Validate;
  20. use app\common\model\User as UserModel;
  21. /**
  22. * 会员接口
  23. */
  24. class User extends Api
  25. {
  26. protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'third','userminilogin','minilogin','wxp'];
  27. protected $noNeedRight='*';
  28. public function _initialize()
  29. {
  30. parent::_initialize();
  31. if (!Config::get('fastadmin.usercenter')) {
  32. $this->error(__('User center already closed'));
  33. }
  34. }
  35. /**
  36. * 会员信息
  37. * @ApiReturnParams (name=id,description=用户ID)
  38. * @ApiReturnParams (name=username,description=用户名)
  39. * @ApiReturnParams (name=nickname,description=昵称)
  40. * @ApiReturnParams (name=mobile,description=手机号)
  41. * @ApiReturnParams (name=avatar,description=头像)
  42. * @ApiReturnParams (name=age,description=年龄)
  43. * @ApiReturnParams (name=gender,description="性别1男2女")
  44. * @ApiReturnParams (name=level_text,description=会员级别标题)
  45. * @ApiReturnParams (name=level,description="会员级别,0游客10安检员20正式会员")
  46. * @ApiReturnParams (name=money,description=余额)
  47. * @ApiReturnParams (name=has_follow,description=是否关注)
  48. * @ApiReturnParams (name=verification,description=认证信息)
  49. * @ApiReturnParams (name=province,description=省对象)
  50. * @ApiReturnParams (name=city,description=市对象)
  51. * @ApiReturnParams (name=county,description=县对象)
  52. * @ApiReturnParams (name=wenda_num,description=问答记录数量)
  53. * @ApiReturnParams (name=follow_count,description=关注数量)
  54. * @ApiReturnParams (name=has_answered,description=是否已答过题)
  55. * @ApiReturnParams (name=userinfo[custom][key],description=自定义资料key)
  56. * @ApiReturnParams (name=userinfo[custom][title],description=自定义资料名称)
  57. * @ApiReturnParams (name=userinfo[custom][value],description=自定义资料值)
  58. */
  59. public function index()
  60. {
  61. $user=$this->auth->getUser();
  62. if(!$user['userinfo']){
  63. $user->userinfo()->save([]);
  64. }
  65. $user=$user
  66. ->append([
  67. 'verification',
  68. 'province',
  69. 'city',
  70. 'county',
  71. 'userinfo',
  72. 'has_answered'
  73. ]);
  74. $user['wenda_num']=$user->pointUser()->count();
  75. $user['follow_count']=$user->follow()->count();
  76. $this->success('', $user);
  77. }
  78. /**
  79. * 会员登录
  80. *
  81. * @ApiMethod (POST)
  82. * @param string $account 账号
  83. * @param string $password 密码
  84. */
  85. public function login()
  86. {
  87. $account = $this->request->post('account');
  88. $password = $this->request->post('password');
  89. if (!$account || !$password) {
  90. $this->error(__('Invalid parameters'));
  91. }
  92. $ret = $this->auth->login($account, $password);
  93. if ($ret) {
  94. $data = ['userinfo' => $this->auth->getUserinfo()];
  95. $this->success(__('Logged in successful'), $data);
  96. } else {
  97. $this->error($this->auth->getError());
  98. }
  99. }
  100. /**
  101. * 手机验证码登录
  102. *
  103. * @ApiMethod (POST)
  104. * @param string $mobile 手机号
  105. * @param string $captcha 验证码
  106. */
  107. public function mobilelogin()
  108. {
  109. $mobile = $this->request->post('mobile');
  110. $captcha = $this->request->post('captcha');
  111. if (!$mobile || !$captcha) {
  112. $this->error(__('Invalid parameters'));
  113. }
  114. if (!Validate::regex($mobile, "^1\d{10}$")) {
  115. $this->error(__('Mobile is incorrect'));
  116. }
  117. if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
  118. $this->error(__('Captcha is incorrect'));
  119. }
  120. $user = UserModel::getByMobile($mobile);
  121. if ($user) {
  122. if ($user->status != 'normal') {
  123. $this->error(__('Account is locked'));
  124. }
  125. //如果已经有账号则直接登录
  126. $ret = $this->auth->direct($user->id);
  127. } else {
  128. $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
  129. }
  130. if ($ret) {
  131. Sms::flush($mobile, 'mobilelogin');
  132. $data = ['userinfo' => $this->auth->getUserinfo()];
  133. $this->success(__('Logged in successful'), $data);
  134. } else {
  135. $this->error($this->auth->getError());
  136. }
  137. }
  138. /**
  139. * 注册会员
  140. *
  141. * @ApiMethod (POST)
  142. * @ApiParams (name=username,description="用户名")
  143. * @ApiParams (name=password,description="密码")
  144. * @ApiParams (name=email,description="邮箱")
  145. * @ApiParams (name=mobile,description="手机号")
  146. * @ApiParams (name=code,description="验证码")
  147. */
  148. public function register()
  149. {
  150. $username = $this->request->post('username');
  151. $password = $this->request->post('password');
  152. $email = $this->request->post('email');
  153. $mobile = $this->request->post('mobile');
  154. $code = $this->request->post('code');
  155. if (!$username || !$password) {
  156. $this->error(__('Invalid parameters'));
  157. }
  158. if ($email && !Validate::is($email, "email")) {
  159. $this->error(__('Email is incorrect'));
  160. }
  161. if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
  162. $this->error(__('Mobile is incorrect'));
  163. }
  164. $ret = Sms::check($mobile, $code, 'register');
  165. if (!$ret) {
  166. $this->error(__('Captcha is incorrect'));
  167. }
  168. $ret = $this->auth->register($username, $password, $email, $mobile);
  169. if ($ret) {
  170. $data = ['userinfo' => $this->auth->getUserinfo()];
  171. $this->success(__('Sign up successful'), $data);
  172. } else {
  173. $this->error($this->auth->getError());
  174. }
  175. }
  176. /**
  177. * 修改会员个人信息
  178. *
  179. * @ApiMethod (POST)
  180. * @ApiParams (name=avatar,description=头像地址)
  181. * @ApiParams (name=nickname,description=昵称)
  182. * @ApiParams (name=bio,description=个人简介)
  183. * @ApiParams (name=age,description=年龄)
  184. * @ApiParams (name=gender,description="性别1男2女")
  185. * @ApiParams (name=county_id,description=区县ID)
  186. * @ApiParams (name="custom[xxxx]",description="自定义资料放这里")
  187. * @ApiReturnParams (name=score,description="赠送的积分数量")
  188. */
  189. public function profile(ScoreSend $score)
  190. {
  191. $data=$this->_validate([
  192. 'avatar|头像'=>['require','url'],
  193. 'nickname|昵称'=>['require','max:12'],
  194. 'age|年龄'=>['require','integer','gt:0'],
  195. //'county_id|地区'=>['require','integer','gt:0'],
  196. 'county_id|地区'=>['require'],
  197. 'gender|性别'=>['require','integer','in:1,2'],
  198. 'bio|性别'=>['max:100'],
  199. ]);
  200. $user = $this->auth->getUser();
  201. Db::startTrans();
  202. $user= UserModel::lock(true)->find($user->id);
  203. $nickname = $data['nickname']??'';
  204. $bio = $data['bio'];
  205. $avatar = $data['avatar']??'';
  206. if ($nickname) {
  207. /*$exists = UserModel::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
  208. if ($exists) {
  209. $this->error(__('Nickname already exists'));
  210. }*/
  211. $user->nickname = $nickname;
  212. }
  213. if($bio) {
  214. $user->bio = $bio;
  215. }
  216. if($avatar) {
  217. $user->avatar = $avatar;
  218. }
  219. if(!empty($data['age'])){
  220. $user->age=$data['age'];
  221. }
  222. if(isset($data['gender'])){
  223. $user->gender=$data['gender'];
  224. }
  225. if(!empty($data['county_id'])){
  226. $county=Area::area()->where('name|shortname',$data['county_id'])->find();
  227. if(!$county) {
  228. $this->error('地区不存在');
  229. }
  230. $user->county_id=$county['id'];
  231. $user->city_id=$county['pid'];
  232. $user->province_id=Area::where('id',$county['pid'])->value('pid');
  233. }
  234. $user->save();
  235. $custom=array_column($user->userinfo->custom,'value','key');
  236. foreach (config('site.userApprove')?:[] as $key=>$value){
  237. if(!empty($data['custom'][$key])){
  238. $custom[$key]=$data['custom'][$key];
  239. }
  240. }
  241. if($custom) {
  242. $user->userinfo->save(['custom' => $custom]);
  243. }
  244. $scoreNum=$score->setUser($user)->setField('score')->setMemo('完善资料')->setConfig('score_editInfo')->onlyOne();
  245. Db::commit();
  246. $this->success('',[
  247. 'score'=>$scoreNum,
  248. ]);
  249. }
  250. /**
  251. * 退出登录
  252. * @ApiMethod (POST)
  253. */
  254. public function logout()
  255. {
  256. if (!$this->request->isPost()) {
  257. $this->error(__('Invalid parameters'));
  258. }
  259. $this->auth->logout();
  260. $this->success(__('Logout successful'));
  261. }
  262. /**
  263. * 修改邮箱
  264. *
  265. * @ApiMethod (POST)
  266. * @param string $email 邮箱
  267. * @param string $captcha 验证码
  268. */
  269. public function changeemail()
  270. {
  271. $user = $this->auth->getUser();
  272. $email = $this->request->post('email');
  273. $captcha = $this->request->post('captcha');
  274. if (!$email || !$captcha) {
  275. $this->error(__('Invalid parameters'));
  276. }
  277. if (!Validate::is($email, "email")) {
  278. $this->error(__('Email is incorrect'));
  279. }
  280. if (UserModel::where('email', $email)->where('id', '<>', $user->id)->find()) {
  281. $this->error(__('Email already exists'));
  282. }
  283. $result = Ems::check($email, $captcha, 'changeemail');
  284. if (!$result) {
  285. $this->error(__('Captcha is incorrect'));
  286. }
  287. $verification = $user->verification;
  288. $verification->email = 1;
  289. $user->verification = $verification;
  290. $user->email = $email;
  291. $user->save();
  292. Ems::flush($email, 'changeemail');
  293. $this->success();
  294. }
  295. /**
  296. * 修改手机号
  297. *
  298. * @ApiMethod (POST)
  299. * @param string $mobile 手机号
  300. * @param string $captcha 验证码
  301. */
  302. public function changemobile()
  303. {
  304. $user = $this->auth->getUser();
  305. $mobile = $this->request->post('mobile');
  306. $captcha = $this->request->post('captcha');
  307. if (!$mobile || !$captcha) {
  308. $this->error(__('Invalid parameters'));
  309. }
  310. if (!Validate::regex($mobile, "^1\d{10}$")) {
  311. $this->error(__('Mobile is incorrect'));
  312. }
  313. if (UserModel::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
  314. $this->error(__('Mobile already exists'));
  315. }
  316. $result = Sms::check($mobile, $captcha, 'changemobile');
  317. if (!$result) {
  318. $this->error(__('Captcha is incorrect'));
  319. }
  320. $user->mobile=$mobile;
  321. $user->save();
  322. Sms::flush($mobile, 'changemobile');
  323. $this->success();
  324. }
  325. /**
  326. * 第三方登录
  327. *
  328. * @ApiMethod (POST)
  329. * @param string $platform 平台名称
  330. * @param string $code Code码
  331. */
  332. public function third()
  333. {
  334. $this->error('功能已禁用');
  335. $url = url('user/index');
  336. $platform = $this->request->post("platform");
  337. $code = $this->request->post("code");
  338. $config = get_addon_config('third');
  339. if (!$config || !isset($config[$platform])) {
  340. $this->error(__('Invalid parameters'));
  341. }
  342. $app = new \addons\third\library\Application($config);
  343. //通过code换access_token和绑定会员
  344. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  345. if ($result) {
  346. $loginret = \addons\third\library\Service::connect($platform, $result);
  347. if ($loginret) {
  348. $data = [
  349. 'userinfo' => $this->auth->getUserinfo(),
  350. 'thirdinfo' => $result
  351. ];
  352. $this->success(__('Logged in successful'), $data);
  353. }
  354. }
  355. $this->error(__('Operation failed'), $url);
  356. }
  357. /**
  358. * 重置密码
  359. *
  360. * @ApiMethod (POST)
  361. * @param string $mobile 手机号
  362. * @param string $newpassword 新密码
  363. * @param string $captcha 验证码
  364. */
  365. public function resetpwd()
  366. {
  367. $type = $this->request->post("type");
  368. $mobile = $this->request->post("mobile");
  369. $email = $this->request->post("email");
  370. $newpassword = $this->request->post("newpassword");
  371. $captcha = $this->request->post("captcha");
  372. if (!$newpassword || !$captcha) {
  373. $this->error(__('Invalid parameters'));
  374. }
  375. if ($type == 'mobile') {
  376. if (!Validate::regex($mobile, "^1\d{10}$")) {
  377. $this->error(__('Mobile is incorrect'));
  378. }
  379. $user = UserModel::getByMobile($mobile);
  380. if (!$user) {
  381. $this->error(__('User not found'));
  382. }
  383. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  384. if (!$ret) {
  385. $this->error(__('Captcha is incorrect'));
  386. }
  387. Sms::flush($mobile, 'resetpwd');
  388. } else {
  389. if (!Validate::is($email, "email")) {
  390. $this->error(__('Email is incorrect'));
  391. }
  392. $user = UserModel::getByEmail($email);
  393. if (!$user) {
  394. $this->error(__('User not found'));
  395. }
  396. $ret = Ems::check($email, $captcha, 'resetpwd');
  397. if (!$ret) {
  398. $this->error(__('Captcha is incorrect'));
  399. }
  400. Ems::flush($email, 'resetpwd');
  401. }
  402. //模拟一次登录
  403. $this->auth->direct($user->id);
  404. $ret = $this->auth->changepwd($newpassword, '', true);
  405. if ($ret) {
  406. $this->success(__('Reset password successful'));
  407. } else {
  408. $this->error($this->auth->getError());
  409. }
  410. }
  411. /**
  412. * 小程序登录
  413. * @ApiMethod (POST)
  414. * @ApiParams (name=code,description="小程序code")
  415. * @ApiParams (name=mob_brand,description="手机品牌")
  416. * @ApiParams (name=mob_model,description="手机型号")
  417. */
  418. public function minilogin(){
  419. $data=input();
  420. $this->validate($data,[
  421. 'code'=>'require',
  422. 'mob_brand'=>'require',
  423. 'mob_model'=>'require',
  424. //'encryptedData'=>'require',
  425. //'iv'=>'require',
  426. ]);
  427. $session=Mini::mini()->auth->session($data['code']);
  428. //$decryptedData = Mini::mini()->encryptor->decryptData($session, $data['iv'], $data['encryptedData']);
  429. $user=\app\admin\model\User::where('openid',$session['openid'])->find();
  430. user_log('minilogin',"code:{$data['code']},session:".json_encode($session).',user:'.json_encode($user));
  431. //$user1=\app\admin\model\User::where('mobile',$decryptedData['phoneNumber'])->find();
  432. //$user=$user?:$user1;
  433. if(!$user){
  434. $ret = $this->auth->register($username=session_create_id(), '', '', $decryptedData['phoneNumber']??'', [
  435. 'openid'=>$session['openid'],
  436. 'mob_brand'=>$data['mob_brand'],
  437. 'nickname'=>'游客',
  438. 'mob_model'=>$data['mob_model'],
  439. 'unionid'=>$session['unionid']??'',
  440. ]);
  441. if ($ret) {
  442. $data = ['userinfo' => $this->auth->getUserinfo()];
  443. $this->success(__('Sign up successful'), $data);
  444. } else {
  445. $this->error($this->auth->getError());
  446. }
  447. }else{
  448. $user['unionid']=$session['unionid']??'';
  449. $user['mob_brand']=$data['mob_brand'];
  450. $user['mob_model']=$data['mob_model'];
  451. $user->save();
  452. }
  453. $this->auth->direct($user['id']);
  454. $data = ['userinfo' => $this->auth->getUserinfo()];
  455. $this->success(__('successful'), $data);
  456. }
  457. /**
  458. * 授权获取手机号
  459. * @ApiParams (name=code,description="小程序code")
  460. * @ApiParams (name=encryptedData,description="encryptedData")
  461. * @ApiParams (name=iv,description="iv")
  462. */
  463. public function wx_mobile(){
  464. $data=$this->_validate([
  465. 'code'=>'require',
  466. 'encryptedData'=>'require',
  467. 'iv'=>'require',
  468. ]);
  469. $user=$this->auth->getUser();
  470. try {
  471. $session=Mini::mini()->auth->session($data['code']);
  472. $decryptedData = Mini::mini()->encryptor->decryptData($session, $data['iv'], $data['encryptedData']);
  473. $user['mobile']=$decryptedData['phoneNumber'];
  474. $user->save();
  475. } catch (DecryptException | InvalidConfigException $e) {
  476. $this->error(sprintf("授权失败(%s)",$e->getMessage()));
  477. }
  478. $this->success('',$user);
  479. }
  480. /**
  481. * 关注取消关注博主
  482. * @ApiParams (name=id,description=博主ID)
  483. * @ApiParams (name=status,description=1关注2取消)
  484. */
  485. public function follow(){
  486. $data=$this->_validate([
  487. 'status'=>'require',
  488. 'id'=>'require',
  489. ]);
  490. $user=$this->auth->getUser();
  491. if($data['status']==1) {
  492. if(!Guest::find($data['id'])){
  493. $this->error('博主不存在');
  494. }
  495. if($user->follow()->guest($data['id'])->find()){
  496. $this->error('您已关注');
  497. }
  498. $user->follow()->attach($data['id']);
  499. }else{
  500. $user->follow()->detach($data['id']);
  501. }
  502. $this->success();
  503. }
  504. /**
  505. * 关注列表
  506. * @ApiParams (name=limit,description=每页数量)
  507. * @ApiParams (name=page,description=第几页)
  508. * @ApiReturnParams (name=id,description=博主ID)
  509. * @ApiReturnParams (name=name,description=名称)
  510. * @ApiReturnParams (name=logo,description=logo)
  511. */
  512. public function my_follow(){
  513. $user=$this->auth->getUser();
  514. $list=$user->follow()
  515. ->paginate(input('limit'));
  516. $this->success('',$list);
  517. }
  518. /**
  519. * 已签到日期列表
  520. * @ApiParams (name=date,description="月份,2020-02")
  521. */
  522. public function sign_list(){
  523. $data=$this->_validate([
  524. 'date'=>['require','date'],
  525. ]);
  526. $user=$this->auth->getUser();
  527. $data=$user->sign()->where('date','>=',$data['date'])->column('date');
  528. $this->success('',$data);
  529. }
  530. /**
  531. * 签到
  532. * @ApiReturnParams (name=score,description="赠送积分数量")
  533. */
  534. public function sign(ScoreSend $send){
  535. $user=$this->auth->getUser();
  536. $date=date('Y-m-d');
  537. Db::startTrans();
  538. if($user->sign()->where('date',$date)->find()){
  539. Db::rollback();
  540. $this->error('您已签到');
  541. }
  542. $sign=$user->sign()->save([
  543. 'date'=>$date,
  544. ]);
  545. $finally=['score'=>0];
  546. $finally['score']=$send->setUser($user)->setField('score')->setMemo("[{$date}]签到")->setObject(['user_sign',$sign['id']])->setConfig('score_sign')->onlyOne();
  547. Db::commit();
  548. $this->success('',$finally);
  549. }
  550. /**
  551. * 微信公众号登录获取参数
  552. * @ApiParams (name=redirect_uri,description=跳转链接)
  553. */
  554. public function wxp(WxPublic $wxPublic){
  555. $this->validate($data=input(),[
  556. 'redirect_uri'=>['require'],
  557. ]);
  558. $url=$wxPublic->getApp()->oauth->redirect($data['redirect_uri'])->getTargetUrl();
  559. $this->success('',[
  560. 'url'=>$url,
  561. ]);
  562. }
  563. /**
  564. * 微信公众号登录
  565. * @ApiParams (name=code,description=微信code)
  566. * @ApiReturnParams (name=userinfo.nickname,description=昵称)
  567. * @ApiReturnParams (name=userinfo.avatar,description=头像)
  568. */
  569. public function wxp_handle(WxPublic $wxPublic){
  570. $this->validate($data=input(),[
  571. 'code'=>['require'],
  572. ]);
  573. $user=$wxPublic->getApp()->oauth->user();
  574. $localUser=U::where('wxp_openid',$user->getId())->find();
  575. if($localUser){
  576. $this->auth->direct($localUser['id']);
  577. }else{
  578. $reg=$this->auth->register(session_create_id(),session_create_id(),'','',[
  579. 'wxp_openid'=>$user->getId(),
  580. 'nickname'=>$user->getNickname(),
  581. 'avatar'=>$user->getAvatar(),
  582. ]);
  583. if(!$reg){
  584. $this->error('注册失败'.$this->auth->getError());
  585. }
  586. }
  587. $data = [
  588. 'userinfo' => $this->auth->getUserinfo(),
  589. ];
  590. $this->success(__('Logged in successful'), $data);
  591. }
  592. }