网站获取微信头像昵称

摘要

php网站获取微信头像昵称等信息的方法

有时网站需要获取用户微信头像用以显示

但是微信头像等信息的获取需要用户的同意,也就不像QQ头像那么容易获取

教程

首先获取授权

index.php  (授权页面)

<html>
<body>
    <script>
    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";     
    </script>
</body>
</html>

注意:将appid以及redirect_uri 改为自己的

oauth_response.php 文件

<?php  header("Content-type: text/html; charset=utf-8"); 


        //获取地址链接中的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 '</br>';
echo '5555';
    echo $user->{'nickname'}."</br>";
echo $user->{'sex'}."</br>";
echo $user->{'province'}."</br>";
echo $user->{'city'}."</br>";
echo $user->{'country'}."</br>";
echo $user->{'headimgurl'}."</br>";
echo $user->{'privilege'}."</br>";
echo $user->{'unionid'}."</br>";
echo $user->{'headimgurl'}."</br>";
?>  
<img src=" <?php echo $user->{'headimgurl'} ?> ">

注意:将appid及secret改为自己的

之后将微信公众号端的授权回调页面域名修改



做好之后,在微信中打开网页即可




admin

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: