代码如下:
1 var express = require(‘express‘); 2 var cookieParser = require(‘cookie-parser‘); 3 var bodyParser = require(‘body-parser‘); 4 var OAuth = require(‘wechat-oauth‘); 5 var request = require(‘request‘); 6 var app = express(); 7 app.use(bodyParser.json()); 8 app.use(bodyParser.urlencoded({ extended: false })); 9 app.use(cookieParser()); 10 var port = 18080; 11 var appid = ‘wx75340481908402a8‘; 12 var appsecret = ‘2b6ee0cbeec0114eb539e68ba356329b‘; 13 14 //首先拼接url 15 var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx75340481908402a8&redirect_uri=http%3a%2f%2fwechatapp1.duapp.com%2fcallback&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect" 16 app.get(‘/‘,function(req,res){ 17 res.redirect(url); 18 }); 19 //四步请求打法; 20 //第一步:获得code; 21 app.get(‘/callback‘,function(req,res){ 22 var code = req.query.code; 23 var url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=‘ + appid + ‘&secret=‘ + appsecret + ‘&code=‘ + code + ‘&grant_type=authorization_code‘; 24 //第二步:获得token 25 request.get(url,function(err,response,body) { 26 var json = JSON.parse(body); 27 var refreshUrl = ‘https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=‘ + appid + ‘&grant_type=refresh_token&refresh_token=‘ + json.refresh_token; 28 //第三步:获得refreshtoken和openId; 29 request.get(refreshUrl,function (err,response,refresh) { 30 var json = JSON.parse(refresh); 31 var infoUrl = ‘https://api.weixin.qq.com/sns/userinfo?access_token=‘ + json.access_token + ‘&openid=‘ + json.openid + ‘&lang=zh_CN‘; 32 //第四步:通过上一步刷新得来的refresh和openId请求用户信息; 33 request.get(infoUrl,function(err,response,info) { 34 var info = JSON.parse(info); 35 res.send(info); 36 }); 37 }); 38 }); 39 }); 40 41 app.listen(port); 微信授权登录页面的设置;分两步第一步拼接url,之后设置一个路由a,当用户点击路由a时,使用户跳转到拼接的路由;第二步,拼接的url里面会有一个回调路由,此路由回调回来时是带着参数的;通过里面的参数通过四步请求法,可以获得用户的信息; 用户信息分两种;一种是关注公众号的;一种是没有;关注公众号的会得到用户的全部信息,没有关注的只得到openid;两种信息里面都有一个相同字段;subscrib其值为0时没有关注,为1时关注;
时间: 2024-10-06 17:16:46