> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Service Account 驗證 - Google Sheets API for Laravel

> 設定 Google Sheets API 的 Service Account 驗證。適合伺服器間通訊。

Service Account 驗證適合在伺服器間存取 Google Sheets。不需使用者操作,由應用程式本身操作試算表。適合自動化任務與背景工作。

## 適用場景

* **伺服器間存取** — 無需使用者操作,應用程式即可存取 Sheets
* **自動化系統** — 背景工作、cron 任務、自動報表
* **固定試算表** — 控制特定的試算表
* **正式環境** — 無需使用者同意流程即可穩定運作

## 前置條件

* Google Cloud Console 專案
* 啟用 Google Sheets API 與 Google Drive API
* 擁有專案管理員權限

## 設定

<Steps>
  <Step title="建立 Google Cloud 專案">
    1. 前往 [Google Cloud Console](https://console.cloud.google.com/)
    2. 建立新專案或選擇現有專案
    3. 記錄專案 ID
  </Step>

  <Step title="啟用必要的 API">
    1. 前往 **APIs & Services** > **Library**
    2. 搜尋並啟用以下 API:
       * **Google Sheets API**
       * **Google Drive API**
  </Step>

  <Step title="建立 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**
  </Step>

  <Step title="產生 Service Account 金鑰">
    1. 於 **Credentials** 頁面點擊剛建立的 Service Account
    2. 進入 **Keys** 分頁
    3. 點擊 **Add Key** > **Create new key**
    4. 金鑰格式選擇 **JSON**
    5. 點擊 **Create**
    6. JSON 檔案會自動下載
  </Step>

  <Step title="儲存 JSON 檔案">
    1. 將下載的 JSON 檔案移至 `storage/app/`
    2. 更名為 `google-service-account.json`
    3. **重要**: 加入 `.gitignore` 以避免納入版本控管

    ```bash theme={null}
    # 加入 .gitignore
    storage/app/google-service-account.json
    ```
  </Step>

  <Step title="設定 .env 檔案">
    在 `.env` 加入:

    ```env theme={null}
    GOOGLE_SERVICE_ENABLED=true
    GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION=storage/app/google-service-account.json
    ```
  </Step>

  <Step title="於 config/google.php 設定 scope">
    ```php theme={null}
    'scopes' => [
        \Google\Service\Sheets::SPREADSHEETS,
        \Google\Service\Drive::DRIVE,
    ],
    ```
  </Step>

  <Step title="共用試算表">
    對每個 Google Sheets 試算表:

    1. 於 Google Sheets 開啟
    2. 點擊 **共用** 按鈕
    3. 複製 JSON 檔案中的 `client_email` 欄位
    4. 與此電子郵件共用(例如: `your-service-account@your-project-id.iam.gserviceaccount.com`)
    5. 選擇權限:
       * **檢視者** — 唯讀
       * **編輯者** — 讀寫
       * **擁有者** — 完整存取(不建議)
  </Step>
</Steps>

## 使用方式

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

```php theme={null}
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(開發、Staging、正式)
* 於 Google Cloud Console 監控這些帳戶的使用狀況
* 對可疑活動記錄與發出警示

## 環境變數參考

| 變數                                     | 說明                    | 範例                                        |
| -------------------------------------- | --------------------- | ----------------------------------------- |
| `GOOGLE_SERVICE_ENABLED`               | 啟用 Service Account 驗證 | `true`                                    |
| `GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION` | JSON 檔案路徑             | `storage/app/google-service-account.json` |

## 進階設定

### 將 JSON 字串儲存於環境變數

除了將 JSON 儲存為獨立檔案外,也可以將 JSON 字串儲存於環境變數。適合 GitHub Actions 等 CI/CD 環境。

**Step 1: 於 `.env` 加入 JSON 字串**

```env theme={null}
GOOGLE_SERVICE_ENABLED=true
GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION='{"type": "service_account", "project_id": "your-project-id", ...}'
```

**Step 2: 於 `config/google.php` 解析 JSON 字串**

```php theme={null}
// 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 server 可讀取

**「API not enabled」錯誤**

* 確認 Google Cloud Console 已啟用 Google Sheets API 與 Google Drive API
* 啟用 API 後等待數分鐘

**「Invalid credentials」錯誤**

* 確認 JSON 金鑰檔有效且未損壞
* 確認 Service Account 未被刪除或停用
* 確認專案 ID 與 Google Cloud 專案相符

### 設定測試

用於確認 Service Account 設定的測試路由:

```php theme={null}
// 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 驗證是否已正確設定。


## Related topics

- [Google Sheets API for Laravel](/zh-TW/packages/laravel-google-sheets/index.md)
- [OAuth 2.0 驗證 - Google Sheets API for Laravel](/zh-TW/packages/laravel-google-sheets/oauth.md)
- [驗證](/zh-TW/validation.md)
- [自訂驗證 Guard 的實作](/zh-TW/advanced/custom-auth-guard.md)
- [驗證（Verify）](/zh-TW/packages/laravel-bluesky/verify.md)
