跳至正文

微信公众号-获取用户信息(网页授权获取)

  • 后端

根据微信公众号开发官方文档:
获取用户信息步骤如下:

1 第一步:用户同意授权,获取code
2 第二步:通过code换取网页授权access_token
3 第三步:刷新access_token(如果需要)
4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

1 获取code

在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(服务号获得高级接口后,默认拥有scope参数中的snsapi_base和snsapi_userinfo),引导关注者打开如下页面:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect

若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
尤其注意:由于授权操作安全等级较高,所以在发起授权请求时,微信会对授权链接做正则强匹配校验,如果链接的参数顺序不对,授权页面将无法正常访问

其中:
AppID – 公众号的唯一标识
REDIRECT_URI – 跳转url
SCOPE – 值为snsapi_base(不弹出授权页面,直接跳转,只能获取用户openid) 或snsapi_userinfo (弹 出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)
STATE – 开发者可以自定义填写a-zA-Z0-9的参数值

2 通过code换取网页授权access_token

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE

state就是上面的STATE参数原样传过来的
实现代码:

$code = I('get.code');
if (empty($code)) {
	//todo 非微信访问
	exit('<h1>请关注公众号“萧山新华书店小书虫俱乐部”来访问此页面</h1>');
}else{
	//授权后操作
}

在这里我们就可以得到code用作后续的获取access_token。

获取code后,请求以下链接获取access_token:

https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

appid – 公众号的唯一标识
secret – 密钥
code – 上述所返回的code
grant_type – 值为authorization_code

实现代码:

$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . C('wechat.AppID') . '&secret=' . C('wechat.AppSecret');
$str = file_get_contents($url);
$str = json_decode($str, true);
$access_token = $str['access_token'];

这里access_token可以做缓存处理,避免造成频繁获取
实现代码,以TP框架为例:

$access_token = S('access_token');
if (empty($access_token)) {
	$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . C('wechat.AppID') . '&secret=' . C('wechat.AppSecret');
	$str = file_get_contents($url);
	$str = json_decode($str, true);
	$access_token = $str['access_token'];
	S('access_token', $access_token, 3600);
}

在获取access_token后,也会一并返回openid(用户唯一标识),微信官方文档的解释是:用户唯一标识,请注意,在未关注公众号时,用户访问公众号的网页,也会产生一个用户和公众号唯一的OpenID
openid是唯一标识微信用户的,如果用户不是第一次登陆,可以在得到openid后查询数据库是否有绑定此openid的用户,之后就无需重新获取用户数据,直接获取的数据库user_id设置session,直接登陆访问

3 第三步忽略,只在需要的时间重新获取access_token而已
4 拉取用户信息(需scope为 snsapi_userinfo)
在数据库无此微信号用户的绑定下,就相当于用户首次访问登陆,则通过第四步来获取用户信息(在用户授权情况下,网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了),然后后台创建user并绑定此微信用户(通过openid)
请求方法
http:GET(请使用https协议)

https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN

access_token – 上述所获取的access_token
openid – 公众号唯一标识
实现代码

$url = "https://api.weixin.qq.com/sns/userinfo?access_token==$access_token&openid=$openid&lang=zh_CN";
$str = file_get_contents($url);
$str = json_decode($str, true);
if (empty($str['errcode'])) {
	//创建user并绑定openid
}else{
	//错误处理
}

完整代码如下:

// 创建自定义函数 userRight ,判断用户是否登录
function userRight(){
	global $config;
	if(isset($_SESSION['user']['id']) && is_numeric($_SESSION['user']['id']) && isset($_SESSION['user']['openid']) && isset($_SESSION['user']['unionid'])){
		return true;
	}
	return false;
}

// 配置全局变量,微信公众号相关参数从微信官网获取
$config['wexin']['AppID'] = 'wxfxxxxxxxxxxxxxxx';
$config['wexin']['AppSecret'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$config['wexin']['redirect'] = 'https://wx.xxxxxx.com/weixin/login.php';  // 跳转回调redirect_uri,应当使用https链接来确保授权code的安全性
$config['wexin']['login'] = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$config['wexin']['AppID'].'&redirect_uri='.urlencode($config['wexin']['redirect']).'&response_type=code&scope=snsapi_userinfo#wechat_redirect';

// 判断用户是否登录,未登录则跳转到微信授权页面,获取code
if(!userRight()){
	header('location:'.$config['wexin']['login']);
	exit;
}

// 页面 /weixin/login.php 处理流程:

//获取 code
$code = $_GET['code'];

//获取 access_token 和 openid
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$config['wexin']['AppID'].'&secret='.$config['wexin']['AppSecret'].'&code='.$code.'&grant_type=authorization_code';
$str = file_get_contents($url);
$str = json_decode($str, true);
$access_token = $str['access_token'];
$openid = $str['openid'];

//获取微信用户信息
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$config['wexin']['AppID'].'&lang=zh_CN';
$str = file_get_contents($url);
$str = json_decode($str, true);
$nickname = $str['nickname'];
$sex = $str['sex'];
$province = $str['province'];
$city = $str['city'];
$country = $str['country'];
$headimgurl = $str['headimgurl'];
$privilege = implode(',', $str['privilege']);
$unionid = $str['unionid'];

if(!$unionid){
	echoHtml('<script>alert("拉取微信授权信息失败,请重新用微信登录方式登录本公众号。"); window.parent.location.href="/weixin/exit.php";</script>');
	exit;
} else {
	// 业务处理
}

以上就是微信公众号获取用户信息的具体步骤,详细接口文档请参考官方文档:微信公众号开发文档-网页授权登录