公司最近有一个外网的项目其中一个需求就是使用谷歌登录,借此分享一下整个过程,希望能对正好有该需求的前端小伙伴提供一些便利
第一步就是前往谷歌的api和服务网页(需要翻墙进入o)
没有项目的需要新建一个项目
接着点击创建凭据选择OAuth客户端id填写相应的信息
随后只需要根据项目的地址编辑授权的js来源即可,
注意点 1.本地测试必须多写一个http://localhost ,不然本地无法请求到谷歌服务 2.端口不是80的话需要写上端口号 3.http协议可能会无法请求到谷歌的服务,(本人公司测试环境是http协议的,无法进行操作,同样代码在生产环境可以运行)
接着是vue项目的代码部分
<div
id="g_id_onload"
data-client_id="yourGoogleId"
data-context="signin"
data-ux_mode="popup"
:data-login_uri="location.origin"
data-auto_prompt="false">
</div>
<el-button class="btn btn-google" v-waves @click="googleClick" :loading="loading">
<span>
<el-image :src="google"></el-image>
Log in with Google
</span>
</el-button>
useScriptTag( //useScriptTag为vueuse库中的函数,引入后可直接使用
'https://accounts.google.com/gsi/client', //该文件需要翻墙才能请求到
// on script tag loaded.
(el: HTMLScriptElement) => {
console.log(el)
//引入成功后会生成一段dom 其中包括id为’button-label‘子元素
//后续点击事件就通过该dom的click事件实现
gload(handleCredentialResponse);
})
//谷歌登录初始化
const gload = async (fn: Function) => {
// console.log(window.google);
if ((window as any).google && (window as any).google.accounts) {
(window as any).google.accounts.id.initialize({
// 主要就是填写client_id
client_id: "yourGoogleId",
callback: fn,
});
const dom = document.getElementById("g_id_onload");
(window as any).google.accounts.id.renderButton(dom, {
type: "icon",
shape: "square",
theme: "outline",
text: "signin_with",
size: "medium"
});
}
}
//谷歌登录服务回调函数
const handleCredentialResponse = async (response) => {
if (response) {
// console.log(response, "回调");
const responsePayload = decodeJwtResponse(response.credential);
console.log(responsePayload, "回调")
}
}
//回调函数参数的处理
const decodeJwtResponse = (token) => { //加密
const strings = token.split(".");
return JSON.parse(
decodeURIComponent(
escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")))
)
);
}
const googleLoginClick = () => {
document.getElementById('button-label')!.click()
}
//谷歌登录按钮的点击事件
const googleClick = () => {
if (document.getElementById('button-label')) {
//登录相关处理
confirmLogin(googleLoginClick)
} else {
gload(handleCredentialResponse);
useMessage().error('Google service loading failed');
}
}