授权的整个 流程梳理
1、首先获取到code
如何获取呢? https://open.weixin.qq.com/connect/oauth2/authorize?appid=".C('wxconfig')['appid']."&redirect_uri=http://www.xxx.com/&response_type=code&scope=snsapi_userinfo&state=kylife#wechat_redirect
这个授权连接地址一调用以后,微信服务器会 调转到你指定的redirect_url设置的地址,,注意:同时将code作为参数带到 redirect_url的后面
如上连接后就会 连接会变成:http://www.xxx.com/code/code码/state/kylife
2、此时获取到code以后,你在去 通过code获取 获取token和openid了
https://api.weixin.qq.com/sns/oauth2/access_token?appid=appid&secret=secret&code=上一步拿到的code&grant_type=authorization_code
3、至此,token和openid有了,就可以调用获取 微信客户 基本信息接口,拿昵称等信息了
https://api.weixin.qq.com/sns/userinfo?access_token=上边拿到的token&openid=上边拿到的openid&lang=zh_CN
OK
封装的一个简单方法 实现了以上流程:
//获取微信 客户端授权信息
function getWxinfo(){
//获取token
$token = C('wxconfig')['appid']; //appid
$secret = C('wxconfig')['secret'];//secret
$code = $_REQUEST;
if(!isset($_GET['code'])){ //如果code不存在,就header跳转一下授权地址,此时 redirect_uri=http://www.xxx.com/xx.php授权后就会get中传递了code然后再次调用本函数,此时code存在就会走下边获取到 信息了
header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".C('wxconfig')['appid']."&redirect_uri=http://www.xxx.com/xx.php&response_type=code&scope=snsapi_userinfo&state=kylife#wechat_redirect");
}
$arr = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$token."&secret=".$secret."&code=".$code['code']."&grant_type=authorization_code");
$arr = json_decode($arr,true);
$userinfo = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=".$arr['access_token']."&openid=".$arr['openid']."&lang=zh_CN");
return $userinfo;
}