1.第一步 首先判断是否有code
![9e68a279866154766f83ff9ef740e5b7.png](https://i-blog.csdnimg.cn/blog_migrate/ebab9c0ad1abfab82543fee2ae99ee03.jpeg)
var ua = window.navigator.userAgent.toLowerCase();// ua.indexOf('micromessenger')为真-微信端,如果为假,就是其他浏览器if (ua.indexOf('micromessenger') > -1) {// 判断有没有code 没有就获取codeif (!this.parse_url(window.location.href).code) {var appid = "****"; // 填写你公众号的appidvar redirect_uri = encodeURIComponent(window.location.href);// 获取codewindow.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
} else {// 如果有code就请求数据获取tokenvar url = window.location.href;var params = this.parse_url(url);
axios({method: 'post',url: '****', // 请求后端协助 写接口返回token给你data:{code: params.code
}
})
.then((res)=>{console.log(res.data.model)// 获取tokenthis.getuserInfo(res.data.model.access_token)
})
}
parse_url(url) { //定义函数var pattern = /(w+)=(w+)/ig; //定义正则表达式var parames = {}; //定义数组
url.replace(pattern, function (a, b, c) {
parames[b] = c;
});return parames; //返回这个数组.
},
2.拿到token去获取信息
![bf80b81c50680ab9a2456e663cb7e24a.png](https://i-blog.csdnimg.cn/blog_migrate/313161c2a863103e4efa87e1a294f134.jpeg)
axios({method: 'post',url: '******', // 接口找后端写data:{accessToken: token, (获取的token)openid: '*****'
}
})
.then((res)=>{localStorage.setItem('nickname',res.data.model.nickname)localStorage.setItem('headimgurl',res.data.model.headimgurl)localStorage.setItem('openid',res.data.model.unionid)
})
3.进入你的公众号设置/功能设置/网页域名授权
设置你的域名