前言
微信在获取openid时,首先需要获取code。根据微信开发文档,获取code
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
在之前的开发中,是将获取code的url放在配置菜单中,每次点击触发菜单,获取code,这样在配置菜单url的时候,url过于复杂。
先改换成在页面中重定向获取code。以下。
1. 进入页面对页面进行重定向,获取code
进入页面之后判断是否有openid,没有的话将页面重定向至获取code的url
export function redirectPage(path) {
let appid = "wxa2b43f80deee74aa";
const url = `http://ylhtest.adt100.com${path}`;
console.log(url);
console.log(window.location.href);
if (window.location.href.includes("code")) {
// 包含就不需要重定向 只需要获取code
console.log(getQueryString("code"));
return getQueryString("code");
} else {
// 对页面进行重定向 以便获取code
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=STATE`;
console.log(window.location.href);
return "";
}
}
2. 获取code之后,调用后端接口获取openid
export function getOpenid(code) {
return dispatch => {
alert(2222);
axios({
method: "get",
url: global.url.GET_OPENID,
params: {
code: code,
appId: "wxa2b43f80deee74aa"
}
})
.then(res => {
console.log(res);
if (res.data.code === 200) {
dispatch(wxOpenid(res.data.data));
}
})
.catch(err => {
console.log("openid获取错误");
});
};
}
网友评论