【微信小程序H5】获取openId,全部过程,复制即用

630 阅读1分钟

1.判断是否为微信环境

var ua = navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      console.log('在微信浏览器内');
      this.wxEnv = true
      //是微信环境就调用获取
      this.getCode()

    } else {
      console.log('不在微信浏览器内');
      this.wxEnv = false
      return
    }

2.获取code

  getCode() {
      let appid = "xxxxxxxxxxx"; //个人开发者appid
      let redirect = encodeURIComponent(window.location.href); //重定向回来的地址
      let wx_code = this.getUrlParam("code"); // 截取url中的code
      //判断有没有code
      if (!wx_code) {
        //获取code的地址。获取成功重定向后地址栏中将会带有code,判断没有code的话,就跳转到微信官方链接上获取,获取成功后会再重定向回来,注意url是需要使用encodeURIComponent处理一下编码的
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
      } else {
        // 获取到了code
        this.getOpenId(wx_code); //把code传给后台获取用户信息
      }
    },
    //getUrlParam方法就是使用正则截取地址栏里的code
    getUrlParam: function (name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      var r = window.location.search.substr(1).match(reg);
      if (r != null) return unescape(r[2]);
      return null;
    },
    getOpenId(code) {
      //这里调用后端给的接口吧code传过去就好了
      console.log(code, "code");
    },