微信静默授权(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);
}

posted @ 2017-08-14 11:01  满月夜  阅读(7270)  评论(0编辑  收藏  举报