facebook twitter hatena line email

Php/GooglePlayApi

提供: 初心者エンジニアの簡易メモ
2025年3月21日 (金) 17:36時点におけるAdmin (トーク | 投稿記録)による版 (ページの作成:「==準備== ===gcpでサービスアカウントを作成し鍵を作る=== #GoogleCloudPlatform(https://console.cloud.google.com/)で、IAMと管理 / サービスアカ...」)

(差分) ←前の版 | 最新版 (差分) | 次の版→ (差分)
移動: 案内検索

準備

gcpでサービスアカウントを作成し鍵を作る

  1. GoogleCloudPlatform(https://console.cloud.google.com/)で、IAMと管理 / サービスアカントを開く
  2. 上にある"サービスアカウントを作成する"を選択
  3. サービスアカウント名に、わかりやすく例えば"purchase"などといれて、apiを作る
  4. 上のタブから鍵を選択し、"キーを追加"から"新しい鍵"を選択してJSONを選択
  5. サービスアカウントJSONファイルが、DLされるので、保存しておく

GooglePlayの売上APIにアクセスするphp

  1. google/apiclientのライブラリを持つプロジェクトを作成
$ composer require google/apiclient

index.php

<?php
require 'vendor/autoload.php'; // ComposerでインストールしたGoogle APIクライアントを読み込む
// 設定
$serviceAccountPath = '/path/to/your-service-account.json'; // サービスアカウントJSONのパス
$packageName = 'com.example.yourapp'; // Google Playのアプリのパッケージ名
$reportType = 'salesreport'; // レポートの種類(売上レポート)
$reportDate = date('Ymd', strtotime('-1 day')); // 昨日の日付のレポートを取得
$bucketName = 'pubsite_prod_xxxxxx'; // Google Cloud Storage のバケット名(Google Play Console レポートのダウンロード売上にCloudStorageURIがあるのでそれのpubsite_~xxxx部分をコピペ)
$objectName = "sales/salesreport_$reportDate.csv"; // レポートのファイル名

// Google APIクライアントの初期化
putenv("GOOGLE_APPLICATION_CREDENTIALS=$serviceAccountPath");

$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(Google_Service_Storage::DEVSTORAGE_READ_ONLY);

// Google Cloud Storage にアクセス
$storage = new Google_Service_Storage($client);

try {
    // 売上レポートをダウンロード
    $file = $storage->objects->get($bucketName, $objectName, ['alt' => 'media']);
    
    // レポートの内容を取得
    $reportData = $file->getBody()->getContents();
    
    // CSVファイルとして保存
    file_put_contents("salesreport_$reportDate.csv", $reportData);
    
    echo "✅ 売上レポートを取得しました: salesreport_$reportDate.csv\n";

} catch (Exception $e) {
    echo "❌ エラー: " . $e->getMessage() . "\n";
}

"エラー: Invalid bucket name: "とでたら

index.phpの$bucketNameに設定した値が、間違えてるので、pubsite_prod_xxxxxxな感じになってるか、確認する。