网页授权获取用户信息

1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)
2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。
3、用户管理类接口中的“获取用户基本信息接口”,是在用户和公众号产生消息交互或关注后事件推送后,才能根据用户OpenID来获取用户基本信息。这个接口,包括其他微信接口,都是需要该用户(
即openid)关注了公众号后,才能调用成功的。

Scope为snsapi_base
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=回调地址&response_type=code&scope=snsapi_base&state=123#wechat_redirect
Scope为snsapi_userinfo
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=回调地址&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
  
header("content-type:text/html;charset=utf-8");
$appid="XXXXXXXXXXXXX";
$appsecret="XXXXXXXXXXXX";
//第一步过后回调地址为此页面(return_uri=这个页面的路径),并接收get传过来的值,获取code
$arr=$_GET;
$code=$arr['code'];
//拿到code之后获取网页授权access_token网页授权之后获取openid
$str=json_decode(file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code"),true);
$access_token=$str['access_token'];
$openid=$str['openid'];
//检验授权凭证(access_token)是否有效  正确的Json返回结果:{ "errcode":0,"errmsg":"ok"}错误时的Json返回示例:{ "errcode":40003,"errmsg":"invalid openid"}

$is=json_decode(file_get_contents("https://api.weixin.qq.com/sns/auth?access_token=$access_token&openid=$openid"),true);
if($is['errcode']===0){
    if(!empty($access_token) && !empty($openid)){
        $use=file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN");
        $use=json_decode($use,true);
        echo "姓名:".$use['nickname']."<br/>";
        echo "头像<img width='50px;' height='50px;' src='$use[headimgurl]'/>";
    }
}else{
    echo "未授权或参数无效";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值