网页获取用户授权信息
最后更新于:2022-04-01 20:00:34
思路是这样的,第一步在页面获取到授权以后的code
拿code去nodejs后台的httpserver请求
nodejs接到请求以后,拿到code去拿accessToken,然后通过accessToken获取用户信息
然后把用户信息扔给页面
后台nodejs代码:
~~~
var request = require('request');
var nodeconfig = require('./nodeconfig');
//api weixin
function wx(res, postData) {
console.log(getUrlVars(postData));
//微信获取用户资料第二步通过code换取网页授权access_token
request.get({
url : 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx01ca1966fe6f8a88&secret=c893b05b38&'+postData+'&grant_type=authorization_code',
form : {}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
var jsondata = JSON.parse(body);
//第四步拉取用户信息(需scope为 snsapi_userinfo)
request.get({
url : 'https://api.weixin.qq.com/sns/userinfo?access_token=' + jsondata.access_token + '&openid=' + jsondata.openid + '&lang=zh_CN',
form : {}
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
var userdata = JSON.parse(body);
console.log(userdata);
nodeconfig.httpHeadSetting(res);
res.end(JSON.stringify(userdata));
}
});
}
});
}
exports.wx = wx;
~~~
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-03-28_56f8eb8b759c9.jpg)
';