diff --git a/app/api/logic/LoginLogic.php b/app/api/logic/LoginLogic.php index 3da398d..9575dfe 100755 --- a/app/api/logic/LoginLogic.php +++ b/app/api/logic/LoginLogic.php @@ -1,218 +1,135 @@ $userSn, - 'avatar' => $avatar, - 'nickname' => '用户' . $userSn, - 'account' => $params['account'], - 'password' => $password, - 'channel' => $params['channel'], - ]); - - return true; - } catch (\Exception $e) { - self::setError($e->getMessage()); - return false; + public static function register($post){ + $client =Client_::mnp; + switch ($post['client']){ + case 2: + $client = Client_::oa; + break; + case 3: + $client = Client_::ios; + break; + case 4: + $client = Client_::android; + break; + case 5: + $client = Client_::pc; + break; + case 6: + $client = Client_::h5; + break; } - } + $time = time(); + $salt = substr(md5($time . $post['mobile']), 0, 4);//随机4位密码盐 + $password = create_password($post['password'], $salt);//生成密码 + $user_data = [ + 'avatar' => ConfigServer::get('website', 'user_image'), + 'sn' => create_user_sn(), + 'mobile' => $post['mobile'], + 'salt' => $salt, + 'password' => $password, + 'create_time' => $time, + 'distribution_code' => generate_invite_code(),//分销邀请码 + 'is_distribution' => DistributionLogic::isDistributionMember(),//是否为分销会员 + ]; + $user_data['nickname'] = '用户'.$user_data['sn']; - /** - * @notes 账号/手机号登录,手机号验证码 - * @param $params - * @return array|false - * @author 段誉 - * @date 2022/9/6 19:26 - */ - public static function login($params) - { - try { - // 账号/手机号 密码登录 - $where = ['account|mobile' => $params['account']]; - if ($params['scene'] == LoginEnum::MOBILE_CAPTCHA) { - //手机验证码登录 - $where = ['mobile' => $params['account']]; - } + $user = new User(); + $user->save($user_data); - $user = User::where($where)->findOrEmpty(); - if ($user->isEmpty()) { - throw new \Exception('用户不存在'); - } + $token = self::createSession($user->id, $client); - //更新登录信息 - $user->login_time = time(); - $user->login_ip = request()->ip(); - $user->save(); + //生成会员分销扩展表 + DistributionLogic::createUserDistribution($user->id); + // 生成分销会员基础表 + \app\common\logic\DistributionLogic::add($user->id); - //设置token - $userInfo = UserTokenService::setToken($user->id, $params['terminal']); - - //返回登录信息 - $avatar = $user->avatar ?: Config::get('project.default_image.user_avatar'); - $avatar = FileService::getFileUrl($avatar); - - return [ - 'nickname' => $userInfo['nickname'], - 'sn' => $userInfo['sn'], - 'mobile' => $userInfo['mobile'], - 'avatar' => $avatar, - 'token' => $userInfo['token'], - ]; - } catch (\Exception $e) { - self::setError($e->getMessage()); - return false; - } - } - public static function authLogin($post) - { - try { - //通过code获取微信 openid - $response = self::getWechatResByCode($post); - $response['headimgurl'] = $post['headimgurl'] ?? ''; - $response['nickname'] = $post['nickname'] ?? ''; - //通过获取到的openID或unionid获取当前 系统 用户id - $user_id = self::getUserByWechatResponse($response); - - } catch (Exception $e) { - self::setError('登录失败:' . $e->getMessage()); - return false; - } -// catch (\think\Exception $e) { -// self::setError('登录失败:' . $e->getMessage()); -// return false; -// } - - if (empty($user_id)) { - $user_info = UserServer::createUser($response, Client_::mnp); - } else { - $user_info = UserServer::updateUser($response, Client_::mnp, $user_id); - } - //验证用户信息 - $check_res = self::checkUserInfo($user_info); - if (true !== $check_res) { - return self::setError($check_res); - - } - - //创建会话 - $user_info['token'] = self::createSession($user_info['id'], Client_::mnp); - self::createUserSession($user_info['id'],$user_info['token']); - unset($user_info['id'], $user_info['disable']); - return $user_info; - } - public static function registerAward($user_id){ - $register_award_integral_status = ConfigServer::get('marketing','register_award_integral_status',0); - $register_award_coupon_status = ConfigServer::get('marketing','register_award_coupon_status',0); - //赠送积分 - if($register_award_integral_status){ - $register_award_integral = ConfigServer::get('marketing','register_award_integral',0); - //赠送的积分 - if($register_award_integral > 0){ - Db::name('user')->where(['id'=>$user_id])->setInc('user_integral',$register_award_integral); - AccountLogLogic::AccountRecord($user_id,$register_award_integral,1,AccountLog::register_add_integral,''); - } - } - //注册账号,首次进入首页时领取优惠券 - $register_award_coupon = ConfigServer::get('marketing','register_award_coupon',''); - if($register_award_coupon_status && $register_award_coupon){ - Cache::tag('register_coupon')->set('register_coupon_'.$user_id,$register_award_coupon); - } - //会员等级 - $user_level = Db::name('user_level')->where(['del'=>0,'growth_value'=>0])->find(); - if($user_level){ - Db::name('user')->where(['id'=>$user_id])->update(['level'=>$user_level['id']]); - } + //注册赠送 + self::registerAward($user->id); + //消息通知 + Hook::listen('notice', [ + 'user_id' => $user->id, + 'scene' => NoticeSetting::REGISTER_SUCCESS_NOTICE, + ]); + return $token; } /** - * Notes: 根据code 获取微信信息(openid, unionid) + * User: 意象信息科技 lr + * Desc: 小程序登录 * @param $post - * @author 段誉(2021/4/19 16:52) - * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string + * @return array|\PDOStatement|string|\think\Model|null * @throws Exception + * @throws \EasyWeChat\Kernel\Exceptions\DecryptException * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException + * @throws \think\db\exception\DataNotFoundException + * @throws \think\db\exception\ModelNotFoundException + * @throws \think\exception\DbException + * @throws \think\exception\PDOException */ - public static function getWechatResByCode($post) + public static function mnpLogin($post) { -// $config = WeChatServer::getMnpConfig(); - $response = (new WeChatMnpService())->getMnpResByCode($post['code']); -// $app = Factory::miniProgram($config); -// $response = $app->auth->session($post['code']); - if (!isset($response['openid']) || empty($response['openid'])) { - throw new Exception('获取openID失败'); + //微信调用 + try { + $config = WeChatServer::getMnpConfig(); + $app = Factory::miniProgram($config); + $response = $app->auth->session($post['code']); + if (!isset($response['openid']) || empty($response['openid'])) { + throw new Exception('获取openID失败'); + } + } catch (Exception $e) { + return self::dataError('登录失败:' . $e->getMessage()); + }catch (\think\Exception $e){ + return self::dataError('登录失败:' . $e->getMessage()); } - return $response; - } - /** - * Notes: 根据微信返回信息查询当前用户id - * @param $response - * @author 段誉(2021/4/19 16:52) - * @return mixed - */ - public static function getUserByWechatResponse($response) - { - $user_id = Db::name('user_auth')->alias("au") + + //添加或更新用户 + $user_id = Db::name('user_auth au') ->join('user u', 'au.user_id=u.id') ->where(['u.del' => 0]) ->where(function ($query) use ($response) { @@ -222,20 +139,253 @@ class LoginLogic extends BaseLogic } }) ->value('user_id'); - return $user_id; - } - public static function checkUserInfo($user_info) - { - if (empty($user_info)) { - return '登录失败:user'; + + if (empty($user_id)) { + $user_info = UserServer::createUser($response, Client_::mnp); + } else { + $user_info = UserServer::updateUser($response, Client_::mnp, $user_id); } if ($user_info['disable']) { - return '账号已被禁用'; + return self::dataError('账号已被禁用'); } - return true; + + if (empty($user_info)) { + return self::dataError('登录失败:user'); + } + + //创建会话 + $user_info['token'] = self::createSession($user_info['id'], Client_::mnp); + + + unset($user_info['id']); + unset($user_info['disable']); + return self::dataSuccess('登录成功', $user_info); + } + + /** + * 获取code的url + * @param $url + * @return string + */ + public static function codeUrl($url) + { + $config = WeChatServer::getOaConfig(); + $app = Factory::officialAccount($config); + $response = $app + ->oauth + ->scopes(['snsapi_userinfo']) + ->redirect($url) + ->getTargetUrl(); + return $response; + } + + + /** + * User: 意象信息科技 lr + * Desc: 微信公众号登录 + * @param $post + * @return array|\PDOStatement|string|\think\Model|null + * @throws Exception + * @throws \EasyWeChat\Kernel\Exceptions\DecryptException + * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException + * @throws \think\db\exception\DataNotFoundException + * @throws \think\db\exception\ModelNotFoundException + * @throws \think\exception\DbException + * @throws \think\exception\PDOException + */ + public static function oaLogin($post) + { + //微信调用 + try { + $config = WeChatServer::getOaConfig(); + $app = Factory::officialAccount($config); + $response = $app + ->oauth + ->scopes(['snsapi_userinfo']) + ->getAccessToken($post['code']); + if (!isset($response['openid']) || empty($response['openid'])) { + throw new Exception(); + } + $user = $app->oauth->user($response); + $user = $user->getOriginal(); + } catch (Exception $e) { + return self::dataError('登录失败:' . $e->getMessage()); + }catch (\think\Exception $e){ + return self::dataError('登录失败:' . $e->getMessage()); + } + + //添加或更新用户 + $user_id = Db::name('user_auth au') + ->join('user u', 'au.user_id=u.id') + ->where(['u.del' => 0]) + ->where(function ($query) use ($user) { + $query->whereOr(['au.openid' => $user['openid']]); + if(isset($user['unionid']) && !empty($user['unionid'])){ + $query->whereOr(['au.unionid' => $user['unionid']]); + } + }) + ->value('user_id'); + + if (empty($user_id)) { + $user_info = UserServer::createUser($user, Client_::oa); + } else { + $user_info = UserServer::updateUser($user, Client_::oa, $user_id); + } + + if (empty($user_info)) { + return self::dataError('登录失败:user'); + } + + if ($user_info['disable']) { + return self::dataError('账号已被禁用'); + } + + //创建会话 + $user_info['token'] = self::createSession($user_info['id'], Client_::oa); + + + unset($user_info['id']); + unset($user_info['disable']); + return self::dataSuccess('登录成功', $user_info); + + } + + /** + * User: 意象信息科技 lr + * Desc: 微信第三方app登录 + * @param $post + * @return array|\PDOStatement|string|\think\Model|null + * @throws Exception + * @throws \EasyWeChat\Kernel\Exceptions\DecryptException + * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException + * @throws \think\db\exception\DataNotFoundException + * @throws \think\db\exception\ModelNotFoundException + * @throws \think\exception\DbException + * @throws \think\exception\PDOException + */ + public static function opLogin($post) + { + //微信调用 + try { + $config = WeChatServer::getOpConfig(); + $app = Factory::officialAccount($config); + $response = $app + ->oauth + ->scopes(['snsapi_userinfo']) + ->getAccessToken($post['code']); + $app->access_token->setToken($response->offsetGet('access_token')); + + //sdk不支持app登录,直接调用微信接口 + $requests = Requests::get('https://api.weixin.qq.com/sns/userinfo?openid=' . 'openid=' . $response->offsetGet('openid') . '&access_token=' . $response->offsetGet('access_token') + ); + $user = json_decode($requests->body, true); + } catch (Exception $e) { + return self::dataError('登录失败:' . $e->getMessage()); + }catch (\think\Exception $e){ + return self::dataError('登录失败:' . $e->getMessage()); + } + + + //添加或更新用户 + $user_id = Db::name('user_auth au') + ->join('user u', 'au.user_id=u.id') + ->where(['u.del' => 0]) + ->where(function ($query) use ($user) { + $query->whereOr(['au.openid' => $user['openid']]) + ->whereOr(['au.unionid' => $user['unionid']]); + }) + ->value('user_id'); + + if (empty($user_id)) { + $user_info = UserServer::createUser($user, $post['client']); + } else { + $user_info = UserServer::updateUser($user, $post['client'], $user_id); + } + + if (empty($user_info)) { + return self::dataError('登录失败:user'); + } + + if ($user_info['disable']) { + return self::dataError('账号已被禁用'); + } + + //创建会话 + $user_info['token'] = self::createSession($user_info['id'], $post['client']); + + + unset($user_info['id']); + unset($user_info['disable']); + return self::dataSuccess('登录成功', $user_info); + + } + + /** + * app登录 + * @param $post + * @return array|\PDOStatement|string|\think\Model|null + * @throws \think\Exception + * @throws \think\db\exception\DataNotFoundException + * @throws \think\db\exception\ModelNotFoundException + * @throws \think\exception\DbException + * @throws \think\exception\PDOException + */ + public static function login($post) + { + $user_info = Db::name('user') + ->field(['id', 'nickname', 'avatar', 'level', 'disable', 'distribution_code']) + ->where(['account|mobile' => $post['account']]) + ->find(); + $user_info['token'] = self::createSession($user_info['id'], $post['client']); + if (empty($user_info['avatar'])) { + $user_info['avatar'] = UrlServer::getFileUrl(ConfigServer::get('website', 'user_image')); + } else { + $user_info['avatar'] = UrlServer::getFileUrl($user_info['avatar']); + } + return $user_info; + } + + /** + * 退出登录 + * @param $user_id + * @param $client + * @return string + * @throws \think\Exception + * @throws \think\db\exception\DataNotFoundException + * @throws \think\db\exception\ModelNotFoundException + * @throws \think\exception\DbException + * @throws \think\exception\PDOException + */ + public static function logout($user_id, $client) + { + return self::expirationSession($user_id, $client); + } + + + /** + * 设置会话过期 + * @param $user_id + * @param $client + * @throws \think\Exception + * @throws \think\exception\PDOException + */ + public static function expirationSession($user_id, $client) + { + $time = time(); + $token = Db::name('session') + ->where(['user_id' => $user_id, 'client' => $client]) + ->value('token'); + $token_cache = new TokenCache($token); + $token_cache->del(); + return Db::name('session') + ->where(['user_id' => $user_id, 'client' => $client]) + ->update(['update_time' => $time, 'expire_time' => $time]); + } + + /** * 创建会话 * @param $user_id @@ -292,182 +442,270 @@ class LoginLogic extends BaseLogic (new TokenCache($token, ['token' => $token]))->set(300); return $token; } - public static function createUserSession($user_id,$tk) - { - //清除之前缓存 - $token = Db::name('user_session') - ->where('user_id' , $user_id) - ->value('token'); - if($token) { - $token_cache = new UserTokenCache(); - $token_cache->deleteUserInfo($token); + public static function registerAward($user_id){ + $register_award_integral_status = ConfigServer::get('marketing','register_award_integral_status',0); + $register_award_coupon_status = ConfigServer::get('marketing','register_award_coupon_status',0); + //赠送积分 + if($register_award_integral_status){ + $register_award_integral = ConfigServer::get('marketing','register_award_integral',0); + //赠送的积分 + if($register_award_integral > 0){ + Db::name('user')->where(['id'=>$user_id])->setInc('user_integral',$register_award_integral); + AccountLogLogic::AccountRecord($user_id,$register_award_integral,1,AccountLog::register_add_integral,''); + } } - - $result = Db::name('user_session') - ->where('user_id',$user_id) - ->find(); - - $time = time(); - $expire_time = $time + Config::get('project.token_expire_time'); - $data = [ - 'user_id' => $user_id, - 'token' => $tk, - 'update_time' => $time, - 'expire_time' => $expire_time, - ]; - - if (empty($result)) { - Db::name('user_session')->insert($data); - } else { - Db::name('user_session') - ->where('user_id', $user_id) - ->update($data); + //注册账号,首次进入首页时领取优惠券 + $register_award_coupon = ConfigServer::get('marketing','register_award_coupon',''); + if($register_award_coupon_status && $register_award_coupon){ + Cache::tag('register_coupon')->set('register_coupon_'.$user_id,$register_award_coupon); + } + //会员等级 + $user_level = Db::name('user_level')->where(['del'=>0,'growth_value'=>0])->find(); + if($user_level){ + Db::name('user')->where(['id'=>$user_id])->update(['level'=>$user_level['id']]); } - $userInfo = (new UserTokenCache())->setUserInfo($tk); } + + /** - * @notes 退出登录 - * @param $userInfo - * @return bool + * Notes: uniApp微信登录 + * @param $post + * @author 段誉(2021/3/16 16:17) + * @return array + * @throws \think\Exception * @throws \think\db\exception\DataNotFoundException - * @throws \think\db\exception\DbException * @throws \think\db\exception\ModelNotFoundException - * @author 段誉 - * @date 2022/9/16 17:56 + * @throws \think\exception\DbException + * @throws \think\exception\PDOException */ - public static function logout($userInfo) + public static function uinAppLogin($post) { - //token不存在,不注销 - if (!isset($userInfo['token'])) { - return false; - } - - //设置token过期 - return UserTokenService::expireToken($userInfo['token']); - } - - - /** - * @notes 获取微信请求code的链接 - * @param string $url - * @return string - * @author 段誉 - * @date 2022/9/20 19:47 - */ - public static function codeUrl(string $url) - { - return (new WeChatOaService())->getCodeUrl($url); - } - - - /** - * @notes 公众号登录 - * @param array $params - * @return array|false - * @throws \GuzzleHttp\Exception\GuzzleException - * @author 段誉 - * @date 2022/9/20 19:47 - */ - public static function oaLogin(array $params) - { - Db::startTrans(); + //微信调用 try { - //通过code获取微信 openid - $response = (new WeChatOaService())->getOaResByCode($params['code']); - $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_OA); - $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo(); - - // 更新登录信息 - self::updateLoginInfo($userInfo['id']); - - Db::commit(); - return $userInfo; - - } catch (\Exception $e) { - Db::rollback(); - self::$error = $e->getMessage(); - return false; - } - } - - - /** - * @notes 小程序-静默登录 - * @param array $params - * @return array|false - * @author 段誉 - * @date 2022/9/20 19:47 - */ - public static function silentLogin(array $params) - { - try { - //通过code获取微信 openid - $response = (new WeChatMnpService())->getMnpResByCode($params['code']); - $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP); - $userInfo = $userServer->getResopnseByUserInfo('silent')->getUserInfo(); - - if (!empty($userInfo)) { - // 更新登录信息 - self::updateLoginInfo($userInfo['id']); + if (empty($post['openid']) || empty($post['access_token']) || empty($post['client'])){ + throw new \think\Exception('参数缺失'); } - return $userInfo; - } catch (\Exception $e) { - self::$error = $e->getMessage(); - return false; + //sdk不支持app登录,直接调用微信接口 + $requests = Requests::get('https://api.weixin.qq.com/sns/userinfo?openid=' . 'openid=' . $post['openid'] . '&access_token=' . $post['access_token']); + $user = json_decode($requests->body, true); + } catch (Exception $e) { + return self::dataError('登录失败:' . $e->getMessage()); + }catch (\think\Exception $e){ + return self::dataError('登录失败:' . $e->getMessage()); } + + //添加或更新用户 + $user_id = Db::name('user_auth au') + ->join('user u', 'au.user_id=u.id') + ->where(['u.del' => 0]) + ->where(function ($query) use ($user) { + $query->whereOr(['au.openid' => $user['openid']]) + ->whereOr(['au.unionid' => $user['unionid']]); + }) + ->value('user_id'); + + if (empty($user_id)) { + $user_info = UserServer::createUser($user, $post['client']); + } else { + $user_info = UserServer::updateUser($user, $post['client'], $user_id); + } + + //验证用户信息 + $check_res = self::checkUserInfo($user_info); + if (true !== $check_res) { + return self::dataError($check_res); + } + + //创建会话 + $user_info['token'] = self::createSession($user_info['id'], $post['client']); + + unset($user_info['id']); + unset($user_info['disable']); + return self::dataSuccess('登录成功', $user_info); + } + + + + + + + /** + * Notes: 根据微信返回信息查询当前用户id + * @param $response + * @author 段誉(2021/4/19 16:52) + * @return mixed + */ + public static function getUserByWechatResponse($response) + { + $user_id = Db::name('user_auth')->alias('au') + ->join('user u', 'au.user_id=u.id') + ->where(['u.del' => 0]) + ->where(function ($query) use ($response) { + $query->whereOr(['au.openid' => $response['openid']]); + if(isset($response['unionid']) && !empty($response['unionid'])){ + $query->whereOr(['au.unionid' => $response['unionid']]); + } + }) + ->value('user_id'); + return $user_id; + } + + + + + /** + * Notes: 根据code 获取微信信息(openid, unionid) + * @param $post + * @author 段誉(2021/4/19 16:52) + * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string + * @throws Exception + * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException + */ + public static function getWechatResByCode($post) + { + $config = WeChatServer::getMnpConfig(); + $response = (new WeChatMnpService())->getMnpResByCode($post['code']); +// $app = Factory::miniProgram($config); +// $response = $app->auth->session($post['code']); + if (!isset($response['openid']) || empty($response['openid'])) { + throw new Exception('获取openID失败'); + } + return $response; } /** - * @notes 小程序-授权登录 - * @param array $params - * @return array|false - * @author 段誉 - * @date 2022/9/20 19:47 + * Notes: 检车用户信息 + * @param $user_info + * @author 段誉(2021/4/19 16:54) + * @return bool|string */ - public static function mnpLogin(array $params) + public static function checkUserInfo($user_info) + { + if (empty($user_info)) { + return '登录失败:user'; + } + + if ($user_info['disable']) { + return '账号已被禁用'; + } + + return true; + } + + + /** + * Notes: 旧用户登录 + * @param $post + * @author 段誉(2021/4/19 16:57) + * @return array + * @throws \think\Exception + * @throws \think\db\exception\DataNotFoundException + * @throws \think\db\exception\ModelNotFoundException + * @throws \think\exception\DbException + * @throws \think\exception\PDOException + */ + public static function silentLogin($post) { - Db::startTrans(); try { //通过code获取微信 openid - $response = (new WeChatMnpService())->getMnpResByCode($params['code']); - $userServer = new WechatUserService($response, UserTerminalEnum::WECHAT_MMP); - $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo(); + $response = self::getWechatResByCode($post); + //通过获取到的openID或unionid获取当前 系统 用户id + $user_id = self::getUserByWechatResponse($response); - // 更新登录信息 - self::updateLoginInfo($userInfo['id']); - - Db::commit(); - return $userInfo; - } catch (\Exception $e) { - Db::rollback(); - self::$error = $e->getMessage(); - return false; + } catch (Exception $e) { + return self::dataError('登录失败:' . $e->getMessage()); + } catch (\think\Exception $e) { + return self::dataError('登录失败:' . $e->getMessage()); } + + if (empty($user_id)) { + //系统中没有用户-调用authlogin接口生成新用户 + return self::dataSuccess('', []); + } else { + $user_info = UserServer::updateUser($response, Client_::mnp, $user_id); + } + + //验证用户信息 + $check_res = self::checkUserInfo($user_info); + if (true !== $check_res) { + return self::dataError($check_res); + } + + //创建会话 + $user_info['token'] = self::createSession($user_info['id'], Client_::mnp); + + unset($user_info['id'], $user_info['disable']); + return self::dataSuccess('登录成功', $user_info); } /** - * @notes 更新登录信息 - * @param $userId - * @throws \Exception - * @author 段誉 - * @date 2022/9/20 19:46 + * Notes: 新用户登录 + * @param $post + * @author 段誉(2021/4/19 16:57) + * @return array + * @throws \think\Exception + * @throws \think\db\exception\DataNotFoundException + * @throws \think\db\exception\ModelNotFoundException + * @throws \think\exception\DbException + * @throws \think\exception\PDOException */ - public static function updateLoginInfo($userId) + public static function authLogin($post) { - $user = User::findOrEmpty($userId); - if ($user->isEmpty()) { - throw new \Exception('用户不存在'); + try { + //通过code获取微信 openid + $response = self::getWechatResByCode($post); + $response['headimgurl'] = $post['headimgurl'] ?? ''; + $response['nickname'] = $post['nickname'] ?? ''; + //通过获取到的openID或unionid获取当前 系统 用户id + $user_id = self::getUserByWechatResponse($response); + + } catch (Exception $e) { + return self::dataError('登录失败:' . $e->getMessage()); + } catch (\think\Exception $e) { + return self::dataError('登录失败:' . $e->getMessage()); } - $time = time(); - $user->login_time = $time; - $user->login_ip = request()->ip(); - $user->update_time = $time; - $user->save(); + if (empty($user_id)) { + $user_info = UserServer::createUser($response, Client_::mnp); + } else { + $user_info = UserServer::updateUser($response, Client_::mnp, $user_id); + } + + //验证用户信息 + $check_res = self::checkUserInfo($user_info); + if (true !== $check_res) { + return self::dataError($check_res); + } + + //创建会话 + $user_info['token'] = self::createSession($user_info['id'], Client_::mnp); + + unset($user_info['id'], $user_info['disable']); + return self::dataSuccess('登录成功', $user_info); + } + + /** + * @notes 更新用户头像昵称 + * @param $post + * @param $user_id + * @return array + * @throws \think\Exception + * @throws \think\exception\PDOException + * @author ljj + * @date 2023/2/1 3:45 下午 + */ + public static function updateUser($post,$user_id) + { +// $user = Db::name('user')->where(['id'=>$user_id])->find(); +// if ($user['is_new_user'] == 0) { +// return self::dataError('非新用户无法使用此接口更新用户信息'); +// } + Db::name('user')->where(['id'=>$user_id])->update(['nickname'=>$post['nickname'],'avatar'=>UrlServer::setFileUrl($post['avatar']),'is_new_user'=>0]); + return self::dataSuccess('操作成功'); } @@ -475,18 +713,37 @@ class LoginLogic extends BaseLogic * @notes 小程序端绑定微信 * @param array $params * @return bool - * @author 段誉 - * @date 2022/9/20 19:46 + * @author lbzy + * @datetime 2023-11-29 10:57:29 */ - public static function mnpAuthLogin(array $params) + public function mnpAuthLogin(array $params) { try { //通过code获取微信openid - $response = (new WeChatMnpService())->getMnpResByCode($params['code']); - $response['user_id'] = $params['user_id']; - $response['terminal'] = UserTerminalEnum::WECHAT_MMP; + $config = WeChatServer::getMnpConfig(); + $app = Factory::miniProgram($config); + $response = $app->auth->session($params['code']); + if (empty($response['openid'])) { + throw new Exception('获取openID失败'); + } - return self::createAuth($response); + $userAuth = UserAuth::where('openid', $response['openid'])->findOrEmpty(); + if (isset($userAuth['id'])) { + if ($userAuth['user_id'] == $params['user_id']) { + return true; + } + throw new \Exception('该微信已绑定其他用户'); + } + + UserAuth::create([ + 'user_id' => $params['user_id'], + 'openid' => $response['openid'], + 'create_time' => time(), + 'unionid' => $response['unionid'] ?? '', + 'client' => Client_::mnp, + ]); + + return true; } catch (\Exception $e) { self::$error = $e->getMessage(); @@ -494,24 +751,44 @@ class LoginLogic extends BaseLogic } } - /** * @notes 公众号端绑定微信 * @param array $params * @return bool - * @throws \GuzzleHttp\Exception\GuzzleException - * @author 段誉 - * @date 2022/9/16 10:43 + * @author lbzy + * @datetime 2023-11-29 10:57:24 */ - public static function oaAuthLogin(array $params) + public function oaAuthLogin(array $params) { try { //通过code获取微信openid - $response = (new WeChatOaService())->getOaResByCode($params['code']); - $response['user_id'] = $params['user_id']; - $response['terminal'] = UserTerminalEnum::WECHAT_OA; + $config = WeChatServer::getOaConfig(); + $app = Factory::officialAccount($config); + $response = $app + ->oauth + ->scopes(['snsapi_userinfo']) + ->getAccessToken($params['code']); + if (empty($response['openid'])) { + throw new Exception(); + } - return self::createAuth($response); + $userAuth = UserAuth::where('openid', $response['openid'])->findOrEmpty(); + if (isset($userAuth['id'])) { + if ($userAuth['user_id'] == $params['user_id']) { + return true; + } + throw new \Exception('该微信已绑定其他用户'); + } + + UserAuth::create([ + 'user_id' => $params['user_id'], + 'openid' => $response['openid'], + 'create_time' => time(), + 'unionid' => $response['unionid'] ?? '', + 'client' => Client_::oa, + ]); + + return true; } catch (\Exception $e) { self::$error = $e->getMessage(); @@ -519,124 +796,4 @@ class LoginLogic extends BaseLogic } } - - /** - * @notes 生成授权记录 - * @param $response - * @return bool - * @throws \Exception - * @author 段誉 - * @date 2022/9/16 10:43 - */ - public static function createAuth($response) - { - //先检查openid是否有记录 - $isAuth = UserAuth::where('openid', '=', $response['openid'])->findOrEmpty(); - if (!$isAuth->isEmpty()) { - throw new \Exception('该微信已被绑定'); - } - - if (isset($response['unionid']) && !empty($response['unionid'])) { - //在用unionid找记录,防止生成两个账号,同个unionid的问题 - $userAuth = UserAuth::where(['unionid' => $response['unionid']]) - ->findOrEmpty(); - if (!$userAuth->isEmpty() && $userAuth->user_id != $response['user_id']) { - throw new \Exception('该微信已被绑定'); - } - } - - //如果没有授权,直接生成一条微信授权记录 - UserAuth::create([ - 'user_id' => $response['user_id'], - 'openid' => $response['openid'], - 'unionid' => $response['unionid'] ?? '', - 'terminal' => $response['terminal'], - ]); - return true; - } - - - /** - * @notes 获取扫码登录地址 - * @return array|false - * @author 段誉 - * @date 2022/10/20 18:23 - */ - public static function getScanCode($redirectUri) - { - try { - $config = WeChatConfigService::getOpConfig(); - $appId = $config['app_id']; - $redirectUri = UrlEncode($redirectUri); - - // 设置有效时间标记状态, 超时扫码不可登录 - $state = MD5(time().rand(10000, 99999)); - (new WebScanLoginCache())->setScanLoginState($state); - - // 扫码地址 - $url = WeChatRequestService::getScanCodeUrl($appId, $redirectUri, $state); - return ['url' => $url]; - - } catch (\Exception $e) { - self::$error = $e->getMessage(); - return false; - } - } - - - /** - * @notes 网站扫码登录 - * @param $params - * @return array|false - * @author 段誉 - * @date 2022/10/21 10:28 - */ - public static function scanLogin($params) - { - Db::startTrans(); - try { - // 通过code 获取 access_token,openid,unionid等信息 - $userAuth = WeChatRequestService::getUserAuthByCode($params['code']); - - if (empty($userAuth['openid']) || empty($userAuth['access_token'])) { - throw new \Exception('获取用户授权信息失败'); - } - - // 获取微信用户信息 - $response = WeChatRequestService::getUserInfoByAuth($userAuth['access_token'], $userAuth['openid']); - - // 生成用户或更新用户信息 - $userServer = new WechatUserService($response, UserTerminalEnum::PC); - $userInfo = $userServer->getResopnseByUserInfo()->authUserLogin()->getUserInfo(); - - // 更新登录信息 - self::updateLoginInfo($userInfo['id']); - - Db::commit(); - return $userInfo; - - } catch (\Exception $e) { - Db::rollback(); - self::$error = $e->getMessage(); - return false; - } - } - - - /** - * @notes 更新用户信息 - * @param $params - * @param $userId - * @return User - * @author 段誉 - * @date 2023/2/22 11:19 - */ - public static function updateUser($params, $userId) - { - return User::where(['id' => $userId])->update([ - 'nickname' => $params['nickname'], - 'avatar' => FileService::setFileUrl($params['avatar']), - 'is_new_user' => YesNoEnum::NO - ]); - } } \ No newline at end of file diff --git a/app/common.php b/app/common.php index beb137d..d3baa03 100755 --- a/app/common.php +++ b/app/common.php @@ -78,6 +78,27 @@ function check_is_image($image) : bool return in_array($ImageType, [1, 2, 3, 6]); } + +function data_success($msg = '', $data = [], $code = 1, $show = 1) +{ + $result = [ + 'code' => $code, + 'msg' => $msg, + 'data' => $data, + 'show' => $show, + ]; + return $result; +} +function data_error($msg = '', $data = [], $code = 0, $show = 1) +{ + $result = [ + 'code' => $code, + 'msg' => $msg, + 'data' => $data, + 'show' => $show, + ]; + return $result; +} /** * @notes 检查文件是否可写 * @param string $dir diff --git a/app/common/logic/LogicBase.php b/app/common/logic/LogicBase.php new file mode 100644 index 0000000..44bad63 --- /dev/null +++ b/app/common/logic/LogicBase.php @@ -0,0 +1,43 @@ +