在项目如何集中微信公众号授权登录
后端跳转获取code码,最后拼接,
//保留登录前的页面参数。为了不让参数传到后台,并且在微信授权链接带来带去,可以将参数和登录前的地址存到本地缓存
let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
let curRoute = routes[routes.length - 1].route //获取当前页面路由
let curParam = routes[routes.length - 1].options; //获取路由参数
console.log(routes)
console.log(curRoute);
console.log(curParam);
if ("pages/login/login" != curRoute) {
//保存登录前的地址
uni.setStorageSync('curRoute','/'+curRoute );
//保存登录前的参数
uni.setStorageSync('curParam',curParam );
}
window.location.href =
"https://open.weixin.qq.com/connect/oauth2/authorize?appid=sdfsdfgsaa194f7ca6"
+
"&redirect_uri=" +
encodeURIComponent("http://sdfa.test.com/pages/login/login") +
"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
然后会跳转前端login这个页面
在这个页面发起请求,用code去获取授权。得到token之后拼接登录前的页面
uni.setStorage({//将用户信息保存在本地
key: 'token',
data: res.data.payload
});
let curRoute = uni.getStorageSync('curRoute');
let curParam = uni.getStorageSync('curParam');
let url = curRoute;
if(Object.keys(curParam).length > 0){
url += '?';
for(let i in curParam){
url += i + '=' + curParam[i] + '&';
}
url = url.substring(0, url.length - 1);
}
uni.reLaunch({
url: url
});
注意,模式最好用history模式
如果本地调试,这个问题很多人是很头痛的,已经弄好的请略过,因为uniapp自带服务器,微信公众号的校验文件,很多人不知道放那个位置 。
我的做法是,用花生壳通过内网穿透,先映射到apache服务器,把文件放大apache服务器下面, 让微信校验成功。成功之后,将内网映射成uniapp服务器的地址,这样就可以进行本地调试了。
有不同的,请在下方提问