有时需要用户同意授权才能获取到用户的信息,本文分享如何获取用户授权的用户信息
参考用户授权文档http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
在测试号管理页面下拉找到网页授权获取用户基本信息,填写域名
code.php文件
<?php
$code = $_GET['code'];
//扫码访问
//https://open.weixin.qq.com/connect/oauth2/authorize?appid=填写appid&redirect_uri=填写服务器上code.php地址&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Document</title>
</head>
<body>
<button>获取</button>
<div></div>
</body>
<script type="text/javascript" src="jquery-3.0.0.min.js"></script>
<script type="text/javascript">
$("button").on("click",function () {
$.ajax({
type:"get",
url:"get.php",
data:{code:"<?php echo $code; ?>"},
success:function(data){
$("div").html(data);
}
})
})
</script>
</html>
get.php文件
<?php
//一获取授权code值
$code = $_GET["code"];
// echo "$code";
$appid = '填写appid';
$secret = '填写secret';
//二根据code值获取access_token
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$str = file_get_contents($url);
$json = json_decode($str);
// var_dump($json);
$access_token = $json->access_token;
// 用户openID
$openid = $json->openid;
//获取用户信息地址
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
//获取接口信息
$user = file_get_contents($url);
//把获取的信息转为JSON对象
$obj = json_decode($user);
//输出表格显示获取到的信息
echo "<table>";
echo "<tr>
<td><img style='width:50px' src='{$obj->headimgurl}' /></td>
<td>{$obj->nickname}</td>
<td>".($obj->sex==1?"男":"女")."</td>
<td>{$obj->city}</td>
</tr>";
echo "</table>";
?>
将以上两个文件连同对应的jq文件上传至新浪云服务器。
将链接https://open.weixin.qq.com/connect/oauth2/authorize?appid=填写appid&redirect_uri=填写服务器上code.php地址&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect;转化为二维码,关注者通过扫码后进入一个页面,点击获取按钮,就会显示对应的关注者信息。