收藏
回答

请问构造网页授权链接时, 怎么判断获取code的时机呢?

https://work.weixin.qq.com/api/doc/90001/90143/91120 具体文档接口。

在使用 构造第三方应用oauth2链接时, 由于设置的是静默授权, 再重新返回到页面时,获取不到code值, 我设置了一个定时器进行延时2秒才能获取code值。 请问一下这个code返回的时机是如何判断的呢?如果用定时器肯定是不可靠的。。


具体代码如下:

  created() {
    if (this.$store.state.userid) {
      //如果已经获取到用户信息,则直接请求数据并返回
      this.aunttes();
      this.announcement();
      return;
    }


    if (!this.$route.query.code) {
      //没有code进行授权跳转
      const redirect_uri = encodeURIComponent(location.href);
      window.open(
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=#wechat_redirect`
      );
    }
  },
  mounted() {
    setTimeout(async () => {
      if (this.$route.query.code) {
        //如果有code请求接口
        try {
          const data = qs.stringify({
            infocode: this.$route.query.code
          });
          const result = await axios({
            url: "/crm/Mymine/updateInfo",
            method: "POST",
            data
          });
          if (result.data.code == 1) {
            this.SET_USERID(result.data.data.userid);
            this.SET_ACCOUNTID(result.data.data.account_id);
            sessionStorage.setItem("userid", result.data.data.userid);
            sessionStorage.setItem("account_id", result.data.data.account_id);
            this.$router.push({
              name: "login"
            });
          } else if (result.data.code == 0) {
            this.unAuthorized();
          }
        } catch (error) {
          this.unAuthorized();
        }
      }
    }, 2000);
  },


回答关注问题邀请回答
收藏

1 个回答

  • 企业微信运营专员-千夜
    企业微信运营专员-千夜
    2020-07-09

    您好,这里只要用户点击完就会跳转到你的页面,跳转到这个页面就会带上code的,不明白这里说的延时是什么意思

    2020-07-09
    有用
    回复 5
    • 沧海的雨季
      沧海的雨季
      2020-07-09
      我这里不加定时器是没有code的, 只有刷新才有了code, 一直想不明白咋回事儿。。 后来加了一个定时2秒才获取到了, 所以我想是不是微信那边获取code也是需要一些时间的,应该是异步的
      2020-07-09
      回复
    • 沧海的雨季
      沧海的雨季
      2020-07-09回复沧海的雨季
      正常的逻辑应该是怎么写的啊?
      2020-07-09
      回复
    • 沧海的雨季
      沧海的雨季
      2020-07-09
      好的, 使用watch监听路由已经解决了, 非常感谢!
      2020-07-09
      回复
    • 企业微信运营专员-千夜
      企业微信运营专员-千夜
      2020-07-09回复沧海的雨季
      code不是异步,是实时回调的
      2020-07-09
      回复
    • 沧海的雨季
      沧海的雨季
      2020-07-09回复企业微信运营专员-千夜
      好的, 非常感谢了!
      2020-07-09
      回复
登录 后发表内容
问题标签