index.js 1.9 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
const {
  callWxOpenApi,
  buildUrl
} = require('../normalize')

module.exports = class Auth {
  constructor (options) {
    this.options = Object.assign({
      baseUrl: 'https://api.weixin.qq.com',
      timeout: 5000
    }, options)
  }

  async _requestWxOpenapi ({ name, url, data, options }) {
    const defaultOptions = {
      method: 'GET',
      dataType: 'json',
      dataAsQueryString: true,
      timeout: this.options.timeout
    }
    const result = await callWxOpenApi({
      name: `auth.${name}`,
      url: `${this.options.baseUrl}${buildUrl(url, data)}`,
      data,
      options,
      defaultOptions
    })
    return result
  }

  async code2Session (code) {
    const url = '/sns/jscode2session'
    const result = await this._requestWxOpenapi({
      name: 'code2Session',
      url,
      data: {
        grant_type: 'authorization_code',
        appid: this.options.appId,
        secret: this.options.secret,
        js_code: code
      }
    })
    return result
  }

  async getOauthAccessToken (code) {
    const url = '/sns/oauth2/access_token'
    const result = await this._requestWxOpenapi({
      name: 'getOauthAccessToken',
      url,
      data: {
        grant_type: 'authorization_code',
        appid: this.options.appId,
        secret: this.options.secret,
        code
      }
    })
    if (result.expiresIn) {
雪洛's avatar
雪洛 已提交
59
      result.expired = Date.now() + result.expiresIn * 1000
DCloud_JSON's avatar
DCloud_JSON 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
      // delete result.expiresIn
    }
    return result
  }

  async getUserInfo ({
    accessToken,
    openid
  } = {}) {
    const url = '/sns/userinfo'
    const {
      nickname,
      headimgurl: avatar
    } = await this._requestWxOpenapi({
      name: 'getUserInfo',
      url,
      data: {
        accessToken,
        openid,
        appid: this.options.appId,
        secret: this.options.secret,
        scope: 'snsapi_userinfo'
      }
    })
    return {
      nickname,
      avatar
    }
  }
}