获取code
以uniapp代码为例,其他类似
在mounted生命周期里执行getCode方法
mounted() {
this.getCode();
}
getCode() {
this.code = "";
let local = window.location.href; // 获取页面url
let appid = "自己公众号的appid";
// 判断本地有没有
let userdatas = uni.getStorageSync("userdata");
this.code = this.getUrlCode().code; // 截取code
if (this.code == null || this.code === "") {
// 如果没有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=123#wechat_redirect`;
} else {
//判断本地有没有用户信息,如果们没有就调接口
// 调用接口获取用户信息
let wxdata = await getdata({
code: this.code,
state: "STATE",
});
if (wxdata[1]?.data?.code == 200) {
uni.setStorageSync('userdata', '');
let Wxobj = {
...wxdata[1]?.data?.data,
wxGuid: wxdata[1]?.data?.data.wxId,
};
this.vxId = wxdata[1]?.data?.data.wxId;
uni.setStorageSync("userdata", JSON.stringify(Wxobj));
this.$refs.child.setTabs();
let carpara = {
guid: wxdata[1]?.data?.data.wxId,
}
this.getMyApprovalParticularsLasts(carpara)
}
}
}
从url获取code的方法
getUrlCode() {
// 截取url中的code方法
var url = location.search;
this.winUrl = 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++) {
theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
}
}
return theRequest;
}