微信云函数获取access_token

// 云函数入口文件
const cloud = require('wx-server-sdk')
const requestpromise = require('request-promise');

cloud.init()

async function getAccessToken(wxContext,add) {
    const options = {
      method: 'GET',
      url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+wxContext.APPID + '&secret=小程序appsecret',
    };
    let db = cloud.database({})
    const result = await requestpromise(options);
    let resultJson = JSON.parse(result)
    if (resultJson.access_token) {
      let data = {
        accessToken: resultJson.access_token,
        expiresIn: resultJson.expires_in,
        createTime: Date.now(),
        appID:wxContext.APPID,
      }
      // expires_in
      if (add) {
        await db.collection('accessToken').add({
          // data 字段表示需新增的 JSON 数据
          data: data,
          success: function (res) {
            // res 是一个对象,其中有 _id 字段标记刚创建的记录的 id
            console.log(res)
          }
        })
      } else {
        await db.collection('accessToken').where({
          appID:wxContext.APPID
        }).update({
          data:data
        })
      }
      return {
        code:'0',
        message:'获取access_token成功',
        result:resultJson,
      }
    } else {
      return {
        code:'-1',
        message:'获取access_token失败'
      }
    }
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  //先从云函数数据库中获取accessToken
  let db = cloud.database({})
  const result = await db.collection('accessToken').where({
    appID:wxContext.APPID
  }).get()
  if ( typeof result.data == 'object' && result.data.length) {
    let info = result.data[0]
    let {
      accessToken,
      expiresIn,
      createTime
    } = info
    let timestamp = Date.now()
    if (timestamp - createTime < expiresIn*1000) {
      return {
        code:'0',
        message:'获取access_token成功',
        access_token:accessToken,
      }
    } else {
      //超时重新获取
      let result = await getAccessToken(wxContext,false)
      if (0 == result.code) {
        return {
          code:'0',
          message:'获取access_token成功',
          access_token:result.result.access_token,
        }
      } else {
        return {
          code:'-1',
          message:'获取access_token失败'
        }
      }
    }
  } else {
    let result = await getAccessToken(wxContext,true)
    if (0 == result.code) {
      return {
        code:'0',
        message:'获取access_token成功',
        access_token:result.result.access_token,
      }
    } else {
      return {
        code:'-1',
        message:'获取access_token失败'
      }
    }
    
  }
}

你可能感兴趣的:(微信云函数获取access_token)