前端部分使用的是vue框架
后端部分使用的是node中的express脚手架
第一步:用户同意授权,获取code
通过node重定向到微信授权页面,当用户点击确认登录以后,会回调到redirct——url中,并返回code码
第二步:通过code换取网页授权access_token
获取code后,请求以下链接获取access_token: https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
在vue 中检查用户是否授权
checkUserAuth检查用户是否授权
checkUserAuth(){
//在cookie中检查是否有openid
let openId = this.$cookie.get('openId');
if(!openId){
//如果没有的话就进行授权
window.location.href = API.wechatRedirect;
}else{
// this.getWechatConfig();
}
}
API.wechatRedirect为重定向地址
/api/wechat/redirect?url=url&scope=snsapi_userinfo’,
url为授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理,
scope为应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, 即使在未关注的情况下,只要用户授权,也能获取其信息 )
这里注意要进行proxy代理
express默认端口为3000,要将自己的本地请求地址代理到 target:‘http://localhost:3000’,
授权是在node的express脚手架上进行的,前端只需要调用接口
app.js为项目入口
//引入js文件
var wx = require('./routes/wx');
//一级路由
app.use('/api/wechat', wx);
./routes/wx.js在wx.js中定义二级路由
//用户授权重定向
router.get('/redirect',function(req,res){
// /api/wechat/redirect?url=url&scope=snsapi_userinfo'里面的参数
//获取到openId之后的重定向地址
let redirectUrl = req.query.url,
//动态获取scope,也可以写死昂
scope = req.query.scope,
//获取openId的地址
callback = '自己的域名/api/wechat/getOpenId';
//缓存
cache.put('redirectUrl',redirectUrl);
let authorizeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${callback}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`
//重定向方法,进行跳转
res.redirect(authorizeUrl);
})
//获取openId
//req.query--get请求
//req.body--post请求
router.get('/getOpenId',function(req,res){
//拿到code码
let code = req.query.code;
console.log("code:"+code);
let token_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appId}&secret=${appsecret}&code=${code}&grant_type=authorization_code`
//code为空
if(!code){
res.json({
code:1001,
data:'',
message:'当前未获取到授权code码'
})
}else{
//err接口是否报错,response响应,body返回值
//response.statusCode请求状态码
request.get(token_url,function(err,response,body){
if(!err && response.statusCode == '200'){
let data = JSON.parse(body);
console.log("body:"+data);
//一分钟过去
let expire_time = 1000*60*1;
res.cookie('openId',data.openid,{maxAge:expire_time});
let redirectUrl = cache.get('redirectUrl')
//重定向到前端
res.redirect(redirectUrl)
}
})
}
第三步:拉取用户信息(需scope为 snsapi_userinfo)
如果网页授权作用域为snsapi_userinfo,则此时开发者可以通过access_token和openid拉取用户信息了。
请求方法