美文网首页
NodeJs开发微信记录(3)--网页授权

NodeJs开发微信记录(3)--网页授权

作者: neoyoun | 来源:发表于2017-03-03 20:54 被阅读0次

    微信公众号提供的与用户互动的功能有限,大部分的业务场景还是需要用户跳转到网页中来实现。同时我们需要获取微信用户信息,这时候我们绕不开的一个重要的点就是微信网页开发。根据官方文档,网页开发有几个步骤:

    步骤1--设置域名

    设置回调域名,登录公众号后 ,进入 ‘开发-接口权限’ ,下拉找到‘网页授权’,修改设置域名(纯域名,不带http或https等协议头)。域名需要ICP备案,填写之后需要下载验证文件。把文件放到项目根目录,路由设置该路径为静态文件。我使用的路由规则是 '/:file',判断为 txt文件名直接返回文件。如果同目录下有其他不希望暴露的文件则需要更细致的判断。

    步骤2--逻辑实现

    网页授权有两种形式
    snsapi_base -- 获取基本信息,仅需要识别用户的话,通过这个就能拿到用户的 openid。如果绑定了开放平台的话,还会返回一个 unionId。这种授权是不需要用户同意的(省去一些信任成本)
    snsapi_userinfo -- 获取用户详细信息,包括用户性别、昵称、地区、性别、微信头像等。如果需要的话选这种,需要用户确认登录。
    相关代码长这样(koa2框架的写法):

    'use strict'
    const rp = require('request-promise')
    let scopePage = async (ctx, next)=>{
      if(!ctx.query.code && !ctx.query.state) {
        //首次进入,需要跳转到scopeurl 来获取 code
        let curUrl = ctx.href
        let scopeUrl = generatorScopeUrl(curUrl, 'info')
        ctx.status = 302;
        ctx.redirect(scopeUrl)
      } else if(ctx.query.code && ctx.query.state) {
        //用户同意授权
        let code = ctx.query.code; 
        let appid = 'yourappid'; //公众号appid
        let fetchWechatUserInfo = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=SECRET&code=${code}&grant_type=authorization_code `;
        let options = {
          method: 'GET',
          uri: fetchWechatUserInfo,
          json: true
        }
        let userInfo = await rp(options);
        if(userInfo.errcode){
          throw new Error('fetch userInfo failure, please check the params')
        }
        let {openid, access_token, refresh_token} = userInfo
      
        let fetchWechatUserDetailInfoUrl = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN `;
        let userDetailInfo = await rp({method:'GET', uri: fetchWechatUserDetailInfoUrl, json:true })
        userInfo = Object.assign({}, userInfo, userDetailInfo)
        ... //dosomething
      }
    }
    function generatorScopeUrl(url, type) {
      if(!url) return false;
      let scopeType = 'snsapi_base';
      if(type == 'info){
        scopeType = 'snsapi_userinfo';
      }
      let state = 'userstate'; //自定义字符串
      let appid = 'yourappid'; //公众号的appid
      return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=${scopeType}&state=${state}#wechat_redirect `
    }
    

    一般拿到用户信息后,将相关信息渲染到模板中。这样就能给每个用户返回不一样的内容了。
    在用户后续的操作中,我们可以进一步完善用户信息(譬如要求用户绑定手机号码),后面如果需要对用户推送通知之类的就可以实现了。
    微信网页开发更强大的功能在 JSSDK 中,以后再记录。

    相关文章

      网友评论

          本文标题:NodeJs开发微信记录(3)--网页授权

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