流程
点击查看微信登陆官方文档: 微信登陆官方文档
二维码生成
一、在页面中先引入如下JS文件(支持https)
head:{
script:[
{src:"http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"}
]
},
二、在需要使用微信登录的地方实例以下JS对象
可以当页面初始化完成时,生成该对象,注意需要首先在页面部分添加一个
标签来生成二维码
<div id="weixin"></div>
mounted(){
var obj = new WxLogin({
self_redirect:false, //页面跳转方式 true:在二维码位置跳转 false:全局跳转
id:"weixin", //当前二维码出现的位置(id)
appid: "wx3bdb1192c22883f3",
scope: "snsapi_login",
redirect_uri: "http://note.java.itcast.cn/weixinlogin", //手机扫码后页面跳转的url地址(跳转到注册web应用绑定的域名下)
});
},
配置本地host和请求端口
一、为了方便测试,在host文件中将跳转的页面改为127.0.0.1
二、nuxt工程的请求端口改为80
修改package.json文件
"config":{
"nuxt":{
"port":80
}
},
此时可以根据域名进入到项目中。
获取用户信息
当进行到此步时,已经进行了扫码确认操作,此时页面的url为
http://note.java.itcast.cn/weixinlogin?code=061Rr6Ha1w1FEz0aUGGa1b15Ts1Rr6Hk&state=undefined
这时,就已经获取了code,然后我们需要通过code
获取access_token
和openid
,获取完成之后,根据access_token
和openid
获取用户信息即可。
注意:获取的用户信息主要是name,avatar和token三个属性,获取完后存储到cookie中,跳转首页。
export default {
asyncData(context){
//context.params 获取所有地址参数
//context.query 获取所有请求参数
let code = context.query.code
console.log(code)
let access_token_url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
return axios.get(access_token_url).then(res => {
let openid = res.data.openid;
let access_token = res.data.access_token;
let openid_url = `https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}`
return axios.get(openid_url).then(res2 => {
return {
user:{
name:res2.data.nickname,
avatar:res2.data.headimgurl,
token:access_token
}
}
})
})
},
mounted(){
if(this.user!=undefined && this.user != null){
auth.setUser(this.user)
location.href="/"
}
}
}
微信登陆完成