-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth.js
104 lines (71 loc) · 3.28 KB
/
auth.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
let https = require('https');
class Auth {
constructor(appId, appSecret) {
this.appId = appId;
this.appSecret = appSecret;
}
// oauth 授权跳转接口
// @param string url
// @param string scope
// @return string
getOauthRedirect(url, scope, state = "") {
return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appId}&redirect_uri=${url}&response_type=code&scope=${scope}#wechat_redirect`;
}
// 通过code获取AccessToken(注意:这里是网页授权access_token,不是基础支持中的access_token)
// @param string code
// @return json {access_token,expires_in,refresh_token,openid,scope}
getOauthAccessToken(code) {
return new Promise((resolve, reject) => {
let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.appId}&secret=${this.appSecret}&code=${code}&grant_type=authorization_code`;
//向微信服务器发送请求
https.get(url, function (res) {
res.setEncoding('utf8');
res.on('data', function (data) {
if (data) {
data = JSON.parse(data);
//如果微信返回错误
if (data.errcode) {
return reject(new Error(data.errmsg));
}
//成功后返回data
return resolve(data);
} else {
return reject(new Error("getOauthAccessToken 请求返回数据为空"));
}
});
}).on("error", function (err) {
return resolve(err);
});
})
}
// 获取授权后的用户资料(注意:这里是网页授权access_token,不是基础支持中的access_token)
// @param string access_token
// @param string openid
// @return json {openid,nickname,sex,province,city,country,headimgurl,privilege,[unionid]}
// 注意:unionid字段 只有在用户将公众号绑定到微信开放平台账号后,才会出现。
getOauthUserinfo(access_token, openid) {
return new Promise((resolve, reject) => {
let url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`;
//向微信服务器发送请求
https.get(url, function (res) {
res.setEncoding('utf8');
res.on('data', function (data) {
if (data) {
data = JSON.parse(data);
//如果微信返回错误
if (data.errcode) {
return reject(new Error(data.errmsg));
}
//成功后返回access_token
return resolve(data);
} else {
return reject(new Error("getOauthAccessToken 请求返回数据为空"));
}
});
}).on("error", function (err) {
return resolve(err);
});
})
}
}
module.exports = Auth;