zhaoxing
2023-05-11 ac65fb87fa3f2e0cd551019cd6cb8de753eebce8
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
59
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
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) {
      result.expired = Date.now() + result.expiresIn * 1000
      // 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
    }
  }
 
  async getPhoneNumber (accessToken, code) {
    const url = `/wxa/business/getuserphonenumber?access_token=${accessToken}`
    const { phoneInfo } = await this._requestWxOpenapi({
      name: 'getPhoneNumber',
      url,
      data: {
        code
      },
      options: {
        method: 'POST',
        dataAsQueryString: false,
        headers: {
          'content-type': 'application/json'
        }
      }
    })
 
    return {
      purePhoneNumber: phoneInfo.purePhoneNumber
    }
  }
}