美文网首页
微信公众号开发—获取微信openid

微信公众号开发—获取微信openid

作者: 月儿湾啊 | 来源:发表于2018-05-20 19:04 被阅读0次

前言

微信在获取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获取错误");
      });
  };
}

相关文章

网友评论

      本文标题:微信公众号开发—获取微信openid

      本文链接:https://www.haomeiwen.com/subject/txitjftx.html