Skip to main content
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 以避免納入版本控管
6

設定 .env 檔案

.env 加入:
7

於 config/google.php 設定 scope

8

共用試算表

對每個 Google Sheets 試算表:
  1. 於 Google Sheets 開啟
  2. 點擊 共用 按鈕
  3. 複製 JSON 檔案中的 client_email 欄位
  4. 與此電子郵件共用(例如: [email protected])
  5. 選擇權限:
    • 檢視者 — 唯讀
    • 編輯者 — 讀寫
    • 擁有者 — 完整存取(不建議)

使用方式

設定完成後,會自動使用 Service Account。不需設定 access token。

安全性最佳實踐

1. 限制 Service Account 權限

  • 只共用必要的試算表
  • 使用 編輯者 而非 擁有者
  • 定期稽核存取權限

2. 安全地保管金鑰

  • 不要將 Service Account 金鑰納入版本控管
  • .gitignore 確實排除
  • 於正式環境儲存於 web root 之外的安全位置
  • 定期輪換金鑰

3. 部署至正式環境

額外的安全措施:
  • 將 JSON 金鑰儲存於 web root 之外的安全位置
  • 不同環境使用不同的 Service Account(開發、Staging、正式)
  • 於 Google Cloud Console 監控這些帳戶的使用狀況
  • 對可疑活動記錄與發出警示

環境變數參考

進階設定

將 JSON 字串儲存於環境變數

除了將 JSON 儲存為獨立檔案外,也可以將 JSON 字串儲存於環境變數。適合 GitHub Actions 等 CI/CD 環境。 Step 1: 於 .env 加入 JSON 字串
Step 2: 於 config/google.php 解析 JSON 字串
此方式不需另外儲存檔案,可完全以 CI/CD 管線的環境變數管理。

疑難排解

常見錯誤

「caller does not have permission」錯誤
  • 確認試算表已與 Service Account 電子郵件共用
  • 若為寫入操作,請確認權限為 編輯者 以上
「File not found」錯誤
  • 確認 JSON 檔案路徑正確
  • 確認檔案存在且 web server 可讀取
「API not enabled」錯誤
  • 確認 Google Cloud Console 已啟用 Google Sheets API 與 Google Drive API
  • 啟用 API 後等待數分鐘
「Invalid credentials」錯誤
  • 確認 JSON 金鑰檔有效且未損壞
  • 確認 Service Account 未被刪除或停用
  • 確認專案 ID 與 Google Cloud 專案相符

設定測試

用於確認 Service Account 設定的測試路由:
存取此測試路由以確認 Service Account 驗證是否已正確設定。
最後修改於 2026年8月2日