因为用的是thinkcmf,所有有的地方写法和原生的不一样。。。
微信扫码登录,首先在开放平台申请到AppID和AppSecret,通过APPID获取到acces_token,然后在跳转的扫码页面扫码之后就能获取到用户的信息,接着改变登录状态
$code= $this->request->get("code");
//开放平台的appid和appsercert
$AppID='';
$AppSecret='';
$myurl="";//这里是点击跳转的链接
$redirect_uri=urlencode($myurl);
$url="https://open.weixin.qq.com/connect/qrconnect?appid=".$AppID."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_login&state=STATE#wechat_redirect";
$userinfo_data=array();
if (empty($code)) {
$this->redirect($url);
}else{
session('code',$code);
if (empty(session('access_token'))|| empty(session('openid'))) {
$oauth2_info = $this->oauth2_access_token($AppID,$AppSecret,$code);
}
$openid= session('openid');
$userinfo = $this->oauth2_get_user_info(session('access_token'), session('openid'));
if (isset($userinfo['errcode'])) {
//access_token过期时需要重新获取
session('access_token',null);
$this->redirect($url);
$oauth2_info = $this->oauth2_access_token($AppID,$AppSecret,$code);
}
//根据获取的openid查询是老用户或新用户
$userinfo_res=Db::name('wechat_fans')->where('openid',$openid)->find();
$useryssk_res=Db::name('user')->where('openid',$openid)->find();
//微信用户的信息
$userwechat_data=array(
'nickname'=>$userinfo['nickname'],
'openid'=>$openid,
'headimgurl'=>$userinfo['headimgurl'],
'sex'=>$userinfo['sex'],
);
//用户表的用户信息
$useryssk_data=array(
'user_type'=>'2',
'user_nickname'=>$userinfo['nickname'],
'openid'=>$openid,
'avatar'=>$userinfo['headimgurl'],
'sex'=>$userinfo['sex'],
);
//进行操作
if (empty($userinfo_res) ||empty($useryssk_res)) {
$useryssk_res =Db::name('user')->insert($useryssk_data);
$useryssk_info_new=Db::name('user')->where('openid',$openid)->find();
$userwechat_data['user_id']=$useryssk_info_new['id'];
$userinfo_ins=Db::name('wechat_fans')->insert($userwechat_data);
}else{
session('user',$useryssk_res);
$useryssk_info_new=Db::name('user')->where('openid',$openid)->find();
$userinfo_data['user_id']=$useryssk_info_new['id'];
$res=Db::name('wechat_fans')->where('openid',$openid)->update($userinfo_data);
}
//生成OAuth2的Access Token
public function oauth2_access_token($appid,$appsecret,$code)
{
$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);
$oauth2_info= json_decode($res, true);
session('access_token',$oauth2_info['access_token']);
session('openid',$oauth2_info['openid']);
return json_decode($res, true);
}
//获取用户基本信息(OAuth2 授权的 Access Token 获取 未关注用户,Access Token为临时获取)
public function oauth2_get_user_info($access_token, $openid)
{
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
$res = file_get_contents($url);
return json_decode($res, true);
}