【微信开发】NodeJS解决微信网页授权获取用户信息

目录

前言

1.开发前准备工作

2.后台开发工作

3.前端开发工作

4.调试工作


 

前言

先回顾一下微信开发中涉及的各种概念以及微信网页授权的流程图

【微信开发】常见的openid/unionid/session_key/access_token究竟是个啥?

官方API文档:微信网页开发-网页授权

 

1.开发前准备工作

开发前的准备工作很简单,登录微信公众号后台

(1)配置授权回调域名:在公众号 “开发 - 接口权限 - 网页服务 - 网页帐号 - 网页授权获取用户基本信息”的配置选项中,修改授权回调域名。

(2)获取公众号的 APPID

(3)获取公众号的AppSecret

 

2.后台开发工作

准备工作完成,进入后台接口开发 app.js

 

后台接口的开发工作十分的简单,有两个 ① /wechat_login ② /user

① 前端请求 /wechat_login ,代表需要申请微信授权,此时,后台重定向至微信授权页面,携带参数 APPID + redirect_uri + scope

② 前端请求 /user, 携带参数code,code即临时登录凭证,后台使用code调微信接口,换取微信用户信息。这一步稍稍有一丢丢复杂,需要拆分成一下几个步骤:

code + AppID + Appsecret → 调微信接口sns/oauth2 → 获取 acccess_token + openid → 调微信接口sns/userinfo - 获取微信用户基本信息userinfo

 

到这里,后台的接口开发工作就结束了。

 

const path = require('path')
const bodyParser = require('body-parser')
const express = require('express')
const app = new express()
const request = require('request')
const port = process.env.PORT || 80;


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ //解析post请求数据
  extended: false
})); 
app.use(express.static('public'));
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
})


const AppID = 'wx8a*********9c03f';
const AppSecret = '255325a***********0db6ce3da8';
const redirect_uri = 'http%3a%2f%2fwww.chunling.online';  // url记得先用encodeURI编码
const scope = 'snsapi_userinfo';


app.get('/wechat_login', (req, res) => { 
  // 第一步,重定向到微信授权页面
  res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + AppID + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=' + scope + '&state=STATE#wechat_redirect');
})

app.get('/user', function (req, res, next) {
  // 第二步:通过code换取网页授权access_token和用户openid
  var code = req.query.code; 
  request.get({
    url: 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + AppID + '&secret=' + AppSecret + '&code=' + code + '&grant_type=authorization_code',
  }, function (error, response, body) {
    if (response.statusCode == 200) {
      var data = JSON.parse(body);
      var access_token = data.access_token;
      var openid = data.openid;
      // 第三步:用access_token和openid获取用户信息
      request.get({  
        url: 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN',
      }, function (error, response, body) {
        if (response.statusCode == 200) {
          // 第四步:根据获取的用户信息进行对应操作
          var userinfo = JSON.parse(body); 
          console.log('获取微信信息成功!');
          res.send({
            name: userinfo.nickname, // 用户微信昵称
            result: true
          });
        } else {
          console.log('获取微信信息失败!', response.statusCode);
          res.send({
            name: '',
            result: false
          })
        }
      });
    } else {
      console.log('获取微信信息失败!', response.statusCode);
      res.send({
        name: '',
        result: false
      })
    }
  })
});


app.listen(port, (error) => {
  if (error) {
    console.error(error);
  } else {
    console.info('==> Listening on port %s. Open up http://localhost:%s/ in your browser.', port, port);
  }
});

 

3.前端开发工作

前端要做的工作十分简单,只有两步。

① 没有微信用户信息则请求后台接口【/wechat_login】申请微信授权,有则继续使用本地存储的信息,不再重复授权。

② 请求后台接口【/user】获取微信用户信息,将信息进行本地存储。

 

特别注意,为了避免频繁地授权,当第一次获取微信用户信息成功时,记得将信息存储起来【localStorage/cookie/sessionStorage均可】。先判断是否有信息,有则无需申请授权,没有再去申请授权。

 

如果网页需要兼容非微信内打开的情况,记得先判断是否微信打开,再申请微信授权

 

/** 获取当前网页url的参数 */
function getQueryStringArgs() {
  var qs = (location.search.length > 0 ? location.search.substring(1) : "");
  var args = {};
  var items = qs.length ? qs.split("&") : [];
  var item = null;
  var name = null;
  var value = null;
  len = items.length;
  for (var i = 0; i < len; i++) {
    item = items[i].split("=");
    name = decodeURIComponent(item[0]);
    value = decodeURIComponent(item[1]);
    if (name.length) {
      args[name] = value;
    }
  }
  return args;
}
const args = getQueryStringArgs();


/** 微信授权 */
function loginWechat() {
  if (args['code']) { // 已经授权并回调成功
    let wechatCode = args['code'];
    $.get('/user?code=' + wechatCode, function (res) {
      if (res.result) {
        $('#res-name').text(res.name);
        localStorage.name = res.name;
      } else {
        if (localStorage.name) {
          $('#res-name').text(localStorage.name);
        }
      }
    })
  } else {
    if (localStorage.name) {
      $('#res-name').text(localStorage.name);
    } else {
      location.href = 'http://www.chunling.online/wechat_login'; // 申请微信授权
    }
  }
}


/** 判断网页是否是微信内打开,是则申请微信授权 */
var wx = (function () {
  return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1
})();
if (wx) {
  console.log('微信内打开');
  loginWechat();  // 申请微信授权
} else {
  console.log('非微信内打开');
}

 

4.调试工作

因为微信授权需要配置回调域名,当我们使用localhost本机调试时,是没办法申请授权的,会返回 redirect_uri 错误的信息。为方便本机测试,需要将域名映射成我们的本机ip地址

打开 C:\Windows\System32\drivers\etc\hosts中的hosts文件,增加一行记录,如下

【微信开发】NodeJS解决微信网页授权获取用户信息_第1张图片

此时,再用微信开发者工具开发 www.chunling.online ,就可以访问我们的 localhost:80 项目,微信授权回调域名的问题也解决了。

 

你可能感兴趣的:(JavaScript,nodeJS)