/**
*彈出授權頁面,可通過openid拿到昵稱、性別、所在地。並且,即使在未關注的情況下,只要用戶授權,也能獲取其信息
*/
function index(){
//公眾號在微信的appid
$appid = ""
//重定向到回調地址
$redirect_uri =urlencode('http://www.xxx.com/xxx/getUserInfo');
//應用授權作用域,
$scope = 'snsapi_userinfo';
//重定向后會帶上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 = "";
$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';
//獲取到access_token
$json_obj = httpRequest($get_token_url);
//根據openid和access_token查詢用戶信息
$access_token = $json_obj['access_token'];
$openid = $json_obj['openid'];
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
//獲取到用戶信息
$userinfo =httpRequest($get_user_info_url);
//記錄用戶信息
$wxuser = array(
'openid' => $userinfo['openid'],
'nickname' => base64_encode($userinfo['nickname']),
'headimgurl' => $userinfo['headimgurl'],
'sex' => $userinfo['sex'],
'province' => $userinfo['province'],
'city' => $userinfo['city'],
'country' => $userinfo['country']
);
//授權成功要重定向的地址
$url="http://www.***.cn"
header("Location:".$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);
}