PAYATHON 2026

无需启用 billing 如何使用 Google Sign-In API?

AI 小顾

结论

可以。普通网站接入 Google 登录,一般不需要启用 Billing,也不需要开通 Google Cloud Free Trial。

接入 Google Sign-In,主要需要创建 OAuth 2.0 Client ID,并配置 OAuth consent screen 和网站来源。如果控制台要求绑定付款方式,通常是因为启用了需要计费的 Google Cloud 服务,或者进入了与登录无关的 API 配置流程。单纯实现 “Continue with Google” 不需要 API Key,也不应要求用户提供 Google 密码。

目前 Web 端应优先使用 Google Identity Services(GIS)。新功能不要再使用旧版 gapi.auth2。

配置步骤

1. 创建或选择 Google Cloud 项目

进入 Google Cloud Console 创建项目。创建项目本身通常不要求启用 Billing。

接着,在 Google Auth Platform 或 OAuth 相关页面中填写应用信息。Google 控制台的菜单名称可能会调整,常见入口有:

  • Google Auth Platform
  • APIs & Services → OAuth consent screen
  • APIs & Services → Credentials

填写应用名称、支持邮箱等基本信息,再根据用户范围选择 Audience:

  • 如果只供某个 Google Workspace 组织内部使用,选择 Internal,但需要满足相应的组织条件。
  • 如果面向普通 Google 账号用户,选择 External。

应用处于测试状态时,需要将测试账号添加到 Test users。未加入名单的账号可能无法登录。

如果只用于身份登录,一般只需申请以下基础身份范围:

  • openid
  • email
  • profile

不要为了登录申请 Gmail、Drive、Calendar 等额外权限。敏感或受限范围可能需要额外审核,但是否需要审核与 Billing 无关。

3. 创建 OAuth Client ID

创建凭据时选择:

OAuth client ID
Application type: Web application

然后配置 Authorized JavaScript origins,例如:

http://localhost:3000
https://www.example.com

这里填写的是”来源”,也就是协议、域名和端口,不能带路径:

https://www.example.com/login   ❌
https://www.example.com         ✅

如果使用重定向登录流程,还要配置 Authorized redirect URIs,例如:

https://www.example.com/auth/google/callback

保存后会得到类似下面的 Client ID:

1234567890-abcdefg.apps.googleusercontent.com

Client ID 可以放在前端代码中。Client Secret 不能放进浏览器代码或公开仓库。

添加 Google 登录按钮

使用 Google Identity Services 提供的按钮组件即可:

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>Google Sign-In</title>
  <script src="https://accounts.google.com/gsi/client" async></script>
</head>
<body>
  <div
    id="g_id_onload"
    data-client_id="YOUR_CLIENT_ID.apps.googleusercontent.com"
    data-callback="handleCredentialResponse"
    data-auto_prompt="false">
  </div>

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

  <script>
    function handleCredentialResponse(response) {
      // response.credential 是 Google 返回的 ID token。
      // 不要只在浏览器中解析后就认为用户已经完成可信登录。
      fetch("/auth/google", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        credentials: "same-origin",
        body: JSON.stringify({
          credential: response.credential
        })
      })
        .then((res) => {
          if (!res.ok) {
            throw new Error("Google sign-in failed");
          }
          return res.json();
        })
        .then((data) => {
          console.log("Signed in:", data);
        })
        .catch((error) => {
          console.error(error);
        });
    }
  </script>
</body>
</html>

把 YOUR_CLIENT_ID.apps.googleusercontent.com 替换为控制台生成的 Web Client ID。

如果直接双击本地 HTML,并通过 file:// 打开,通常无法通过 OAuth 来源校验。开发时应启动本地 Web 服务器,并将实际来源添加到 Authorized JavaScript origins,例如:

http://localhost:3000

服务端必须验证 ID token

前端收到的 response.credential 是 JWT 格式的 ID token。正式登录时,需要将它提交到自己的服务端,并由服务端验证:

  • 签名是否有效;
  • aud 是否等于你的 Google Client ID;
  • iss 是否为合法的 Google 签发方;
  • token 是否过期;
  • 必要时检查 nonce、hd 等约束。

验证通过后,使用 sub 作为 Google 账号稳定的唯一标识,再创建自己的登录 Session。不要将邮箱作为永不变化的主键,也不能只解码 JWT 就信任其中的内容。

下面是 Node.js/Express 示例:

npm install express google-auth-library
import express from "express";
import { OAuth2Client } from "google-auth-library";

const app = express();
const clientId = process.env.GOOGLE_CLIENT_ID;
const googleClient = new OAuth2Client(clientId);

app.use(express.json());

app.post("/auth/google", async (req, res) => {
  try {
    const { credential } = req.body;

    if (typeof credential !== "string" || credential.length === 0) {
      return res.status(400).json({ error: "Missing credential" });
    }

    const ticket = await googleClient.verifyIdToken({
      idToken: credential,
      audience: clientId
    });

    const payload = ticket.getPayload();

    if (!payload?.sub) {
      return res.status(401).json({ error: "Invalid Google identity" });
    }

    const user = {
      googleSubject: payload.sub,
      email: payload.email,
      emailVerified: payload.email_verified,
      name: payload.name,
      picture: payload.picture
    };

    // 在这里查找或创建本地用户,并建立安全的服务端 Session。
    // 不要直接把整个 Google token 当作自己的长期会话凭据。

    res.json({
      ok: true,
      user
    });
  } catch {
    res.status(401).json({ error: "Invalid Google ID token" });
  }
});

app.listen(3000);

GOOGLE_CLIENT_ID 应使用同一个 Web Client ID,例如:

GOOGLE_CLIENT_ID=1234567890-abcdefg.apps.googleusercontent.com

常见问题

控制台仍然要求启用 Billing

先确认你创建的是 OAuth 2.0 Client ID,而不是 API Key、Firebase 付费功能、Maps、Cloud Run 或其他可能收费的服务。

如果只接入 Google 登录,通常不需要启用额外的 Google API。如果某一步确实强制要求 Billing,请记录页面显示的具体产品名称和提示内容。这通常意味着当前配置的不是单纯的身份登录功能。

出现 The given origin is not allowed

这表示实际页面来源与 Authorized JavaScript origins 中的配置不一致。协议、域名和端口必须完全匹配,例如:

http://localhost:3000
http://localhost:5173
https://example.com
https://www.example.com

这些地址属于不同来源,需要分别配置。

测试账号能登录,其他账号不能

检查 OAuth 应用是否仍处于 Testing 状态,以及目标账号是否已经加入 Test users。

面向公众开放前,还需要补齐应用信息、隐私政策和授权域名等配置。是否需要验证,取决于应用类型和申请的权限范围。

是否可以自己画一个相似按钮

可以通过 JavaScript API 自定义触发流程,但按钮的文字、图标、间距和品牌样式需要遵守 Google 的品牌规范。直接使用 GIS 渲染的官方按钮通常更方便,也能减少样式和兼容性问题。

官方入口:

备注:内容仅供参考。