-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathoauth.js
378 lines (359 loc) · 9.58 KB
/
oauth.js
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
'use strict';
var urllib = require('urllib');
var wrapper = require('./util').wrapper;
var extend = require('util')._extend;
var querystring = require('querystring');
var AccessToken = function (data) {
if (!(this instanceof AccessToken)) {
return new AccessToken(data);
}
this.data = data;
};
/*!
* 检查AccessToken是否有效,检查规则为当前时间和过期时间进行对比
*
* Examples:
* ```
* token.isValid();
* ```
*/
AccessToken.prototype.isValid = function () {
return !!this.data.access_token && (new Date().getTime()) < (this.data.create_at + this.data.expires_in * 1000);
};
/*!
* 处理token,更新过期时间
*/
var processToken = function (that, callback) {
return function (err, data, res) {
if (err) {
return callback(err, data);
}
data.create_at = new Date().getTime();
// 存储token
that.saveToken(data.openid, data, function (err) {
callback(err, new AccessToken(data));
});
};
};
/**
* 根据appid和appsecret创建OAuth接口的构造函数
* 如需跨进程跨机器进行操作,access token需要进行全局维护
* 使用使用token的优先级是:
*
* 1. 使用当前缓存的token对象
* 2. 调用开发传入的获取token的异步方法,获得token之后使用(并缓存它)。
* Examples:
* ```
* var OAuth = require('wechat-oauth');
* var api = new OAuth('appid', 'secret');
* ```
* @param {String} appid 在公众平台上申请得到的appid
* @param {String} appsecret 在公众平台上申请得到的app secret
* @param {Function} getToken 用于获取token的方法
* @param {Function} saveToken 用于保存token的方法
*/
var OAuth = function (appid, appsecret, getToken, saveToken) {
this.appid = appid;
this.appsecret = appsecret;
// token的获取和存储
this.store = {};
this.getToken = getToken || function (openid, callback) {
callback(null, this.store[openid]);
};
if (!saveToken && process.env.NODE_ENV === 'production') {
console.warn("Please dont save oauth token into memory under production");
}
this.saveToken = saveToken || function (openid, token, callback) {
this.store[openid] = token;
callback(null);
};
this.defaults = {};
};
/**
* 用于设置urllib的默认options
*
* Examples:
* ```
* oauth.setOpts({timeout: 15000});
* ```
* @param {Object} opts 默认选项
*/
OAuth.prototype.setOpts = function (opts) {
this.defaults = opts;
};
/*!
* urllib的封装
*
* @param {String} url 路径
* @param {Object} opts urllib选项
* @param {Function} callback 回调函数
*/
OAuth.prototype.request = function (url, opts, callback) {
var options = {};
extend(options, this.defaults);
if (typeof opts === 'function') {
callback = opts;
opts = {};
}
for (var key in opts) {
if (key !== 'headers') {
options[key] = opts[key];
} else {
if (opts.headers) {
options.headers = options.headers || {};
extend(options.headers, opts.headers);
}
}
}
urllib.request(url, options, callback);
};
/**
* 获取授权页面的URL地址
* @param {String} redirect 授权后要跳转的地址
* @param {String} state 开发者可提供的数据
* @param {String} scope 作用范围,值为snsapi_userinfo和snsapi_base,前者用于弹出,后者用于跳转
*/
OAuth.prototype.getAuthorizeURL = function (redirect, state, scope) {
var url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
var info = {
appid: this.appid,
redirect_uri: redirect,
response_type: 'code',
scope: scope || 'snsapi_base',
state: state || ''
};
return url + '?' + querystring.stringify(info) + '#wechat_redirect';
};
/**
* 获取授权页面的URL地址
* @param {String} redirect 授权后要跳转的地址
* @param {String} state 开发者可提供的数据
* @param {String} scope 作用范围,值为snsapi_login,前者用于弹出,后者用于跳转
*/
OAuth.prototype.getAuthorizeURLForWebsite = function (redirect, state, scope) {
var url = 'https://open.weixin.qq.com/connect/qrconnect';
var info = {
appid: this.appid,
redirect_uri: redirect,
response_type: 'code',
scope: scope || 'snsapi_login',
state: state || ''
};
return url + '?' + querystring.stringify(info) + '#wechat_redirect';
};
/**
* 根据授权获取到的code,换取access token和openid
* 获取openid之后,可以调用`wechat.API`来获取更多信息
* Examples:
* ```
* api.getAccessToken(code, callback);
* ```
* Callback:
*
* - `err`, 获取access token出现异常时的异常对象
* - `result`, 成功时得到的响应结果
*
* Result:
* ```
* {
* data: {
* "access_token": "ACCESS_TOKEN",
* "expires_in": 7200,
* "refresh_token": "REFRESH_TOKEN",
* "openid": "OPENID",
* "scope": "SCOPE"
* }
* }
* ```
* @param {String} code 授权获取到的code
* @param {Function} callback 回调函数
*/
OAuth.prototype.getAccessToken = function (code, callback) {
var url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
var info = {
appid: this.appid,
secret: this.appsecret,
code: code,
grant_type: 'authorization_code'
};
var args = {
data: info,
dataType: 'json'
};
this.request(url, args, wrapper(processToken(this, callback)));
};
/**
* 根据refresh token,刷新access token,调用getAccessToken后才有效
* Examples:
* ```
* api.refreshAccessToken(refreshToken, callback);
* ```
* Callback:
*
* - `err`, 刷新access token出现异常时的异常对象
* - `result`, 成功时得到的响应结果
*
* Result:
* ```
* {
* data: {
* "access_token": "ACCESS_TOKEN",
* "expires_in": 7200,
* "refresh_token": "REFRESH_TOKEN",
* "openid": "OPENID",
* "scope": "SCOPE"
* }
* }
* ```
* @param {String} refreshToken refreshToken
* @param {Function} callback 回调函数
*/
OAuth.prototype.refreshAccessToken = function (refreshToken, callback) {
var url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token';
var info = {
appid: this.appid,
grant_type: 'refresh_token',
refresh_token: refreshToken
};
var args = {
data: info,
dataType: 'json'
};
this.request(url, args, wrapper(processToken(this, callback)));
};
OAuth.prototype._getUser = function (options, accessToken, callback) {
var url = 'https://api.weixin.qq.com/sns/userinfo';
var info = {
access_token: accessToken,
openid: options.openid,
lang: options.lang || 'en'
};
var args = {
data: info,
dataType: 'json'
};
this.request(url, args, wrapper(callback));
};
/**
* 根据openid,获取用户信息。
* 当access token无效时,自动通过refresh token获取新的access token。然后再获取用户信息
* Examples:
* ```
* api.getUser(options, callback);
* ```
*
* Options:
* ```
* openId
* // 或
* {
* "openid": "the open Id", // 必须
* "lang": "the lang code" // zh_CN 简体,zh_TW 繁体,en 英语
* }
* ```
* Callback:
*
* - `err`, 获取用户信息出现异常时的异常对象
* - `result`, 成功时得到的响应结果
*
* Result:
* ```
* {
* "openid": "OPENID",
* "nickname": "NICKNAME",
* "sex": "1",
* "province": "PROVINCE"
* "city": "CITY",
* "country": "COUNTRY",
* "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
* "privilege": [
* "PRIVILEGE1"
* "PRIVILEGE2"
* ]
* }
* ```
* @param {Object|String} options 传入openid或者参见Options
* @param {Function} callback 回调函数
*/
OAuth.prototype.getUser = function (options, callback) {
if (typeof options !== 'object') {
options = {
openid: options
};
}
var that = this;
this.getToken(options.openid, function (err, data) {
if (err) {
return callback(err);
}
// 没有token数据
if (!data) {
var error = new Error('No token for ' + options.openid + ', please authorize first.');
error.name = 'NoOAuthTokenError';
return callback(error);
}
var token = new AccessToken(data);
if (token.isValid()) {
that._getUser(options, token.data.access_token, callback);
} else {
that.refreshAccessToken(token.data.refresh_token, function (err, token) {
if (err) {
return callback(err);
}
that._getUser(options, token.data.access_token, callback);
});
}
});
};
OAuth.prototype._verifyToken = function (openid, accessToken, callback) {
var url = 'https://api.weixin.qq.com/sns/auth';
var info = {
access_token: accessToken,
openid: openid
};
var args = {
data: info,
dataType: 'json'
};
this.request(url, args, wrapper(callback));
};
/**
* 根据code,获取用户信息。
* Examples:
* ```
* api.getUserByCode(code, callback);
* ```
* Callback:
*
* - `err`, 获取用户信息出现异常时的异常对象
* - `result`, 成功时得到的响应结果
*
* Result:
* ```
* {
* "openid": "OPENID",
* "nickname": "NICKNAME",
* "sex": "1",
* "province": "PROVINCE"
* "city": "CITY",
* "country": "COUNTRY",
* "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46",
* "privilege": [
* "PRIVILEGE1"
* "PRIVILEGE2"
* ]
* }
* ```
* @param {String} code 授权获取到的code
* @param {Function} callback 回调函数
*/
OAuth.prototype.getUserByCode = function (code, callback) {
var that = this;
this.getAccessToken(code, function (err, result) {
if (err&&err!='ok') {
return callback(err);
}
that.getUser(result.data.openid, callback);
});
};
module.exports = OAuth;