123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540 |
- <?php
- namespace app\api\controller;
- use app\common\controller\Api;
- use app\common\library\Email;
- use app\common\library\Redis;
- use app\common\library\Sms;
- use app\main\constants\ErrorCodeConstants;
- use app\main\service\AdminService;
- use app\main\service\BookService;
- use app\main\service\LogService;
- use app\main\service\OpenPlatformService;
- use app\main\service\UserService;
- use EasyWeChat\Kernel\Messages\Text;
- use fast\Random;
- use think\Config;
- use think\Cookie;
- use think\Validate;
- /**
- * 会员接口
- */
- class User extends Api
- {
- protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
- protected $noNeedRight = '*';
- protected $redis;
- public function _initialize()
- {
- parent::_initialize();
- $this->redis = Redis::instance();
- }
- /**
- * 会员中心
- */
- public function index()
- {
- $this->success('', ['welcome' => $this->auth->nickname]);
- }
- /**
- * 会员登录
- *
- * @param string $account 账号
- * @param string $password 密码
- */
- public function login()
- {
- $account = $this->request->request('account');
- $password = $this->request->request('password');
- if (!$account || !$password)
- {
- $this->error(__('Invalid parameters'));
- }
- $ret = $this->auth->login($account, $password);
- if ($ret)
- {
- $data = ['userinfo' => $this->auth->getUserinfo()];
- $this->success(__('Logged in successful'), $data);
- }
- else
- {
- $this->error($this->auth->getError());
- }
- }
- /**
- * 手机验证码登录
- *
- * @param string $mobile 手机号
- * @param string $captcha 验证码
- */
- public function mobilelogin()
- {
- $mobile = $this->request->request('mobile');
- $captcha = $this->request->request('captcha');
- if (!$mobile || !$captcha)
- {
- $this->error(__('Invalid parameters'));
- }
- if (!Validate::regex($mobile, "^1\d{10}$"))
- {
- $this->error(__('Mobile incorrect'));
- }
- if (!Sms::check($mobile, $captcha, 'mobilelogin'))
- {
- $this->error(__('Captcha invalid'));
- }
- $user = \app\common\model\User::getByMobile($mobile);
- if ($user)
- {
- //如果已经有账号则直接登录
- $ret = $this->auth->direct($user->id);
- }
- else
- {
- $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
- }
- if ($ret)
- {
- Sms::flush($mobile, 'mobilelogin');
- $data = ['userinfo' => $this->auth->getUserinfo()];
- $this->success(__('Logged in successful'), $data);
- }
- else
- {
- $this->error($this->auth->getError());
- }
- }
- /**
- * 注册会员
- *
- * @param string $username 用户名
- * @param string $password 密码
- * @param string $email 邮箱
- * @param string $mobile 手机号
- */
- public function register()
- {
- $username = $this->request->request('username');
- $password = $this->request->request('password');
- $email = $this->request->request('email');
- $mobile = $this->request->request('mobile');
- if (!$username || !$password)
- {
- $this->error(__('Invalid parameters'));
- }
- if ($email && !Validate::is($email, "email"))
- {
- $this->error(__('Email incorrect'));
- }
- if ($mobile && !Validate::regex($mobile, "^1\d{10}$"))
- {
- $this->error(__('Mobile incorrect'));
- }
- $ret = $this->auth->register($username, $password, $email, $mobile, []);
- if ($ret)
- {
- $data = ['userinfo' => $this->auth->getUserinfo()];
- $this->success(__('Sign up successful'), $data);
- }
- else
- {
- $this->error($this->auth->getError());
- }
- }
- /**
- * 注销登录
- */
- public function logout()
- {
- $this->auth->logout();
- $this->success(__('Logout successful'));
- }
- /**
- * 修改会员个人信息
- *
- * @param string $avatar 头像地址
- * @param string $username 用户名
- * @param string $nickname 昵称
- * @param string $bio 个人简介
- */
- public function profile()
- {
- $user = $this->auth->getUser();
- $username = $this->request->request('username');
- $nickname = $this->request->request('nickname');
- $bio = $this->request->request('bio');
- $avatar = $this->request->request('avatar');
- $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
- if ($exists)
- {
- $this->error(__('Username already exists'));
- }
- $user->username = $username;
- $user->nickname = $nickname;
- $user->bio = $bio;
- $user->avatar = $avatar;
- $user->save();
- $this->success();
- }
- /**
- * 修改邮箱
- *
- * @param string $email 邮箱
- */
- public function changeemail()
- {
- $user = $this->auth->getUser();
- $email = $this->request->post('email');
- if (!$email)
- {
- $this->error(__('Invalid parameters'));
- }
- if (!Validate::is($email, "email"))
- {
- $this->error(__('Mobile incorrect'));
- }
- if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find())
- {
- $this->error(__('Email already exists'));
- }
- $verification = $user->verification;
- $verification->email = 0;
- $user->verification = $verification;
- $user->email = $email;
- $user->save();
- $time = time();
- $code = ['id' => $user->id, 'time' => $time, 'key' => md5(md5($user->id . $user->email . $time) . $user->salt)];
- $code = base64_encode(http_build_query($code));
- $url = url("index/user/activeemail", ['code' => $code], true, true);
- $message = __('Verify email') . ":<a href='{$url}'>{$url}</a>";
- Email::instance()->to($email)->subject(__('Verify email'))->message($message)->send();
- $this->success();
- }
- /**
- * 修改手机号
- *
- * @param string $email 手机号
- * @param string $captcha 验证码
- */
- public function changemobile()
- {
- $user = $this->auth->getUser();
- $mobile = $this->request->request('mobile');
- $captcha = $this->request->request('captcha');
- if (!$mobile || !$captcha)
- {
- $this->error(__('Invalid parameters'));
- }
- if (!Validate::regex($mobile, "^1\d{10}$"))
- {
- $this->error(__('Mobile incorrect'));
- }
- if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find())
- {
- $this->error(__('Mobile already exists'));
- }
- $result = Sms::check($mobile, $captcha, 'changemobile');
- if (!$result)
- {
- $this->error(__('Captcha invalid'));
- }
- $verification = $user->verification;
- $verification->mobile = 1;
- $user->verification = $verification;
- $user->mobile = $mobile;
- $user->save();
- Sms::flush($mobile, 'changemobile');
- $this->success();
- }
- /**
- * 第三方登录
- *
- * @param string $platform 平台名称
- * @param string $code Code码
- */
- public function third()
- {
- $url = url('user/index');
- $platform = $this->request->request("platform");
- $code = $this->request->request("code");
- $config = get_addon_config('third');
- if (!$config || !isset($config[$platform]))
- {
- $this->error(__('Invalid parameters'));
- }
- $app = new \addons\third\library\Application($config);
- //通过code换access_token和绑定会员
- $result = $app->{$platform}->getUserInfo(['code' => $code]);
- if ($result)
- {
- $loginret = \addons\third\library\Service::connect($platform, $result);
- if ($loginret)
- {
- $data = [
- 'userinfo' => $this->auth->getUserinfo(),
- 'thirdinfo' => $result
- ];
- $this->success(__('Logged in successful'), $data);
- }
- }
- $this->error(__('Operation failed'), $url);
- }
- /**
- * 重置密码
- *
- * @param string $mobile 手机号
- * @param string $newpassword 新密码
- * @param string $captcha 验证码
- */
- public function resetpwd()
- {
- $mobile = $this->request->request("mobile");
- $newpassword = $this->request->request("newpassword");
- $captcha = $this->request->request("captcha");
- if (!$mobile || !$newpassword || !$captcha)
- {
- $this->error(__('Invalid parameters'));
- }
- if ($mobile && !Validate::regex($mobile, "^1\d{10}$"))
- {
- $this->error(__('Mobile incorrect'));
- }
- $user = \app\common\model\User::getByMobile($mobile);
- if (!$user)
- {
- $this->error(__('User not found'));
- }
- $ret = Sms::check($mobile, $captcha, 'resetpwd');
- if (!$ret)
- {
- $this->error(__('Captcha invalid'));
- }
- Sms::flush($mobile, 'resetpwd');
- //模拟一次登录
- $this->auth->direct($user->id);
- $ret = $this->auth->changepwd($newpassword, '', true);
- if ($ret)
- {
- $this->success(__('Reset password successful'));
- }
- else
- {
- $this->error($this->auth->getError());
- }
- }
- /**
- * 判断当前用户今日有没有签到
- * @return bool
- */
- public function isSign()
- {
- $uid = Cookie::get('user_id');
- $todayDate = Date('Ymd', time());
- if (Cookie::get('sign' . $todayDate) == '1') {
- return true;
- } else {
- $isSign = model('Sign')->setConnect($uid)->where(['uid' => $uid, 'createdate' => $todayDate])->find();
- if (empty($isSign)) {
- return false;
- } else {
- Cookie::set('sign' . $todayDate, '1', 86400); //已经签到了,存cookie里
- Cookie::set('signcontinuedays'.$isSign->uid, $isSign->days, 86400);
- return true;
- }
- }
- }
- /**
- * 签到
- * @return string|\think\response\Json
- * @throws \Exception
- * err:0 签到成功,1 用户今日已签到,2 签到失败,3 用户未登录
- */
- public function sign()
- {
- if($this->request->isAjax()){
- $kandian = Config::get('site.kandian_sign');
- $uid = Cookie::get('user_id');
- if(!$uid){ //未登录
- return json(['err'=>3,'msg'=>'请先登录']);
- }
- $isBrowser = $this->request->post('isbrowser');
- $todayDate = Date('Ymd',time());
- $isSign = $this->isSign();
- //如果是阅读页签到
- if($isBrowser == 1 && $isSign){
- Cookie::set('sign'.$todayDate,'1',86400);
- return json(['err'=>1,'msg'=>'今日已签到,不能重复签到']);
- }
- $user = UserService::instance()->getUserModel()->getUserInfo($uid);
- $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($user['channel_id']);
- $refresh_token = OpenPlatformService::instance()->getRefreshToken($user['channel_id']);
- if($isSign){ //已经签到
- if($user){
- $officialAccount = OpenPlatformService::instance()->getOfficialAccount($adminConfig['appid'], $refresh_token);
- $text = new Text(UserService::instance()->getSignModel()->setConnect($uid)->getSignedRecommendBookTemplate());
- $officialAccount->customer_service->message($text)->to($user['openid'])->send();
- }
- return json(['err'=>1,'msg'=>'今日已签到,不能重复签到']);
- }
- list($status, $message, $kandian, $continue_days) = UserService::instance()->getSignModel()->setConnect($uid)->UserSignContinuous();
- if(!$status){
- return json(['err'=>2,'msg'=>'签到失败']);
- }
- //签到成功后存到cookie里
- Cookie::set('sign'.$todayDate,'1',86400);
- Cookie::set('signcontinuedays' . $uid, $continue_days, 86400);
- if($user){
- $officialAccount = OpenPlatformService::instance()->getOfficialAccount($adminConfig['appid'], $refresh_token);
- $text = new Text($message);
- $officialAccount->customer_service->message($text)->to($user['openid'])->send();
- }
- return json(['err'=>0,'msg'=>'签到成功','kandian'=>$kandian]);
- }
- }
- /**
- * 连续签到
- * @return string|\think\response\Json
- * @throws \Exception
- * err:0 签到成功,1 用户今日已签到,2 签到失败,3 用户未登录
- */
- public function signcontinuous()
- {
- LogService::info('[ SIGN ] signcontinuous');
- if ($this->request->isAjax()) {
- LogService::info('[ SIGN ] ajax:' . json_encode($this->request->post()));
- $uid = Cookie::get('user_id');
- if (!$uid) { //未登录
- return json(['err' => 3, 'msg' => '请先登录']);
- }
- $isBrowser = $this->request->post('isbrowser');
- $actionfrom = $this->request->post('actionfrom') ?? '';
- $todayDate = Date('Ymd', time());
- $isSign = $this->isSign();
- //如果是阅读页签到
- if ($isBrowser == 1 && $isSign) {
- Cookie::set('sign' . $todayDate, '1', 86400);
- return json(['err' => 1, 'msg' => '今日已签到,不能重复签到', 'continue_days' => Cookie::get('signcontinuedays' . $uid)]);
- }
- $user = UserService::instance()->getUserModel()->getUserInfo($uid);
- $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($user['channel_id']);
- if (!$adminConfig || !$adminConfig['appid']) {
- return json(['err' => 2, 'msg' => '签到失败']);
- }
- $refresh_token = OpenPlatformService::instance()->getRefreshToken($user['channel_id']);
- if ($isSign) { //已经签到
- if(empty($actionfrom)){
- if ($user) {
- $officialAccount = OpenPlatformService::instance()->getOfficialAccount($adminConfig['appid'], $refresh_token);
- $text = new Text(UserService::instance()->getSignModel()->setConnect($uid)->getSignedRecommendBookTemplate());
- try{
- $officialAccount->customer_service->message($text)->to($user['openid'])->send();
- }catch (\Exception $e) {
- LogService::notice($uid . ',签到错误:' . $e->getMessage());
- }
- }
- }
- return json(['err' => 1, 'msg' => '今日已签到,不能重复签到', 'continue_days' => Cookie::get('signcontinuedays' . $uid)]);
- }
- list($status, $message, $kandian, $continue_days) = UserService::instance()->getSignModel()->setConnect($uid)->UserSignContinuous();
- if (!$status) {
- return json(['err' => 2, 'msg' => '签到失败']);
- }
- if ($user && !Cookie::get('sign' . $todayDate)) {
- $officialAccount = OpenPlatformService::instance()->getOfficialAccount($adminConfig['appid'], $refresh_token);
- $text = new Text($message);
- try{
- $officialAccount->customer_service->message($text)->to($user['openid'])->send();
- }catch (\Exception $e) {
- LogService::notice($uid . ',签到错误:' . $e->getMessage());
- }
- }
- //签到成功后存到cookie里
- Cookie::set('sign' . $todayDate, '1', 86400);
- Cookie::set('signcontinuedays' . $uid, $continue_days, 86400);
- return json(['err' => 0, 'msg' => '签到成功', 'kandian' => $kandian, 'continue_days' => $continue_days]);
- }
- }
- /**
- *ajax请求最近阅读记录
- */
- public function getReadRecently(){
- if($this->request->isAjax()){
- $pageSize = empty(input('pageSize'))? 10:input('pageSize');
- $updatetime = empty(input('updatetime'))?0:input('updatetime');
- $rencently = model('UserRecentlyRead')->getRecentlyRead($updatetime, $pageSize, null, true);
- if ($rencently['totalNum'] > 0) {
- return json($rencently);
- } else {
- return json(['data' => []]);
- }
- }
- }
- /**
- * ajax删除阅读记录
- */
- public function delRecently(){
- if($this->request->isAjax()){
- $userId = UserService::instance()->getUserInfo()->id;
- $urKey = BookService::instance()->getUserRecentlyRead()->getURKey($userId);
- $recentIds = input('bookIds');
- $recentArr = \GuzzleHttp\json_decode($recentIds,true);
- $aRecentIds = [];
- $aBookIds = [];
- foreach ($recentArr as $key => $val) {
- $ids = explode('_', $val);
- $aRecentIds[] = $ids[0];
- $aBookIds[] = $ids[1];
- }
- $removeRes = BookService::instance()->removeRecentlyRead($aRecentIds, $aBookIds);
- $redis = Redis::instance();
- $recentCount = $redis->zcard($urKey); // 返回元素个数
- $res = [];
- $res['totalNum'] = $recentCount;
- $res['err'] = $removeRes->code == ErrorCodeConstants::SUCCESS ? 0 : 1;
- return json($res);
- }
- }
- }
|