跳转到主要内容
Service Account 认证非常适合服务器间访问 Google Sheets 的场景。无需用户操作,应用程序自身即可操作电子表格。适用于自动化任务和后台作业。

适用场景

  • 服务器间访问 — 无需用户操作,应用即可访问 Sheets
  • 自动化系统 — 后台作业、cron 任务、自动化报表
  • 固定电子表格 — 控制特定的电子表格
  • 生产环境 — 无需用户同意流程,稳定运行

前提条件

  • Google Cloud Console 项目
  • 启用 Google Sheets API 与 Google Drive API
  • 项目管理员权限

配置

1

创建 Google Cloud 项目

  1. 访问 Google Cloud Console
  2. 新建项目或选择已有项目
  3. 记下项目 ID
2

启用所需 API

  1. 前往 APIs & Services > Library
  2. 搜索并启用以下 API:
    • Google Sheets API
    • Google Drive API
3

创建 Service Account

  1. 前往 APIs & Services > Credentials
  2. 点击 Create Credentials > Service Account
  3. 填写 Service Account 详情:
    • Service account name:具有描述性的名称(例如”Laravel Sheets App”)
    • Service account ID:自动生成
    • Description:可选
  4. 点击 Create and Continue
  5. 两个可选部分均跳过,点击 Done
4

生成 Service Account 密钥

  1. Credentials 页面点击刚创建的 Service Account
  2. 切换到 Keys 标签
  3. 点击 Add Key > Create new key
  4. 密钥格式选择 JSON
  5. 点击 Create
  6. JSON 文件将自动下载
5

保存 JSON 文件

  1. 将下载的 JSON 文件移动到 storage/app/
  2. 重命名为 google-service-account.json
  3. 重要:将其加入 .gitignore,排除在版本控制之外
# 添加到 .gitignore
storage/app/google-service-account.json
6

配置 .env 文件

.env 中添加以下内容:
GOOGLE_SERVICE_ENABLED=true
GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION=storage/app/google-service-account.json
7

在 config/google.php 中配置 scope

'scopes' => [
    \Google\Service\Sheets::SPREADSHEETS,
    \Google\Service\Drive::DRIVE,
],
8

共享电子表格

对于每个 Google Sheets 电子表格:
  1. 在 Google Sheets 中打开
  2. 点击 共享 按钮
  3. 复制 JSON 文件中的 client_email 字段
  4. 将电子表格分享给该邮箱(例如 [email protected]
  5. 选择权限:
    • 查看者 — 只读
    • 编辑者 — 读写
    • 所有者 — 完全访问(不推荐)

使用方法

配置完成后,Service Account 将被自动使用。无需设置访问令牌。
use Revolution\Google\Sheets\Facades\Sheets;

// Service Account 会被自动使用
$values = Sheets::spreadsheet('your-spreadsheet-id')
    ->sheet('Sheet1')
    ->all();

// 通过电子表格名称引用(需要访问 Drive API)
$values = Sheets::spreadsheetByTitle('My Spreadsheet')
    ->sheet('Sheet1')
    ->all();

安全最佳实践

1. 限制 Service Account 权限

  • 仅共享必要的电子表格
  • 使用 编辑者 而非 所有者
  • 定期审计访问权限

2. 安全保管密钥

  • 不要将 Service Account 密钥纳入版本控制
  • 通过 .gitignore 可靠地排除
  • 生产环境将其保存在 web root 之外的安全位置
  • 定期轮换密钥

3. 部署到生产环境

额外的安全措施:
  • 将 JSON 密钥保存在 web root 之外的安全位置
  • 各环境使用不同的 Service Account(开发、预发布、生产)
  • 在 Google Cloud Console 中监控这些账号的使用情况
  • 对可疑活动进行日志记录与告警

环境变量参考

变量说明示例
GOOGLE_SERVICE_ENABLED启用 Service Account 认证true
GOOGLE_SERVICE_ACCOUNT_JSON_LOCATIONJSON 文件路径storage/app/google-service-account.json

高级配置

将 JSON 字符串存储在环境变量中

除了将 JSON 保存为独立文件之外,你还可以将 JSON 字符串作为环境变量存储。这适用于 GitHub Actions 等 CI/CD 环境。 Step 1:在 .env 中添加 JSON 字符串
GOOGLE_SERVICE_ENABLED=true
GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION='{"type": "service_account", "project_id": "your-project-id", ...}'
Step 2:在 config/google.php 中解码 JSON 字符串
// config/google.php
'service' => [
    'enable' => env('GOOGLE_SERVICE_ENABLED', false),
    'file' => json_decode(env('GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION', ''), true),
],
这样一来,无需单独保存文件,即可完全通过 CI/CD 流水线的环境变量进行管理。

故障排查

常见错误

“caller does not have permission” 错误
  • 确认电子表格已共享给 Service Account 邮箱
  • 若为写入操作,请确认权限至少为 编辑者
“File not found” 错误
  • 检查 JSON 文件路径是否正确
  • 确认文件存在且 web 服务器可读
“API not enabled” 错误
  • 在 Google Cloud Console 中确认 Google Sheets API 与 Google Drive API 已启用
  • API 启用后请等待几分钟
“Invalid credentials” 错误
  • 确认 JSON 密钥文件有效且未损坏
  • 确认 Service Account 未被删除或禁用
  • 确认项目 ID 与 Google Cloud 项目一致

测试配置

用于验证 Service Account 配置的测试路由:
// routes/web.php
Route::get('/test-sheets', function () {
    try {
        $sheets = Sheets::spreadsheetList();
        return response()->json([
            'status' => 'success',
            'message' => 'Service Account 认证已生效',
            'spreadsheet_count' => count($sheets)
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    }
});
访问该测试路由,即可确认 Service Account 认证是否配置正确。
最后修改于 2026年7月13日