您的位置:首页 > 移动开发 > 微信开发

微信网页授权获取用户基本信息

2017-07-30 10:51 525 查看
如果用户在微信客户端中访问第三方网页,公众号可以通过微信网页授权机制,来获取用户基本信息,但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。

网页授权分为两种,这两种以scope来区别:

1、以snsapi_base为scope发起的网页授权,是用来获取进入页面的用户的openid的,并且是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面)

2、以snsapi_userinfo为scope发起的网页授权,是用来获取用户的基本信息的。但这种授权需要用户手动同意,并且由于用户同意过,所以无须关注,就可在授权后获取该用户的基本信息。

基本步骤如下:

1 第一步:准备发起的网页授权的回调页URL

2 第二步:用户同意授权,获取code

3 第三步:通过code换取网页授权access_token

4 第四步:刷新access_token(如果需要)
5 第五步:拉取用户信息(需scope为 snsapi_userinfo)

好了,直接贴方法代码:

前期准备:
配置授权回调域名

微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的开发者中心页配置授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头



先构造好PHP的curl网络请求函数,方法见:PHP中的curl网络请求

1.Scope为snsapi_base基本授权

[php]
view plain
copy

public function _baseAuth($redirect_url){  
      
    //1.准备scope为snsapi_base网页授权页面  
    $baseurl = urlencode($redirect_url);  
    $snsapi_base_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->_appid.'&redirect_uri='.$baseurl.'&response_type=code&scope=snsapi_base&state=YQJ#wechat_redirect';  
      
    //2.静默授权,获取code  
    //页面跳转至redirect_uri/?code=CODE&state=STATE  
    $code = $_GET['code'];  
    if( !isset($code) ){  
        header('Location:'.$snsapi_base_url);  
    }  
      
    //3.通过code换取网页授权access_token和openID  
    $curl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->_appid.'&secret='.$this->_appsecret.'&code='.$code.'&grant_type=authorization_code';  
    $content = $this->_request($curl);  
    $result = json_decode($content);  
      
    return $result;  
}  

2.Scope为snsapi_userinfo用户授权

[php]
view plain
copy

public function _userInfoAuth($redirect_url){  
      
    //1.准备scope为snsapi_userInfo网页授权页面  
    $redirecturl = urlencode($redirect_url);  
    $snsapi_userInfo_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->_appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=YQJ#wechat_redirect';  
      
    //2.用户手动同意授权,同意之后,获取code  
    //页面跳转至redirect_uri/?code=CODE&state=STATE  
    $code = $_GET['code'];  
    if( !isset($code) ){  
        header('Location:'.$snsapi_userInfo_url);  
    }  
      
    //3.通过code换取网页授权access_token  
    $curl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->_appid.'&secret='.$this->_appsecret.'&code='.$code.'&grant_type=authorization_code';  
    $content = $this->_request($curl);  
    $result = json_decode($content);  
      
    //4.通过access_token和openid拉取用户信息  
    $webAccess_token = $result->access_token;  
    $openid = $result->openid;  
    $userInfourl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$webAccess_token.'&openid='.$openid.'&lang=zh_CN ';  
      
    $recontent = $this->_request($userInfourl);  
    $userInfo = json_decode($recontent,true);  
    return $userInfo;  
}  

亲测有效
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: