获取微信授权的code

823 阅读1分钟

跳转微信获取code

const goWxGetCode = (appid) => {
  const localUrl = encodeURIComponent(location.href)

  const params = {
    appid,
    redirect_uri: localUrl,
    response_type: 'code',
    scope: 'snsapi_base',
    state: 'STATE',
  }
  const stringify = (obj)=> Object.keys(obj).reduce((pre, cur) => pre + `${cur}=${obj[cur]}&`, '').slice(0, -1)
  const url = `https://open.weixin.qq.com/connect/oauth2/authorize?${stringify(params)}#wechat_redirect`
  location.replace(url);
}

如果有多余的返回可以增加返回关闭功能

// const jsApiList = ['closeWindow']
 if (window.history && (window.history).pushState) {
    
      history.pushState(null, null, document.URL)
      window.addEventListener(
        "popstate",
        () => {
          window.wx.closeWindow();
        },
        false
      );
    }