Vue WeChat public account development h5 authorized login

Vue public account h5 web page realizes WeChat authorized login

This blog is written to avoid some pitfalls for the friends who started the official account. I have never done this function in the background like me. I have searched a lot of blogs. The process is very difficult. It is not difficult. Above code (can be copied directly).

1. The official account h5's webpage authorization has to configure the official account settings

Insert picture description here
2. The most important thing for h5 webpage authorization is the callback address. This address is the page you want to return to after authorization. Remember to configure the backend, otherwise it won’t work.

Insert picture description here

3. The front-end logic is 1. Page callback, 2. Get code, 3. Intercept code, 4. Back-end interaction code, appid is the appid of your own official account, remember to modify it, local generally do not change, directly encodeURIComponent analysis.
Insert picture description here

 //拿到微信code
    async toWx() {
      // 授权回调
      let local = window.location.href.split("#")[0];
      let url =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5e173bc64f0b0888&redirect_uri=" +
        encodeURIComponent(local) +
        "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
      console.log("window.location.href", window.location.href);
      let code = this.GetParam(window.location.href.split("#")[0], "code");
      if (!code) {
        window.location.href = url;
        // console.log("code", code);
      } else {
        this.code = this.GetParam(window.location.href, "code");
        console.log("code", code);
      }
    },
    // 截取code
    GetParam(url, code) {
      url = url + "";
      let regstr = "/(\\?|\\&)" + code + "=([^\\&]+)/";
      let reg = eval(regstr);
      //eval可以将 regstr字符串转换为 正则表达式
      let result = url.match(reg);
      if (result && result[2]) {
        return result[2];
      }
    },
   
  },

This is when I just started to write a blog. Forgive me for not writing a lot. If you have any questions, you can deduct me or leave a message

Guess you like

Origin blog.csdn.net/weixin_45575933/article/details/109025083