美文网首页
公众号授权网页获取 openid

公众号授权网页获取 openid

作者: 阿拉斯加南海岸线 | 来源:发表于2021-09-23 17:34 被阅读0次

参考官方文档的介绍,网页授权流程分为四步:

  1. 引导用户进入授权页面同意授权,获取 code;
  2. 通过 code 换取网页授权 access_token(与基础支持中的 access_token 不同);
  3. 如果需要,开发者可以刷新网页授权 access_token,避免过期;
  4. 通过网页授权 access_token 和 openid 获取用户基本信息(支持 unionid 机制)。

网页授权有两种 scope,以 snsapi_base 为 scope 发起的网页授权,是用来获取进入页面的用户 openid,同时是静默授权并自动跳转到回调页的。用户感知的就是直接进入了回调页(往往是业务页面),具体步骤如下:

第一步:用户同意授权,获取 code
访问页面的时候,重定向到授权页面(https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect),授权完成页面将跳转至 redirect_uri/?code=CODE&state=STATE。

第二步:通过 code 换取网页授权 access_token
本步骤中获取到网页授权 access_token 的同时,也获取到了 openid。
注意:由于公众号的 secret 和获取到的 access_token 安全级别都非常高,必须只保存在服务端,不允许传给客户端。因此,服务器发起获取 openid 的接口:

window.onload = function() {
    var localUrl = window.location.href;
    var code = getQueryString('code');
    var APPID = 'xxxxxxx';
    if(code == null || code == '' ) {
        var scopeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=" + encodeURIComponent(localUrl) + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect"
        window.location.href = scopeUrl;
    } else {
        console.log(code)
        // 调用服务端的通过 code 获取 openid 接口
        getWebOpenId(code).then(function(res) {
            console.log(res.result.openid)
        });  }

}

第三步:服务端获取 openid

相关代码如下所示:

// appid 和 appsecret 存储在服务端
var appId = config.appId,
    appSecret = config.appSecret;

// 公众号授权网页通过 code 获取 openid
router.post('/getCode', function(req, res) {
  console.log(req.body);
  var url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + appId + '&secret='+ appSecret +'&code=' + req.body.code + '&grant_type=authorization_code';
  axios.get(url)
    .then(function(response) {
      console.log('response', response.data);
      res.json(response.data)
    })
    .catch(function(err) {
      console.log(err)
      res.json(err)
    })
    .then(function() {

    })
})

获取的 openid 如下图所示:


网页获取到的 openid

相关文章

网友评论

      本文标题:公众号授权网页获取 openid

      本文链接:https://www.haomeiwen.com/subject/khdggltx.html