实现逻辑
用户访问需要授权登陆的公众号,用是否存在openid判断登录状态。不存在,重定向到微信服务器。
微信服务器返回code,用code换取openid和access_token。
再用openid和access_token换取用户信息。
代码逻辑
判断openid,重定向到微信服务器
if (!$this->isAuth()) {
$this->current_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
Cookie::set('target_url',$this->current_url);
$userAuth = new Weixin();
$userAuth->getCode();
}
//判断登录状态
function isAuth(){
$openid = Cookie::get('openid');
if(!empty($openid)){
$this->openid=$openid;
return true;
}else{
return false;
}
}
//获取code
public function getCode()
{
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . url('index/Weixin/auth');
$jummpUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=" . urlencode($redirect_uri) . "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
$this->redirect($jummpUrl);
}
接收微信服务器返回的code,并换取openid和access_token
//微信登陆授权
public function auth()
{
$code = $this->request->param('code');
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->appSecret . "&code=" . $code . "&grant_type=authorization_code";
$json = json_decode(file_get_contents($url), true);
$userInfo = $this->getUserInfo($json);
}
用openid和access_token换取用户微信信息
//换取用户微信信息
function getUserInfo($json){
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $json['access_token'] . "&openid=" . $json['openid'] . "&lang=zh_CN";
$data = json_decode(file_get_contents($url), true);
return $data;
}
结语
其实授权就是几个接口互相请求。比较困难的是调试,因为你无法打印微信服务器返给你的信息,可以自己写日志来进行调试。
附上连接
微信官方文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842