微信靜默授權(snsapi_base)


/**
*(不會彈出頁面,直接跳轉,只能獲取用戶的openid)
*/
function index(){
//公眾號在微信的appid
$appid = ""
//重定向到回調地址
$redirect_uri =urlencode('http://www.xxx.com/xxx/getUserInfo');
/*應用授權作用域,snsapi_base (不彈出授權頁面,直接跳轉,只能獲取用戶openid)
snsapi_userinfo (彈出授權頁面,可通過openid拿到昵稱、性別、所在地。
並且,即使在未關注的情況下,只要用戶授權,也能獲取其信息)*/
$scope = 'snsapi_base';
//重定向后會帶上state參數,開發者可以填寫a-zA-Z0-9的參數值,最多128字節
$state = '';
//進行重定向操作
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_uri.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
header("Location:".$url);
}

/**
* 得到用戶信息
*/
function getUserInfo(){
//通過code換取網頁授權access_token(訪問令牌)
$appid = "";//公眾號在微信的appid
$secret = "";//微信生成的秘鑰
$code = $_GET["code"];
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$json_obj =httpRequest($get_token_url);
//獲取用戶的openid
$openid = $json_obj['openid'];
//refresh_token有效期為30天,當refresh_token失效之后,需要用戶重新授權。
$refresh_token=$json_obj['refresh_token'];
//獲取第二步的refresh_token后,請求以下鏈接獲取access_token:
$get_user_info_url="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".$appid."&grant_type=refresh_token&refresh_token=".$refresh_token;
//獲取到用戶信息
$userinfo = $this->httpRequest($get_user_info_url);

}


/**
* curl請求封裝
*/
function httpRequest(){
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
return json_decode($res, true);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM