微信官方文档:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0
let link = window.location.href;
let params = getUrlParams(link);
console.log('params', params)
console.log('link', link)
if (params.code) {
console.log('code1', params.code)
this.code = params.code //此重定向后会返回code,需要传递给后端
} else {
//跳转微信授权链接获取
let appid = 'wx446b2d301a9e7ddc';
let uri = encodeURIComponent(link);
console.log('uri', uri)
let authURL =`https://open.weixin.qq.com/connect/oauth2/authorize? appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
console.log('authURL', authURL)
window.location.href = authURL;
}
使用封装的方法,获取返回的code:
export function getUrlParams (search) {
search = search || location.search;
var paramsSplit = search.replace(/^[^\?]*\?/i, '').split('&');
var params = {};
if (Array.isArray(paramsSplit)) {
paramsSplit.forEach(function (item) {
const itemSplit = item.split('=');
params[itemSplit[0]] = itemSplit[1];
});
}
return params
}