微信網頁授權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)就好

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