微信网页授权snsapi_base,snsapi_userinfo区别和实现

文章转至longlongcheng >>>

微信开发文档有四部:

1 第一步:用户同意授权,获取code

2 第二步:通过code换取网页授权access_token、openid

3 第三步:刷新access_token(如果需要)

4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

snsapi_base: 到第二步就结束了,获取到openid,其他操作在这个基础上(比如记录该用户访问时间次数信息)

snsapi_userinfo: 获取openid和用户资料(暱称、头像、国、省、城市、性别、权限)

snsapi_base:

public function getBaseInfo(){
    //1、获取code
    $appid = 'wxe3ccbacbfdxxxxx';
    $redirect_url = urlencode('http://wx.xx.com/index.php/Weixin/Index/getUserOpenId');
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    header('location:'.$url);
}

//获取用户openid
public function getUserOpenId(){
    //2、获取网页授权的access_token
    $appid = 'wxe3ccbacbfdxxxxx';
    $appsecret = '989b45dd6d2441ed01a5f5933aaaaaaa';
    $code = $_GET['code']; //从上面函数getBaseInfo获取得到
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code ";
    //3、获取openid
    $res = $this->http_curl($url);
    var_dump($res); //里面便是有openid数据
}

userinfo:

//1、获取code

public function getUserDetail(){
    $appid = 'wxe3ccbacbfdxxxxxx';
    $redirect_url = urlencode('http://wx.xx.com/index.php/Weixin/Index/getUserinfo');
    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_userinfo&state=333#wechat_redirect";
    header('location:'.$url);
}

public function getUserinfo(){
    //2、获取网页授权的access_token
    $appid = 'wxe3ccbacbfdxxxxxx';
    $appsecret = '989b45dd6d2441ed01a5f59336aaaaaa';
    $code = $_GET['code']; //从上面函数getBaseInfo获取得到
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code ";
    //3、获取用户信息
    $res = $this->http_curl($url);
    $openid = $res['openid'];
    $access_token = $res['access_token'];
    $url2 = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
    $res2 = $this->http_curl($url2);
    var_dump($res2); 
}

注意:

1、获取code – xx.com域名是要备案的,在开发-权限接口-网页里面配置

2、注意获取code的函数(getBaseInfo)里面链接是指向获取用户openid和信息函数(getUserOpenId)的获取后的相应功能逻辑可以在这边实现,但代码访问 获取code 函数(getBaseInfo)就好

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章