【h5+微信小程序】vue2实现h5扫码登录功能

前言

需要实现在同域名的h5页面上增加一个微信扫码登录的功能,如果用户已经有小程序的账号,可以直接登录。

使用:vue2+微信小程序原生开发
可以实现上述功能的前提是:同一用户,对同一个微信开放平台下的不同应用,UnionID是相同的。域名已经配置。
可以用什么来区分是否为同一用户呢?目前项目里还是用的手机号。

正文

流程

页面嵌入二维码->用户扫码后获得临时code->发送code到后台,后台返回用户的信息

  1. 在index.html页中引入地址(但是报错了,我的解决方案在下面)
<script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
  1. 在展示二维码的页面增加如下代码,进行实例化
  //login.vue
  //二维码容器
  <div id="login_container"></div>

//在mounted中执行下面的代码,获取二维码
    //获得登录二维码
    getwxCode() {
    
    
      var obj = new WxLogin({
    
    
        id: "login_container",
        appid: "自己的",
        scope: "snsapi_login",
        redirect_uri: encodeURI("自己的"),
        state: "",
        style: "black",
        href: "自定义的样式..../qrcode.css",
        self_redirect: false,
      });
    },

这时候如果能正确展示二维码,使用手机扫码的话,就会跳转到redirect_uri,后面拼接上传回来的code值。
3.正常来讲应该在一个把redirect_uri设置为一个中间页,在中间页上进行code的处理的。
但是因为用的是history模式,所以就在首页先实现了。

  mounted() {
    
    
    this.getCodeMes();
  },
    getCodeMes() {
    
    
      let code = this.getQueryString("code");
      console.log("code:", code);
      if (!code) {
    
    
      return
      } else {
    
    
        this.getLoginMes(code);
      }
    },
    //使用正则读取url里的code
    getQueryString(name) {
    
    
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      // console.log(window.location.search);
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
    
    
        return unescape(r[2]);
      }
      return "";
    },
    //对接后端接口,获取用户信息
    getLoginMes(code) {
    
    
      let params = {
    
    
        code: code,
      };
      let queryParams = new URLSearchParams(params);
      fetch("后端接口", {
    
    
        method: "POST",
        body: queryParams,
      })
        .then((response) => {
    
    
          if (response.ok) {
    
    
            return response.json();
          }
          console.log(response);
          throw new Error("Network response was not ok.");
        })
        .then((data) => {
    
    
          console.log(data);
          //如果code过期失效了处理
          if (data.code == "100") {
    
    
            //清除一下地址上的code
            window.history.replaceState(
              null,
              null,
              window.location.href.split("?")[0] + window.location.hash
            );
            this.$router.push("/");
          }
          if (data.code == "200") {
    
    
            localStorage.setItem(
              "userinfo",
              JSON.stringify(data.result)
            );
            
            setTimeout(() => {
    
    
              window.history.replaceState(
                null,
                null,
                window.location.href.split("?")[0] + window.location.hash
              );
              this.$router.push("/登入后的页面");
            }, 2000);
          } 
        })
        .catch((error) => {
    
    
          console.error("There was a problem with the network request:", error);
        });
    },
  },

这样就基本完成了

遇到的问题

  1. 步骤1中引入地址后,谷歌浏览器上报错如下:
Unsafe JavaScript attempt to initiate navigation for frame with URL 'http://www.xxx.xxx/' from    frame with URL "https://open.weixin.com/xxxxxxx" The frame attempting navigation is targeting its top-level window, but is neither same-origin with its target nor is it processing a user gesture

解决方法:引入的js文件换成下面的
原因:浏览器禁止重定向
解决方法:直接参考里面的代码即可
https://www.cnblogs.com/enhengenhengNymph/p/14450416.html
2. 二维码无法正常显示,报错:Oops! something went wrong
- 我的原因是:“授权回调域”写错了。没有和开放平台的对上。
- 其他可能的原因:先排除不是网站备案问题,不是第三方与微信平台配置的问题,也不是公众号里面没有设置业务域名或js接口安全域名。
- 参考

参考和补充

参考

0.微信官方:网站应用微信登录开发指南
1.vue 微信扫码登录嵌入方式及开发踩的坑点:比较详细,从获取appid到二维码样式都有说到。不足是没有继续说明扫码的过程了。
2.vue 实现PC端微信扫码登录(二维码内嵌网页版):有比较完整的流程,使用路由拦截code,还包括了如果扫码用户未注册的绑定?(我没试过)
3.前端实现 微信扫码登录网站 pc端(二维码嵌套页面) 超详细,包会:是挺详细的,关于样式自定义也有说,但是图挂了。
4.关于二维码的生成和嵌入讲得比较详细:关于二维码的生成和嵌入讲得比较详细
5.如何实现微信扫码登录功能(Vue):很全,包括后端使用Node.js的部分也有写到。从注册到获取token。100分!
6.微信小程序如何获取用户unionId?前置知识可看下

补充

其他参考&方案

Vue微信登录流程:使用的是vue-wxlogin,感觉差不多,只是不需要引入script

其他优化

  1. 完成登录之后,处理一下code,去掉它。(只是为了让url看起来清爽点)

其他待优化

1.没有用history模式,所以扫码完,只能先返回...8080/这个页面接收code。(不能带#号,#后面的会被清除掉
2.可以参考这种样式,使用图标进行登录方式的切换,这样UI还挺好苦的。vue - 网站接入微信扫码登录功能详细教程,完整详细流程及完整功能示例源代码(附常见问题的解决方案与二维码样式修改方案)一个付费专栏的文章,没有看。
3.可以接着增加二维码的有效期、自动/手动刷新等功能。

猜你喜欢

转载自blog.csdn.net/sinat_41838682/article/details/131028854