微信打开h5页面时,获取微信code作为参数使用
global.js
let environment = true; //配置正式环境和测试环境的appid(微信公众号的)
export default {
oauth_url_weixin: "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + (environment ? 'wx3c9600b2c259e4c8' : 'wxc541f115b5e6857f') + "&redirect_uri=REDIRECTURI&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect",
}
getUrl.js
// 将连接后面的参数 对象化
export default function getQueryString(url) {
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 ++) {
// decodeURI 乱码转中文
theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1])
}
}
return theRequest;
}
main.js
import getQueryString from '@/utils/getUrl.js'
router.beforeEach((to, from, next) => {
let cusId = window.sessionStorage.getItem("cusId");
//获取code
let code = getQueryString(window.location.search).code;
//获取链接后面参数
let channel = getQueryString(window.location.search).channel;
let productId = getQueryString(window.location.search).productId;
let g = getQueryString(window.location.search).g;
//code五分钟失效
if (code == undefined || code == 'undefined' || code == null) {
if (cusId == undefined || cusId == 'undefined' || cusId == null) {
window.localStorage.clear()
//重定向的链接及拼接参数
let url = "https://youxuan.91betterwei.com/smhk/index.html?channel=" + channel + '&productId=' + productId + '&g=' + g
window.location.href = global.oauth_url_weixin.replace('REDIRECTURI', encodeURIComponent(url));
}
}
if (to.meta.title) {
document.title = to.meta.title
}
next()
})