准備:你自己需要有備案好的域名。在權限表-網頁授權獲取用戶信息 里面可以設置該域名。
微信開發文檔有四部:
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'); // 攜帶code跳轉到該地址,也就是下面這個函數
$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);
}
//2、獲取用戶openid
public function getUserOpenId(){
$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 ";
//獲取openid
$res = $this->http_curl($url);
var_dump($res); //里面便是有openid數據
}
掃碼:http://wx.xx.com/index.php/Weixin/Index/getBaseInfo 生成的二維碼,可以看到打印出來了:
{ "access_token":"", "expires_in":7200, "refresh_token":"", "openid":"", "scope":"" } 這幾個參數。
使用:
$res 里面便是有openid這個時候便是可以針對只需知道用戶openid開發的小功能了:比如 用戶記事本。
function getUserOpenId() 后面可以補充成:
$openid = $res['openid'];
$this->assign('openid',$openid);
$this->display('message');
二、snsapi_userinfo
//1、獲取code
public function getUserDetail(){
$appid = 'wxe3ccbacbfdxxxxxx';
$redirect_url = urlencode('http://wx.xx.com/index.php/Weixin/Index/getUserinfo'); //攜帶code跳轉到該地址,即下面方法
$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(){
$appid = 'wxe3ccbacbfdxxxxxx';
$appsecret = '989b45dd6d2441ed01a5f59336aaaaaa';
$code = $_GET['code']; //從上面函數 getUserDetail 獲取得到
//2、獲取openid和access_token
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code ";
$res = $this->http_curl($url);
$openid = $res['openid'];
$access_token = $res['access_token'];
//3、獲取用戶信息
$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、redirect_uri 鏈接 xx.com 域名是要備案的,可以在開發-權限接口-網頁授權獲取用戶信息 里面配置
2、注意獲取code的函數(getBaseInfo)里面redirect_url鏈接是指向獲取用戶openid信息的函數(getUserOpenId),獲取后的相應功能邏輯可以在這邊實現,但菜單鏈接是先訪問 獲取code 函數(getBaseInfo)
菜單鏈接:http://wx.xx.com/index.php/Weixin/Index/getBaseInfo
3、整個邏輯的一個順序是:
訪問菜單上面鏈接 getBaseInfo函數 ,攜帶着 code 跳轉到redirect_url 如: redirect_url (getUserOpenId) 或者redirect_url ( getUserinfo),里面獲取到openid 或用戶具體資料信息 后再利用這些信息做功能開發、邏輯跳轉,如:$this->assign('openid',$openid);$this->display('message'); 。