適用場景
- 伺服器間存取 — 無需使用者操作,應用程式即可存取 Sheets
- 自動化系統 — 背景工作、cron 任務、自動報表
- 固定試算表 — 控制特定的試算表
- 正式環境 — 無需使用者同意流程即可穩定運作
前置條件
- Google Cloud Console 專案
- 啟用 Google Sheets API 與 Google Drive API
- 擁有專案管理員權限
設定
1
建立 Google Cloud 專案
- 前往 Google Cloud Console
- 建立新專案或選擇現有專案
- 記錄專案 ID
2
啟用必要的 API
- 前往 APIs & Services > Library
- 搜尋並啟用以下 API:
- Google Sheets API
- Google Drive API
3
建立 Service Account
- 前往 APIs & Services > Credentials
- 點擊 Create Credentials > Service Account
- 輸入 Service Account 詳細資訊:
- Service account name: 具描述性的名稱(例如「Laravel Sheets App」)
- Service account ID: 自動產生
- Description: 選填
- 點擊 Create and Continue
- 兩個選用區段直接略過並點擊 Done
4
產生 Service Account 金鑰
- 於 Credentials 頁面點擊剛建立的 Service Account
- 進入 Keys 分頁
- 點擊 Add Key > Create new key
- 金鑰格式選擇 JSON
- 點擊 Create
- JSON 檔案會自動下載
5
儲存 JSON 檔案
- 將下載的 JSON 檔案移至
storage/app/ - 更名為
google-service-account.json - 重要: 加入
.gitignore以避免納入版本控管
6
設定 .env 檔案
在
.env 加入:7
於 config/google.php 設定 scope
8
共用試算表
對每個 Google Sheets 試算表:
- 於 Google Sheets 開啟
- 點擊 共用 按鈕
- 複製 JSON 檔案中的
client_email欄位 - 與此電子郵件共用(例如:
[email protected]) - 選擇權限:
- 檢視者 — 唯讀
- 編輯者 — 讀寫
- 擁有者 — 完整存取(不建議)
使用方式
設定完成後,會自動使用 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 字串
config/google.php 解析 JSON 字串
疑難排解
常見錯誤
「caller does not have permission」錯誤- 確認試算表已與 Service Account 電子郵件共用
- 若為寫入操作,請確認權限為 編輯者 以上
- 確認 JSON 檔案路徑正確
- 確認檔案存在且 web server 可讀取
- 確認 Google Cloud Console 已啟用 Google Sheets API 與 Google Drive API
- 啟用 API 後等待數分鐘
- 確認 JSON 金鑰檔有效且未損壞
- 確認 Service Account 未被刪除或停用
- 確認專案 ID 與 Google Cloud 專案相符