微信授权php获取用户基本信息
未关注微信公众号进行基本信息获取
- 首先配置你的回调函数页面
- 配置js 接口安全域名(用来调用js接口)
- 在新建网站根目录新建getcodeurl.php添加代码如下
//换成自己的接口信息
$appid = 'XXXXX';
header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri=你的域名/oauth.php&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect');
参数如下
应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
- 新建oauth.php 文件 添加代码如下
<?php
$code = $_GET['code'];
$state = $_GET['state'];
//换成自己的接口信息
$appid = 'XXXXX';
$appsecret = 'XXXXX';
if (empty($code)) $this->error('授权失败');
$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
echo '<h1>错误:</h1>'.$token->errcode;
echo '<br/><h2>错误信息:</h2>'.$token->errmsg;
exit;
}
$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//转成对象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
echo '<h1>错误:</h1>'.$access_token->errcode;
echo '<br/><h2>错误信息:</h2>'.$access_token->errmsg;
exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//转成对象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
echo '<h1>错误:</h1>'.$user_info->errcode;
echo '<br/><h2>错误信息:</h2>'.$user_info->errmsg;
exit;
}
//打印用户信息
echo '<pre>';
print_r($user_info);
echo '</pre>';
?>
在你的微信打开连接www.你的域名.com/getcodeurl.php 成功拿到用户信息
www.186886.top
liulei.186886.top