You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需付费或免费试用,能否用Google-signin API实现Google登录按钮?

无需付费集成Google登录按钮的方法

首先明确:Google登录(Continue with Google)的基础功能完全可以免费使用,不需要强制付费或开启付费试用。Google Identity Platform提供每月10万次免费的身份验证请求额度,这个量级足够个人开发者或小型网站使用,超出额度后才会产生费用。

以下是具体实现步骤:

1. 配置Google开发者控制台

  • 登录Google开发者控制台,创建一个新项目。
  • 进入「OAuth同意屏幕」配置页面:
    • 选择「外部」类型(适合公开访问的网站),填写应用名称、支持邮箱等基础信息。
    • 在「测试用户」部分添加允许登录的邮箱(未完成应用验证前,只有这些测试用户能使用登录功能)。
  • 创建OAuth 2.0客户端ID:
    • 选择「Web应用」类型,填写应用名称。
    • 在「授权重定向URI」中添加你的登录回调地址(比如本地开发用http://localhost:3000/google-callback,生产环境填你的域名地址)。
    • 创建后保存生成的客户端ID,后续会用到。

2. 前端实现登录按钮

使用Google官方提供的GSI(Google Identity Services)库快速实现按钮:

引入GSI脚本

在HTML页面的<head>或<body>末尾添加:

<script src="https://accounts.google.com/gsi/client" async defer></script>

添加登录按钮容器

在需要显示按钮的位置插入:

<!-- 初始化配置 -->
<div id="g_id_onload"
     data-client_id="你的客户端ID"
     data-callback="handleGoogleLogin">
</div>

<!-- 登录按钮 -->
<div class="g_id_signin"
     data-type="standard"
     data-size="large"
     data-theme="outline"
     data-text="continue_with"
     data-shape="rectangular"
     data-logo_alignment="left">
</div>

编写回调函数

在页面中添加JavaScript处理登录回调:

function handleGoogleLogin(response) {
  // response.credential是Google返回的JWT令牌,包含用户基本信息
  const idToken = response.credential;
  
  // 将令牌发送到后端验证(推荐步骤,确保登录安全)
  fetch('/api/google-auth', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ token: idToken })
  })
  .then(res => res.json())
  .then(data => {
    if (data.success) {
      // 登录成功,跳转到主页或用户面板
      window.location.href = '/dashboard';
    } else {
      alert('登录失败,请重试');
    }
  });
}

3. 后端验证令牌(可选但推荐)

为了确保登录请求的合法性,建议在后端验证Google返回的JWT令牌。以下是Node.js示例:

安装依赖

npm install google-auth-library

验证代码

const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client('你的客户端ID');

// 验证令牌的函数
async function verifyToken(idToken) {
  try {
    const ticket = await client.verifyIdToken({
      idToken: idToken,
      audience: '你的客户端ID' // 必须和前端使用的客户端ID一致
    });
    const payload = ticket.getPayload();
    // payload包含用户的邮箱、姓名、头像等信息
    return { success: true, user: payload };
  } catch (error) {
    return { success: false, message: '无效的令牌' };
  }
}

// 路由处理
app.post('/api/google-auth', async (req, res) => {
  const { token } = req.body;
  const result = await verifyToken(token);
  res.json(result);
});

额外说明

  • 未验证的应用仅支持测试用户登录,如果要面向所有Google用户开放,需要提交应用验证(免费,需等待Google审核)。
  • 免费额度每月10万次请求,超出后按阶梯计费,个人项目基本不会触发收费。

内容的提问来源于stack exchange,提问作者Stephen Matthew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 14:22:47