helper.js 1.46 KB
/**
 * Created by Tommy Huang on 18/03/21.
 */

const config = require('config-lite')({
  config_basedir: __dirname,
  config_dir: 'config'
})
const axios = require('axios')

/**
 * 获取用户微信 Token
 * @param {string} code 微信返回的用户 code
 */
exports.getUserWxAccessTokenInfo = async function(code) {
  const {data} = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.wx.appId}&secret=${config.wx.appSecret}&code=${code}&grant_type=authorization_code`)
  if (data.access_token && data.refresh_token && data.openid) {
    return data
  } else {
    return false
  }
}

/**
 * 刷新用户的 Token
 * @param {string} refreshToken 微信返回的用户 refresh_token
 */
exports.refreshUserWxToken = async function(refreshToken) {
  const {data} = await axios.get(`https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=${config.wx.appId}&grant_type=refresh_token&refresh_token=${refreshToken}`)
  if (data.access_token && data.refresh_token && data.openid) {
    return data
  } else {
    return false
  }
}
/**
 * 拉取用户信息
 * @param {string} token 微信返回的用户 access_token
 * @param {string} openId 微信返回的用户 openid
 */
exports.getUserWxInfo = async function(token, openId) {
  const {data} = await axios.get(`https://api.weixin.qq.com/sns/userinfo?access_token=${token}&openid=${openId}&lang=zh_CN`)
  if (data.openid && data.nickname && data.headimgurl) {
    return data
  } else {
    return false
  }
}