vue微信网页授权
vue微信授权登陆
·
vue微信微信网页授权
vue代码
router.beforeEach((to, from, next) => {
let locationUrl = window.location.href;
let openid = window.localStorage.getItem("openid"); // 从内存取得openid
if (!openid) { // 内存内没有openid
// 检测是否参数内有code,若有则跳接口获取openid,若没有则跳授权页
if (locationUrl.indexOf("code") >= 0) { // 链接里有code
axios.get(" ****** url ****** ", { params: {
code: getval(locationUrl, 'code'),
state: getval(locationUrl, 'state')
}}).then((res) => {
if (res.data.rel) {
window.localStorage.setItem("openid", res.data.result.openid);
window.localStorage.setItem("nickname", res.data.result.nickName);
window.localStorage.setItem("userheadimg", res.data.result.userHeadimg);
window.localStorage.setItem("amount", res.data.result.amount);
// 存入vuex相关登陆信息
store.commit('setUserMsg', res.data.result);
store.commit('setOpenId', res.data.result.openid);
} else {
console.log('登陆失败' + res.data.msg);
}
}).catch((err) => {
console.error('登陆失败' + err);
})
} else { // 链接里没有code
let redirectHref = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='
+ appid
+ '&redirect_uri='
+ encodeURIComponent(locationUrl)
+ '&response_type=code&scope=snsapi_userinfo&state='
+ state
+'#wechat_redirect';
window.location.href = redirectHref; // 跳转微信链接获取code和state(state没啥用目前暂时)
}
} else { // 内存里有openid
let member = {};
member.nickName = window.localStorage.getItem("nickName");
member.userHeadimg = window.localStorage.getItem("userHeadimg");
member.amount = window.localStorage.getItem("amount");
store.commit('setUserMsg', member);
}
}
//从url中获取参数值
function getval(url, name) {
var reg = new RegExp("(^|\\?|&)"+ name +"=([^&|#]*)(\\s|&|#|$)", "i"); // 因为vue有添加“#”的特点,所以这里的正则表达式会匹配 & -- &/#
if (reg.test(url)) return unescape(RegExp.$2.replace(/\+/g, " "));
return "";
};
URL
这里的url必须是全面encode的状态:encodeURIComponent(currentPageUrl)
,不需要像微信JSSDK一样location.split('#')[0]
流程图
visio下载太慢了,手绘了一张,凑合看吧:
手绘什么的太恶心了,补上一张processon大赞的流程图在线制作网站生成的:
更多推荐
已为社区贡献2条内容
所有评论(0)