微信详细授权(snsapi_userinfo)


/**
*弹出授权页面,可通过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);
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM