1、判断是否微信浏览器
// 判断是否为公众号模拟器环境
const isWechat = () => {
return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
2、访问特定微信链接来获取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
3、截取code方法
getUrlCode() {
// 截取url中的code方法
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
console.log(theRequest);
return theRequest;
},
4、上demo
// 判断是否为微信环境
const isWechat = () => {
return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}
export default {
data() {
return {
code: ''
}
},
onLoad() {
this.getWechatCode()
},
methods: {
getWechatCode() {
if (isWechat) {
let appid = "公众号后台获取的APPID"; //微信APPid
let code = this.getUrlCode().code; //是否存在code
let local = window.location.href;
if (code == null || code === "") {
//不存在就打开上面的地址进行授权
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
appid +
"&redirect_uri=" +
encodeURIComponent(local) +
"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
} else {
this.code = code;
}
}
},
getUrlCode() {
// 截取url中的code方法
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
var strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
console.log(theRequest);
return theRequest;
},
}
}
5、调试工具(微信开发者工具 ::公众号网页)
输入重定向域名