User.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. use app\common\library\Email;
  5. use app\common\library\Redis;
  6. use app\common\library\Sms;
  7. use app\main\constants\ErrorCodeConstants;
  8. use app\main\service\AdminService;
  9. use app\main\service\BookService;
  10. use app\main\service\LogService;
  11. use app\main\service\OpenPlatformService;
  12. use app\main\service\UserService;
  13. use EasyWeChat\Kernel\Messages\Text;
  14. use fast\Random;
  15. use think\Config;
  16. use think\Cookie;
  17. use think\Validate;
  18. /**
  19. * 会员接口
  20. */
  21. class User extends Api
  22. {
  23. protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
  24. protected $noNeedRight = '*';
  25. protected $redis;
  26. public function _initialize()
  27. {
  28. parent::_initialize();
  29. $this->redis = Redis::instance();
  30. }
  31. /**
  32. * 会员中心
  33. */
  34. public function index()
  35. {
  36. $this->success('', ['welcome' => $this->auth->nickname]);
  37. }
  38. /**
  39. * 会员登录
  40. *
  41. * @param string $account 账号
  42. * @param string $password 密码
  43. */
  44. public function login()
  45. {
  46. $account = $this->request->request('account');
  47. $password = $this->request->request('password');
  48. if (!$account || !$password)
  49. {
  50. $this->error(__('Invalid parameters'));
  51. }
  52. $ret = $this->auth->login($account, $password);
  53. if ($ret)
  54. {
  55. $data = ['userinfo' => $this->auth->getUserinfo()];
  56. $this->success(__('Logged in successful'), $data);
  57. }
  58. else
  59. {
  60. $this->error($this->auth->getError());
  61. }
  62. }
  63. /**
  64. * 手机验证码登录
  65. *
  66. * @param string $mobile 手机号
  67. * @param string $captcha 验证码
  68. */
  69. public function mobilelogin()
  70. {
  71. $mobile = $this->request->request('mobile');
  72. $captcha = $this->request->request('captcha');
  73. if (!$mobile || !$captcha)
  74. {
  75. $this->error(__('Invalid parameters'));
  76. }
  77. if (!Validate::regex($mobile, "^1\d{10}$"))
  78. {
  79. $this->error(__('Mobile incorrect'));
  80. }
  81. if (!Sms::check($mobile, $captcha, 'mobilelogin'))
  82. {
  83. $this->error(__('Captcha invalid'));
  84. }
  85. $user = \app\common\model\User::getByMobile($mobile);
  86. if ($user)
  87. {
  88. //如果已经有账号则直接登录
  89. $ret = $this->auth->direct($user->id);
  90. }
  91. else
  92. {
  93. $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
  94. }
  95. if ($ret)
  96. {
  97. Sms::flush($mobile, 'mobilelogin');
  98. $data = ['userinfo' => $this->auth->getUserinfo()];
  99. $this->success(__('Logged in successful'), $data);
  100. }
  101. else
  102. {
  103. $this->error($this->auth->getError());
  104. }
  105. }
  106. /**
  107. * 注册会员
  108. *
  109. * @param string $username 用户名
  110. * @param string $password 密码
  111. * @param string $email 邮箱
  112. * @param string $mobile 手机号
  113. */
  114. public function register()
  115. {
  116. $username = $this->request->request('username');
  117. $password = $this->request->request('password');
  118. $email = $this->request->request('email');
  119. $mobile = $this->request->request('mobile');
  120. if (!$username || !$password)
  121. {
  122. $this->error(__('Invalid parameters'));
  123. }
  124. if ($email && !Validate::is($email, "email"))
  125. {
  126. $this->error(__('Email incorrect'));
  127. }
  128. if ($mobile && !Validate::regex($mobile, "^1\d{10}$"))
  129. {
  130. $this->error(__('Mobile incorrect'));
  131. }
  132. $ret = $this->auth->register($username, $password, $email, $mobile, []);
  133. if ($ret)
  134. {
  135. $data = ['userinfo' => $this->auth->getUserinfo()];
  136. $this->success(__('Sign up successful'), $data);
  137. }
  138. else
  139. {
  140. $this->error($this->auth->getError());
  141. }
  142. }
  143. /**
  144. * 注销登录
  145. */
  146. public function logout()
  147. {
  148. $this->auth->logout();
  149. $this->success(__('Logout successful'));
  150. }
  151. /**
  152. * 修改会员个人信息
  153. *
  154. * @param string $avatar 头像地址
  155. * @param string $username 用户名
  156. * @param string $nickname 昵称
  157. * @param string $bio 个人简介
  158. */
  159. public function profile()
  160. {
  161. $user = $this->auth->getUser();
  162. $username = $this->request->request('username');
  163. $nickname = $this->request->request('nickname');
  164. $bio = $this->request->request('bio');
  165. $avatar = $this->request->request('avatar');
  166. $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
  167. if ($exists)
  168. {
  169. $this->error(__('Username already exists'));
  170. }
  171. $user->username = $username;
  172. $user->nickname = $nickname;
  173. $user->bio = $bio;
  174. $user->avatar = $avatar;
  175. $user->save();
  176. $this->success();
  177. }
  178. /**
  179. * 修改邮箱
  180. *
  181. * @param string $email 邮箱
  182. */
  183. public function changeemail()
  184. {
  185. $user = $this->auth->getUser();
  186. $email = $this->request->post('email');
  187. if (!$email)
  188. {
  189. $this->error(__('Invalid parameters'));
  190. }
  191. if (!Validate::is($email, "email"))
  192. {
  193. $this->error(__('Mobile incorrect'));
  194. }
  195. if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find())
  196. {
  197. $this->error(__('Email already exists'));
  198. }
  199. $verification = $user->verification;
  200. $verification->email = 0;
  201. $user->verification = $verification;
  202. $user->email = $email;
  203. $user->save();
  204. $time = time();
  205. $code = ['id' => $user->id, 'time' => $time, 'key' => md5(md5($user->id . $user->email . $time) . $user->salt)];
  206. $code = base64_encode(http_build_query($code));
  207. $url = url("index/user/activeemail", ['code' => $code], true, true);
  208. $message = __('Verify email') . ":<a href='{$url}'>{$url}</a>";
  209. Email::instance()->to($email)->subject(__('Verify email'))->message($message)->send();
  210. $this->success();
  211. }
  212. /**
  213. * 修改手机号
  214. *
  215. * @param string $email 手机号
  216. * @param string $captcha 验证码
  217. */
  218. public function changemobile()
  219. {
  220. $user = $this->auth->getUser();
  221. $mobile = $this->request->request('mobile');
  222. $captcha = $this->request->request('captcha');
  223. if (!$mobile || !$captcha)
  224. {
  225. $this->error(__('Invalid parameters'));
  226. }
  227. if (!Validate::regex($mobile, "^1\d{10}$"))
  228. {
  229. $this->error(__('Mobile incorrect'));
  230. }
  231. if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find())
  232. {
  233. $this->error(__('Mobile already exists'));
  234. }
  235. $result = Sms::check($mobile, $captcha, 'changemobile');
  236. if (!$result)
  237. {
  238. $this->error(__('Captcha invalid'));
  239. }
  240. $verification = $user->verification;
  241. $verification->mobile = 1;
  242. $user->verification = $verification;
  243. $user->mobile = $mobile;
  244. $user->save();
  245. Sms::flush($mobile, 'changemobile');
  246. $this->success();
  247. }
  248. /**
  249. * 第三方登录
  250. *
  251. * @param string $platform 平台名称
  252. * @param string $code Code码
  253. */
  254. public function third()
  255. {
  256. $url = url('user/index');
  257. $platform = $this->request->request("platform");
  258. $code = $this->request->request("code");
  259. $config = get_addon_config('third');
  260. if (!$config || !isset($config[$platform]))
  261. {
  262. $this->error(__('Invalid parameters'));
  263. }
  264. $app = new \addons\third\library\Application($config);
  265. //通过code换access_token和绑定会员
  266. $result = $app->{$platform}->getUserInfo(['code' => $code]);
  267. if ($result)
  268. {
  269. $loginret = \addons\third\library\Service::connect($platform, $result);
  270. if ($loginret)
  271. {
  272. $data = [
  273. 'userinfo' => $this->auth->getUserinfo(),
  274. 'thirdinfo' => $result
  275. ];
  276. $this->success(__('Logged in successful'), $data);
  277. }
  278. }
  279. $this->error(__('Operation failed'), $url);
  280. }
  281. /**
  282. * 重置密码
  283. *
  284. * @param string $mobile 手机号
  285. * @param string $newpassword 新密码
  286. * @param string $captcha 验证码
  287. */
  288. public function resetpwd()
  289. {
  290. $mobile = $this->request->request("mobile");
  291. $newpassword = $this->request->request("newpassword");
  292. $captcha = $this->request->request("captcha");
  293. if (!$mobile || !$newpassword || !$captcha)
  294. {
  295. $this->error(__('Invalid parameters'));
  296. }
  297. if ($mobile && !Validate::regex($mobile, "^1\d{10}$"))
  298. {
  299. $this->error(__('Mobile incorrect'));
  300. }
  301. $user = \app\common\model\User::getByMobile($mobile);
  302. if (!$user)
  303. {
  304. $this->error(__('User not found'));
  305. }
  306. $ret = Sms::check($mobile, $captcha, 'resetpwd');
  307. if (!$ret)
  308. {
  309. $this->error(__('Captcha invalid'));
  310. }
  311. Sms::flush($mobile, 'resetpwd');
  312. //模拟一次登录
  313. $this->auth->direct($user->id);
  314. $ret = $this->auth->changepwd($newpassword, '', true);
  315. if ($ret)
  316. {
  317. $this->success(__('Reset password successful'));
  318. }
  319. else
  320. {
  321. $this->error($this->auth->getError());
  322. }
  323. }
  324. /**
  325. * 判断当前用户今日有没有签到
  326. * @return bool
  327. */
  328. public function isSign()
  329. {
  330. $uid = Cookie::get('user_id');
  331. $todayDate = Date('Ymd', time());
  332. if (Cookie::get('sign' . $todayDate) == '1') {
  333. return true;
  334. } else {
  335. $isSign = model('Sign')->setConnect($uid)->where(['uid' => $uid, 'createdate' => $todayDate])->find();
  336. if (empty($isSign)) {
  337. return false;
  338. } else {
  339. Cookie::set('sign' . $todayDate, '1', 86400); //已经签到了,存cookie里
  340. Cookie::set('signcontinuedays'.$isSign->uid, $isSign->days, 86400);
  341. return true;
  342. }
  343. }
  344. }
  345. /**
  346. * 签到
  347. * @return string|\think\response\Json
  348. * @throws \Exception
  349. * err:0 签到成功,1 用户今日已签到,2 签到失败,3 用户未登录
  350. */
  351. public function sign()
  352. {
  353. if($this->request->isAjax()){
  354. $kandian = Config::get('site.kandian_sign');
  355. $uid = Cookie::get('user_id');
  356. if(!$uid){ //未登录
  357. return json(['err'=>3,'msg'=>'请先登录']);
  358. }
  359. $isBrowser = $this->request->post('isbrowser');
  360. $todayDate = Date('Ymd',time());
  361. $isSign = $this->isSign();
  362. //如果是阅读页签到
  363. if($isBrowser == 1 && $isSign){
  364. Cookie::set('sign'.$todayDate,'1',86400);
  365. return json(['err'=>1,'msg'=>'今日已签到,不能重复签到']);
  366. }
  367. $user = UserService::instance()->getUserModel()->getUserInfo($uid);
  368. $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($user['channel_id']);
  369. $refresh_token = OpenPlatformService::instance()->getRefreshToken($user['channel_id']);
  370. if($isSign){ //已经签到
  371. if($user){
  372. $officialAccount = OpenPlatformService::instance()->getOfficialAccount($adminConfig['appid'], $refresh_token);
  373. $text = new Text(UserService::instance()->getSignModel()->setConnect($uid)->getSignedRecommendBookTemplate());
  374. $officialAccount->customer_service->message($text)->to($user['openid'])->send();
  375. }
  376. return json(['err'=>1,'msg'=>'今日已签到,不能重复签到']);
  377. }
  378. list($status, $message, $kandian, $continue_days) = UserService::instance()->getSignModel()->setConnect($uid)->UserSignContinuous();
  379. if(!$status){
  380. return json(['err'=>2,'msg'=>'签到失败']);
  381. }
  382. //签到成功后存到cookie里
  383. Cookie::set('sign'.$todayDate,'1',86400);
  384. Cookie::set('signcontinuedays' . $uid, $continue_days, 86400);
  385. if($user){
  386. $officialAccount = OpenPlatformService::instance()->getOfficialAccount($adminConfig['appid'], $refresh_token);
  387. $text = new Text($message);
  388. $officialAccount->customer_service->message($text)->to($user['openid'])->send();
  389. }
  390. return json(['err'=>0,'msg'=>'签到成功','kandian'=>$kandian]);
  391. }
  392. }
  393. /**
  394. * 连续签到
  395. * @return string|\think\response\Json
  396. * @throws \Exception
  397. * err:0 签到成功,1 用户今日已签到,2 签到失败,3 用户未登录
  398. */
  399. public function signcontinuous()
  400. {
  401. LogService::info('[ SIGN ] signcontinuous');
  402. if ($this->request->isAjax()) {
  403. LogService::info('[ SIGN ] ajax:' . json_encode($this->request->post()));
  404. $uid = Cookie::get('user_id');
  405. if (!$uid) { //未登录
  406. return json(['err' => 3, 'msg' => '请先登录']);
  407. }
  408. $isBrowser = $this->request->post('isbrowser');
  409. $actionfrom = $this->request->post('actionfrom') ?? '';
  410. $todayDate = Date('Ymd', time());
  411. $isSign = $this->isSign();
  412. //如果是阅读页签到
  413. if ($isBrowser == 1 && $isSign) {
  414. Cookie::set('sign' . $todayDate, '1', 86400);
  415. return json(['err' => 1, 'msg' => '今日已签到,不能重复签到', 'continue_days' => Cookie::get('signcontinuedays' . $uid)]);
  416. }
  417. $user = UserService::instance()->getUserModel()->getUserInfo($uid);
  418. $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($user['channel_id']);
  419. if (!$adminConfig || !$adminConfig['appid']) {
  420. return json(['err' => 2, 'msg' => '签到失败']);
  421. }
  422. $refresh_token = OpenPlatformService::instance()->getRefreshToken($user['channel_id']);
  423. if ($isSign) { //已经签到
  424. if(empty($actionfrom)){
  425. if ($user) {
  426. $officialAccount = OpenPlatformService::instance()->getOfficialAccount($adminConfig['appid'], $refresh_token);
  427. $text = new Text(UserService::instance()->getSignModel()->setConnect($uid)->getSignedRecommendBookTemplate());
  428. try{
  429. $officialAccount->customer_service->message($text)->to($user['openid'])->send();
  430. }catch (\Exception $e) {
  431. LogService::notice($uid . ',签到错误:' . $e->getMessage());
  432. }
  433. }
  434. }
  435. return json(['err' => 1, 'msg' => '今日已签到,不能重复签到', 'continue_days' => Cookie::get('signcontinuedays' . $uid)]);
  436. }
  437. list($status, $message, $kandian, $continue_days) = UserService::instance()->getSignModel()->setConnect($uid)->UserSignContinuous();
  438. if (!$status) {
  439. return json(['err' => 2, 'msg' => '签到失败']);
  440. }
  441. if ($user && !Cookie::get('sign' . $todayDate)) {
  442. $officialAccount = OpenPlatformService::instance()->getOfficialAccount($adminConfig['appid'], $refresh_token);
  443. $text = new Text($message);
  444. try{
  445. $officialAccount->customer_service->message($text)->to($user['openid'])->send();
  446. }catch (\Exception $e) {
  447. LogService::notice($uid . ',签到错误:' . $e->getMessage());
  448. }
  449. }
  450. //签到成功后存到cookie里
  451. Cookie::set('sign' . $todayDate, '1', 86400);
  452. Cookie::set('signcontinuedays' . $uid, $continue_days, 86400);
  453. return json(['err' => 0, 'msg' => '签到成功', 'kandian' => $kandian, 'continue_days' => $continue_days]);
  454. }
  455. }
  456. /**
  457. *ajax请求最近阅读记录
  458. */
  459. public function getReadRecently(){
  460. if($this->request->isAjax()){
  461. $pageSize = empty(input('pageSize'))? 10:input('pageSize');
  462. $updatetime = empty(input('updatetime'))?0:input('updatetime');
  463. $rencently = model('UserRecentlyRead')->getRecentlyRead($updatetime, $pageSize, null, true);
  464. if ($rencently['totalNum'] > 0) {
  465. return json($rencently);
  466. } else {
  467. return json(['data' => []]);
  468. }
  469. }
  470. }
  471. /**
  472. * ajax删除阅读记录
  473. */
  474. public function delRecently(){
  475. if($this->request->isAjax()){
  476. $userId = UserService::instance()->getUserInfo()->id;
  477. $urKey = BookService::instance()->getUserRecentlyRead()->getURKey($userId);
  478. $recentIds = input('bookIds');
  479. $recentArr = \GuzzleHttp\json_decode($recentIds,true);
  480. $aRecentIds = [];
  481. $aBookIds = [];
  482. foreach ($recentArr as $key => $val) {
  483. $ids = explode('_', $val);
  484. $aRecentIds[] = $ids[0];
  485. $aBookIds[] = $ids[1];
  486. }
  487. $removeRes = BookService::instance()->removeRecentlyRead($aRecentIds, $aBookIds);
  488. $redis = Redis::instance();
  489. $recentCount = $redis->zcard($urKey); // 返回元素个数
  490. $res = [];
  491. $res['totalNum'] = $recentCount;
  492. $res['err'] = $removeRes->code == ErrorCodeConstants::SUCCESS ? 0 : 1;
  493. return json($res);
  494. }
  495. }
  496. }