静默授权-前端篇
注:本代码基于vue
一、获取code
1.存入当前地址,用于回调
let baseUrl = window.location.href;
// 存入当前地址,需在getCode方法前调用,建议放在created里获取
2.getCode的方法
getCode() {
const code = this.$route.query.code; // 截取路径中的code,如果没有就去微信授权,如果已经获取到了就直接传code给后台获取openId
if (code == null || code === "") {
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid='+ APPID +'&redirect_uri=" +
this.baseUrl +
"&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
// baseUrl则为网站最初地址,用于回调回去
// APPID则为公众号的appid
// snsapi_base则为静默授权 snsapi_userinfo则为非静默授权
} else {
this.getOpenId(code); //把code传给后台获取用户信息
}
}
二、通过code向后台的接口获取openid
getOpenId(code) {
// 通过code获取 openId等用户信息,/api/user/wechat/login 为后台接口
let _this = this;
axios({
url: "后台接口",
data: {
code: code
}
}).then(res => {
if (res.code == 200) {
获取openid
}
});
},
如此便实现了数据保密