> ## 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 でスコープ設定">
    ```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 が自動的に使用されます。アクセストークンの設定は不要です。

```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 を使用（開発・ステージング・本番）
* 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 サーバーが読み取れるか確認

**「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 認証が正しく設定されているか確認します。
