现在,我们要实现一个微信内网页,通过微信访问网页时,网页会展示微信用户的个人信息。因为涉及到用户的个人信息,所以需要有用户授权才可以。当用户授权后,我们的网页服务器(开发者服务器)会拿到用户的“授权书”(code),我们用这个code向微信服务器领取访问令牌(accecc_token)和用户的身份号码(openid),然后凭借access_token和openid向微信服务器提取用户的个人信息。


  • 第一步:用户同意授权,获取code
  • 第二步:通过code换取网页授权access_token
  • 第三步:拉取用户信息(需scope为 snsapi_userinfo)


那么,如何拿到用户的授权code呢?

授权是由微信发起让用户进行确认,在这个过程中是微信在与用户进行交互,所以用户应该先访问微信的内容,用户确认后再由微信将用户导向到我们的网页链接地址,并携带上code参数。我们把这个过程叫做网页回调,类似于我们在程序编写时用到的回调函数,都是回调的思想。

1.获取流程

1.1 设置网页授权回调域名

微信公众号请求用户网页授权之前,开发者需要先到公众平台官网中的开发者中心页配置授权回调域名。请注意,这里填写的是域名(是一个字符串),而不是URL,因此请勿加 http:// 等协议头;

授权回调域名配置规范为全域名,比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com无法进行OAuth2.0鉴权。

13 公众号开发 - 微信网页授权_微信

13 公众号开发 - 微信网页授权_微信_02

1.2 用户同意授权,获取code

让用户访问一下链接地址:

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

13 公众号开发 - 微信网页授权_微信_03

下图为scope等于snsapi_userinfo时的授权页面:

13 公众号开发 - 微信网页授权_微信_04

用户同意授权后

如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE

1.3 通过code换取网页授权access_token

请求方法:

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

参数说明:

13 公众号开发 - 微信网页授权_微信_05

返回值

正确时返回的JSON数据包如下:

{
"access_token":"ACCESS_TOKEN",
"expires_in":7200,
"refresh_token":"REFRESH_TOKEN",
"openid":"OPENID",
"scope":"SCOPE"
}

13 公众号开发 - 微信网页授权_html_06

错误时微信会返回JSON数据包如下(示例为Code无效错误):

{
"errcode":40029,
"errmsg":"invalid code"
}

1.4 拉取用户信息(需scope为 snsapi_userinfo)

请求方法

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

参数说明

13 公众号开发 - 微信网页授权_网页授权_07

返回值

正确时返回的JSON数据包如下:

{
"openid":" OPENID",
" nickname": NICKNAME,
"sex":"1",
"province":"PROVINCE"
"city":"CITY",
"country":"COUNTRY",
"headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
"privilege":[
"PRIVILEGE1"
"PRIVILEGE2"
],
"unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
}

13 公众号开发 - 微信网页授权_网页授权_08

错误时微信会返回JSON数据包如下:

{
"errcode":40003,
"errmsg":" invalid openid "
}

2.代码

后端Python程序(以Tornado框架为例)​:

class UserHandler(tornado.web.RequestHandler):
"""获取粉丝信息页面"""
@tornado.gen.coroutine
def get(self):
code = self.get_argument("code")
if not code:
self.write("您未授权,无法获取您的信息!")
return
client = AsyncHTTPClient()
url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code" % (WECHAT_APPID, WECHAT_APPSECRET, code)
resp = yield client.fetch(url)
ret = json.loads(resp.body)
access_token = ret.get("access_token")
if access_token:
openid = ret.get("openid")
url = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN" % (access_token, openid)
resp = yield client.fetch(url)
ret = json.loads(resp.body)
if ret.get("errcode"):
self.write(ret.get("errmsg", "获取个人信息错误"))
else:
self.render("user.html", user=ret)
else:
self.write(ret.get("errmsg", "获取access_token错误"))

端user.html文件代码

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{user["nickname"]}}的个人主页</title>
</head>
<body>
<img alt="头像" src="{{user['headimgurl']}}">
<table>
<tr>
<th>openid</th>
<td>{{user["openid"]}}</td>
</tr>
<tr>
<th>昵称</th>
<td>{{user["nickname"]}}</td>
</tr>
<tr>
<th>性别</th>
<td>
{% if 1 == user["sex"] %}

{% elif 2 == user["sex"] %}

{% else %}
未知
{% end if %}
</td>
</tr>
<tr>
<th>省份</th>
<td>{{user["province"]}}</td>
</tr>
<tr>
<th>城市</th>
<td>{{user["city"]}}</td>
</tr>
<tr>
<th>国家</th>
<td>{{user["country"]}}</td>
</tr>
</table>
</body>
</html>

3.页面效果

13 公众号开发 - 微信网页授权_微信_09

13 公众号开发 - 微信网页授权_网页授权_10