js获取微信验证实现微信自动跳转 检验code操作

315 阅读1分钟
// 监测sessionStorage code是否存在
 if (!sessionStorage.getItem("islogin")) {
      if (code == "" || code == undefined) {
        console.log('code为空') // 没有code获取code
        $.ajax({
          type: 'GET',
          // 域名  自定义链接微信地址获取app_id
          url: 'https://  /wechatcallback/v1/wxappinfo/' ,
          success: function (res) {
            if (Number(res.errno) === 0) {
              appid = res.wxappinfo.app_id;
              app_name = res.wxappinfo.app_name;
              var state = Date.parse(new Date());
              var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(location.href)}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
              document.write("<a href='" + url + "'>如您的浏览器没有自动跳转,请点击此处手动跳转</a>");
              window.location.href = url;
            }
          }, 
          error: function () {
            warningTip('服务器链接失败', 5000)
          }
        })
      } else {
      // code存在 通过自定义微信内置接口获取想要的数据
        code = getSearchVal('code');
        $.ajax({
          type: 'POST',
          url: ',
          contentType: 'application/json',
          data: JSON.stringify({
            code: code,
          }),
          success: function (res) {
            if (Number(res.errno) === 0) {
              sessionStorage.setItem("unionid", res.data.unionid);
              sessionStorage.setItem("nickname", res.data.nickname);
              unionid = res.data.unionid;
              nickname = res.data.nickname;
            }
          },
          error: function () {
            warningTip('服务器链接失败', 5000)
          }
        })
      }
    } else {
      console.log('最后')
      // alert('有code') 有code直接保存uniond
      console.log()
      unionid = sessionStorage.getItem("unionid");
      nickname = sessionStorage.getItem("nickname");
    }
  }