5.微信网页授权

微信网页授权

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

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

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

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

获取流程

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鉴权。

 

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

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

用户同意授权后

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

3. 通过code换取网页授权access_token

请求方法

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

参数说明

返回值

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

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

 

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

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

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

请求方法

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

参数说明

返回值

正确时返回的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"
}

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

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

上代码

后端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>

页面效果

 

 

转载于:https://www.cnblogs.com/alexzhang92/p/9380349.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值