网站微信扫码登陆
开发文档:https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
微信默认就有扫码登陆的接口,但网页授权作用域(scope=snsapi_login)需要额外收取验证费用,应此不想使用这个方式登陆
通过微信公从号,获取用户信息登陆
开发文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
方式:前端生成二维码-》用户扫码进入微信-》后端获取用信息并缓存-》js轮循校验缓存,显示登陆状态
//生成微信登陆二维码5分钟有效,并生成缓存登陆验证码
public function wxLoginImg(){
$loginCode = time().uniqid();
Cache::set($loginCode,'wait',300);
return $this->fetch('/default/builtIn/member_wxLoginImg',['loginCode'=>$loginCode]);
}
//获取微信用信息,并赋值给登陆验证码
//https://blockphp.com/index/member/wxLogin
public function wxLogin(){
//获取微信配置
$otherConfig = Db::name('sys')->where('key','otherConfig')->value('value');
$otherConfig = json_decode($otherConfig,true);
$appId = $otherConfig['weChat']['appid'];
$appsecret = $otherConfig['weChat']['appsecret'];
//获取code
$code = input('code');
if(empty($code)){
//当前页面地址
$backUrl = request()->url(true);
//url status携带参数
$status = input('loginCode');
//发起请求用户信息
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appId.'&redirect_uri='.urlencode($backUrl).'&response_type=code&scope=snsapi_userinfo&state='.$status.'#wechat_redirect';
$this->redirect($url,302);
}
$loginCode = input('state');
//获取access_token
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appId.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$res = file_get_contents($url);
$res = json_decode($res,true);
$openid = $res['openid'];
$access_token = $res['access_token'];
//获取用户信息
$getUserUrl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$userInfo = file_get_contents($getUserUrl);
Cache::set($loginCode,$userInfo);
return $this->fetch('/default/builtIn/member_wxLogin');
}
//js 轮循验证是否扫码登陆
//$loginCode 登陆验证码
public function wxCodeLogin($loginCode){
$loginCode = input('post.loginCode');
$userinfo = Cache::get($loginCode);
if(!$userinfo){
return 'outTime';
}
if($userinfo == 'wait'){
return 'wait';
}
$userinfo = json_decode($userinfo,true);
$user =  Db::name('member')->where(['openid'=>$userinfo['openid']])->find();
if($user){
$this->buildLogin($user);
return 'success';
}
$ip = request()->ip();
$addtime = $lasttime = time();
$user =['ip'=>$ip,'username'=>$userinfo['nickname'],'openid'=>$userinfo['openid'],'headimg'=>$userinfo['headimgurl'],'sex'=>$userinfo['sex'],'userType'=>'wx','addtime'=>$addtime,'lasttime'=>$lasttime];
$user['id'] = Db::name('member')->insertGetId($user);
$this->buildLogin($user);
Cache::rm($loginCode);
return 'success';
}