1.问题
微信网页授权获取用户详细信息即userinfo不成功
2.代码如下(php框架thinkPHP下编写)
//获取用户详细信息方法
class Index extends Action{
public function getUserInfo(){
$code = $_GET['code'];
//控制器自身链接
$self_uri = urlencode($_SERVER['SCRIPT_URI']);
if(!isset($code)){
//无值,重新获取code
$get_code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APP_ID."&redirect_uri=".$self_uri."&response_type=code&scope=snsapi_userinfo&state=16384#wechat_redirect";
header('location:'.$get_code_url);
}else{
//有值,直接用code获取用户access_token与openid
$handleModel = new HandleModel();
$base_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APP_ID."&secret=".APP_SECRET."&code=".$code."&grant_type=authorization_code";
$base_res = $handleModel->http_curl($base_url,'get','json');
dump($base_res);
//获取用户access_token与openid
$access_token = $base_res['access_token'];
$openid = $base_res['openid'];
$detail_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token.".&openid=".$openid."&lang=zh_CN";
//抓取用户详细信息
$detail_res = $handleModel->http_curl($detail_url,'get','json');
dump($detail_res);
}
}
}
以上代码是参照慕课网上微信开发教程以及网上一些教程结合而来,其中APP_ID与APP_SECRET的值已在配置文件中定义,而对象$handleModel的http_curl方法用于抓包。
3.报错情况
以上方法我用微信扫二维码访问以及在微信点击链接两种方法访问
1. 微信扫二维码报错情况
//代码中dump($base_res)输出
array(2){
["errcode"] => int(40163)
["errmsg"] => String(49) "Code been used,hints:[ req_id]: 1492wa0248th44"
}
//代码中dump($detail_res)输出
array(2){
["errcode"] => int(40001)
["errmsg"] => String "invalid credential,access_token is invalid or not lartest,hints:[ req_id]: 1492wa0248th44"
}
2. 在微信点击链接报错情况
//代码中dump($base_res)输出
array(5){
["access_token"] => String(107) "fkldflnfklrjvkljlkfbfh........"
["expires_in"] => int(7200)
["refresh_token"] => String(107) "fkldflnfklrjvkljlkfbfh........"
["openid"] => String(28) "idxpqekgfbfh........"
["scope"] => String(15) "snsapi_userinfo"
}
//代码中dump($detail_res)输出
array(2){
["errcode"] => int(40001)
["errmsg"] => String "invalid credential,access_token is invalid or not lartest,hints:[ req_id]: 1492wa0248th44"
}
对比下,直接点击链接能获取access_token;而扫二维码不仅提示code已用过,更导致后来获取access_token的出错
4.截图
1. 微信扫二维码访问时出现的中转提示页面
2. 微信点击链接访问时出现的中转提示页面
对比下,扫二维码提示页面出现两次,其提示的访问链接;而点击链接仅出现一次中转提示页面
5.尝试解决办法
我尝试过如慕课网教程那样,将方法getUserInfo拆分为两个方法infoA和infoB来实现,infoA负责重定向并且按微信网页授权机制携带参数code值到infoB,但结果与之前无二。
后来我猜想是否是访问时出现的"非微信官方页面"搞的鬼,导致页面的多次请求使code与access_token发生变更导致其失效。因为我尝试过点击其他域名的链接,都是直接跳转而不会出现"非微信官方页面"。可能跟域名未备案有关,但我的是新浪云的二级域名啊,还是实名验证过得啊,实在不可思议。
求大神解答,到底是我代码的错还是域名的错(排版太幼稚,请见谅^_^)