vue公众号 h5网页页面 实现微信授权登录
写这篇博客是为了给入手公众号的小伙伴避免一些坑,我后台和我一样刚没做过这个功能,我两搜索了很多博客,过程七上八下,其实不难,不说了直接上代码(可直接复制)。
一.公众号h5的网页授权先后台配置好公众号的设置
二.h5网页授权最重要的就是回调地址,这个地址就是你授权后要回到的页面记得一定要后端配置上不然就不行
三.前端逻辑是1.页面回调,2.获取code,3.截取code,4.后台交互code,appid是自己公众号的appid记得修改,local一般不要改,直接encodeURIComponent解析。
//拿到微信code
async toWx() {
// 授权回调
let local = window.location.href.split("#")[0];
let url =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5e173bc64f0b0888&redirect_uri=" +
encodeURIComponent(local) +
"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
console.log("window.location.href", window.location.href);
let code = this.GetParam(window.location.href.split("#")[0], "code");
if (!code) {
window.location.href = url;
// console.log("code", code);
} else {
this.code = this.GetParam(window.location.href, "code");
console.log("code", code);
}
},
// 截取code
GetParam(url, code) {
url = url + "";
let regstr = "/(\\?|\\&)" + code + "=([^\\&]+)/";
let reg = eval(regstr);
//eval可以将 regstr字符串转换为 正则表达式
let result = url.match(reg);
if (result && result[2]) {
return result[2];
}
},
},
这是我刚开始写博客,写的不好多多见谅,有问题都可以直接扣我或留言