-
Notifications
You must be signed in to change notification settings - Fork 0
/
wechat_oauth.js
97 lines (87 loc) · 2.51 KB
/
wechat_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
// https://github.com/node-weixin/node-weixin-oauth
import utils from './wechat_util.js'
const {app, work, web} = Meteor.settings.private.wechat
WechatOAuth = {}
var userAgent = 'Meteor'
if (Meteor.release)
userAgent += '/' + Meteor.release
WechatOAuth.createMobileURL = function (redirectUri, state, scope, type) {
type = 0
var oauthUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize'
var params = {
appid: app.id,
redirect_uri: redirectUri,
// Only on type currently
response_type: ['code'][type],
scope: ['snsapi_base', 'snsapi_userinfo'][scope],
state: state
}
return oauthUrl + '?' + utils.toParam(params) + '#wechat_redirect'
}
WechatOAuth.createWebURL = function (redirectUri, state) {
type = 0
var oauthUrl = 'https://open.weixin.qq.com/connect/qrconnect'
var params = {
appid: web.id,
redirect_uri: redirectUri,
response_type: 'code',
scope: 'snsapi_login',
state: state
}
return oauthUrl + '?' + utils.toParam(params) + '#wechat_redirect'
}
WechatOAuth.getMobileToken = function (query) {
return WechatOAuth.getTokenResponse(app, query)
}
WechatOAuth.getTokenResponse = function (app, query) {
var response
try {
response = HTTP.post('https://api.weixin.qq.com/sns/oauth2/access_token', {
headers: {
Accept: 'application/json',
'User-Agent': userAgent
},
params: {
code: query.code,
appid: app.id,
secret: app.secret,
grant_type: 'authorization_code'
}
})
} catch (err) {
throw _.extend(new Error('Failed to complete OAuth handshake with Wechat. ' + err.message), {
response: err.response
})
}
response = JSON.parse(response.content)
if (response.errcode) {
throw new Error('Failed to complete OAuth handshake with Wechat. ' + response.errmsg)
} else {
return response
}
}
WechatOAuth.getUserInfo = function (access_token, openid) {
var response
try {
response = HTTP.get('https://api.weixin.qq.com/sns/userinfo', {
headers: {
Accept: 'application/json',
'User-Agent': userAgent
},
params: {
access_token: access_token,
openid: openid
}
})
} catch (err) {
throw _.extend(new Error('Failed to complete OAuth handshake with Wechat. ' + err.message), {
response: err.response
})
}
response = JSON.parse(response.content)
if (response.errcode) {
throw new Error('Failed to complete OAuth handshake with Wechat. ' + response.errmsg)
} else {
return response
}
}