摘要
php网站获取微信头像昵称等信息的方法
有时网站需要获取用户微信头像用以显示
但是微信头像等信息的获取需要用户的同意,也就不像QQ头像那么容易获取
教程
首先获取授权
index.php (授权页面)
window.location.href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxdc******81c9143&redirect_uri=http://www.h1.xhbjwy.xin/oauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect";
注意:将appid以及redirect_uri 改为自己的
//获取地址链接中的code参数
$location = $_SERVER["QUERY_STRING"];
$data = strstr($location,'&',true);
$code = substr($data, 5);
//curl 的post请求
function CurlPost($url, $data)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
curl_setopt($curl, CURLOPT_URL, $url);
if(!empty($data))
{
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
//get请求
function CurlGet($url)
{
return CurlPost($url, "");
}
//通过code换取网页授权access_token
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx2e******e98d6577&secret=195ef2*****6308e6e2d3ab477d7&code=".$code."&grant_type=authorization_code";
$rs = json_decode(CurlGet($url));
//请求成功返回access_token
if(isset($rs->{'access_token'})){
//保存access_token
$access_token = $rs->{'access_token'};
$openid = $rs->{'openid'};
//请求成功返回errcode
}else if (isset($rs->{'errcode'})) {
//# code...
}
//拉取用户信息(需scope为 snsapi_userinfo)
$user = json_decode(CurlGet("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN"));
echo '';
echo '5555';
echo $user->{'nickname'}."";
echo $user->{'sex'}."";
echo $user->{'province'}."";
echo $user->{'city'}."";
echo $user->{'country'}."";
echo $user->{'headimgurl'}."";
echo $user->{'privilege'}."";
echo $user->{'unionid'}."";
echo $user->{'headimgurl'}."";
?>
注意:将appid及secret改为自己的
之后将微信公众号端的授权回调页面域名修改
做好之后,在微信中打开网页即可