vue实现web微信扫码登录

306 阅读1分钟

web微信扫码登录

1、准备工作

  • 去微信开放平台注册账号,然后申请对应的网站应用开发,需要域名做重定向操作

    open.weixin.qq.com/cgi-bin/ind…

  • 申请成功后,拿到应用内的 appid

2、使用

  • 加入微信官方的 js 文件

    • <script src="https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
      
      注意:http 和 https
      
  • 需要容器去显示二维码相关内容,我这边因为需要频繁去切换,且暂时没有办法隐藏已经加载的二维码内容,所以使用创建、删除 DOM 操作达到需求

    • <div id="didver" ref="wxContainer"></div>
      //用来创建 dom,创建的dom在它里面
      
      //创建 dom,然后使用方法渲染上去
      this.$nextTick(() => {
      	let div = document.createElement('div')
      	div.id='wxContainer'
      	this.$refs.wxContainer.appendChild(div)
      	new WxLogin({
      	self_redirect: false,//扫码后默认重新打开的回调地址,true当前页iframe内嵌打开,false为替换当前页面打开
      	id: 'wxContainer',
      	appid: 'wx73e45673cb4accf4',
      	scope: 'snsapi_login',
      	redirect_uri:encodeURIComponent('https://...'),
      	state: dayjs().valueOf(), 
      	style: 'black',      	href:'data:text/css;base64,LnFyY29kZSB7CiAgd2lkdGg6IDIyMHB4ICFpbXBvcnRhbnQ7CiAgaGVpZ2h0OiAyMjBweDsKfQo=',
          //样式写好后转为base64  地址https://www.zxgj.cn/g/base64
      	state: 2 //自定义带的参数
      })
      })
      
      //关闭-删除dom操作
      document.getElementById("wxContainer").remove()
      

3、在 vue3 + ts 中使用

大致是一样的,唯一的点就是 ts 对于 new ... 这种操作需要先定义

declare let TencentCaptcha: any;
new TencentCaptcha ...