先说先思路:在要扫码的页面嵌入webview,注意这个webview是隐藏在页面的后面,里面是微信的扫码登陆界面,获取这个页面的二维码,然后把这个码显示到真实的页面上,用户扫码之后在webview里面的页面就会触发微信的回调,监听这个回调,获取自家服务器返回的信息,判断用户是否能够登陆
1. 嵌入webview
<webview id="webview" :src="wxloginurl"></webview>
2. 生成微信的扫码页面,就是上面wxloginurl
const appID = config.appID
const webviewUrl = encodeURIComponent(`${config.baseUrl}/login/weixin/callback`)
const state = Math.random().toString().slice(2)
this.wxloginurl = `https://open.weixin.qq.com/connect/qrconnect?appid=${appID}&redirect_uri=${webviewUrl}&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect`
3. 获取webview中的微信二维码
先引入能生成二维码的npm包 yarn add qrcode
然后引入 import QRCode from 'qrcode'
const webview = document.querySelector('webview')
webview.addEventListener('dom-ready', e => {
webview.executeJavaScript(`document.querySelector('.qrcode').outerHTML`).then(res => {
const uuid = res?.match(/src="\/connect\/qrcode\/(\S*)">/)[1]
const qrCodeUrl = `https://open.weixin.qq.com/connect/confirm?uuid=${uuid}&chInfo=ch_share__chsub_CopyLink`
QRCode.toDataURL(qrCodeUrl, (err, url) => {
if (err) return
// 这里的url就是要显示在真实页面上的二维码了
})
})
})
4. 用户扫码之后, 监听webview中地址的跳转,也就是微信的回调
webview.addEventListener('will-navigate', (e) => {
const webContents = this.$electron.remote.webContents.fromId(webview.getWebContentsId())
// 过滤url地址,只监听需要的url
const filter = { urls: [`${config.baseUrl}/*`] }
webContents.session.webRequest.onCompleted(filter, (details) => {
const Token = details.responseHeaders['Header-Access-Token']
// 我这里是获取到请求头中的Token,details中有更多信息
// do some thing
})
})
还有一种简单的方法:
就是直接通过 this.$electron.remote.session.defaultSession.webRequest.onCompleted(filter, (details) => {}) 监听扫码后微信的回调