文章目录
- 引入
- 实现思路
- 实现步骤
引入
electron中实际就是嵌入了一个浏览器内核,所以在electron中集成微信登录实际和web端的集成方式是一样的。
demo项目地址
实现思路
这里参考这篇文章的 electron之微信扫码登陆(不使用轮询) 实现思路:
- 1.嵌入webview,并指定地址为对应的微信登录页面 【这里的请求地址可以参考官方文档:微信网站应用登录文档说明】
- 2.监听webview的初始化,webview初始化完成后,我们执行js脚本获取二维码内容,然后通过二维码工具将其显示在图片元素中
- 3.监听webview的跳转事件,当我们扫码成功选择登录后,截取回调服务器地址跟的参数code,然后我们自己手动使用code去请求
实现步骤
1.安装二维码依赖:
npm i qrcode
npm i --save-dev @types/qrcode
2.创建窗口的位置补充允许使用webview标签:
- 参考官方文档说明:启用webview
webviewTag: true,
3.封装微信登录组件:
- 注意这里设置里webview的高度为0,测试阶段可以不设置高度为0 ,就可以看到webview页面中真正的微信登录页面
<template>
<div class="weiXinLoginBox">
<webview id="webview" :src="wxloginurl"></webview>
<div class="qrcode" v-loading="loading">
<img src="" alt="" />
</div>
</div>
</template>
<script setup lang="ts">
import QRCode from "qrcode";
import { getUrlParam } from "@/utils/myUtils";
import { ref, onMounted } from "vue";
const emit = defineEmits(["wxloginCallback"]);
const loading = ref(true);
const wxloginurl = ref("");
// ***** 只需修改以下2个参数的值即可 *****
// 回调地址 这里其实只需要保证和微信开放平台配置的服务器域名一致即可,地址随便填,因为我们真正要取到的是回调的code
const webviewUrl = encodeURIComponent(
`服务器回调地址`
);
const appId = "";
// 可由后端生成,用做安全校验,微信回调会返回这个值
const state = Math.random().toString().slice(2);
// 拼接微信登录请求地址
wxloginurl.value = `https://open.weixin.qq.com/connect/qrconnect?appid=${appId}&redirect_uri=${webviewUrl}&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect`;
// 获取微信登录的二维码
onMounted(() => {
const webview = document.querySelector("webview") as any;
webview.addEventListener("dom-ready", (e: any) => {
console.log("webview加载完毕~~");
webview
.executeJavaScript(`document.querySelector('.qrcode').outerHTML`)
.then((res: any) => {
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`;
console.log("qrcodeUrl", qrCodeUrl);
QRCode.toDataURL(qrCodeUrl, (err: any, url: string) => {
loading.value = false;
if (err) return;
// 这里的url就是要显示在真实页面上的二维码了
const img = document.querySelector("img");
if (img) {
img.src = url;
}
});
});
});
// 微信扫码后的webView跳转监听
webview.addEventListener("will-navigate", (e: any) => {
console.log(
"监听到用户扫码后的webView跳转,得到的登录code为",
getUrlParam(e.url, "code")
);
loading.value = true;
// 将得到的code返回给父组件
emit("wxloginCallback", getUrlParam(e.url, "code"));
});
});
</script>
<style scoped lang="scss">
.weiXinLoginBox {
width: 100%;
#webview {
height: 0;
}
.qrcode {
width: 200px;
height: 200px;
margin: 0 auto;
img {
width: 100%;
height: 100%;
margin: auto;
}
}
}
</style>