Php/GooglePlayApi
提供: 初心者エンジニアの簡易メモ
準備
gcpでサービスアカウントを作成し鍵を作る
- GoogleCloudPlatform(https://console.cloud.google.com/ )で、IAMと管理 / サービスアカントを開く
- 上にある"サービスアカウントを作成する"を選択
- サービスアカウント名に、わかりやすく例えば"purchase"などといれて、apiを作る。(例:purchase@appname1.iam.gserviceaccount.com)
- 上のタブから鍵を選択し、"キーを追加"から"新しい鍵"を選択してJSONを選択
- サービスアカウントJSONファイルが、DLされるので、保存しておく
gcpでGoogle Play Android Developer APIを有効に
- GoogleCloudPlatform(https://console.cloud.google.com/ )で、"APIとサービス"を選択
- ライブラリを選択し、"Google Play Android Developer API"で検索し、でてきたものを有効にする
PlayConsoleにサービスアカウントの権限を追加
- PlayConsole( https://play.google.com/console/developers )のユーザーと権限を開く
- "新しいユーザを招待"を選択して、上の項目で作った、サービスアカウント(例:purchase@appname1.iam.gserviceaccount.com)を追加する
- 権限の項目のアプリ追加を選択し、売上を見たいアプリを選択する
- その歳、"アプリ情報の閲覧(読み取り専用)"、"売上データの表示"、"注文と定期購入"の管理の3つにチェックを付ける
GooglePlayの売上APIにアクセスするphp
- 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のアプリのパッケージ名
$productId = 'your_product_id'; // 取得したい製品のID(例: 月額サブスクリプションや消耗品のID)
$purchaseToken = 'your_purchase_token'; // 購入トークン
// Google APIクライアントの初期化
putenv("GOOGLE_APPLICATION_CREDENTIALS=$serviceAccountPath");
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/androidpublisher');
// Android Publisher APIにアクセス
$service = new Google_Service_AndroidPublisher($client);
try {
// 製品の購入情報を取得
$purchase = $service->purchases_products->get($packageName, $productId, $purchaseToken);
// 購入情報を表示
echo "✅ 購入情報を取得しました:\n";
print_r($purchase);
} catch (Google_Service_Exception $e) {
echo "❌ Google API エラー: " . $e->getMessage() . "\n";
echo "詳細: " . $e->getErrors()[0]['message'] . "\n";
} catch (Exception $e) {
echo "❌ エラー: " . $e->getMessage() . "\n";
}
"エラー: Invalid bucket name: "とでたら
index.phpの$bucketNameに設定した値が、間違えてるので、pubsite_prod_[数字]な感じになってるか、確認する。
"Google Play Android Developer API has not been used in project" エラーと出るとき
- GoogleCloudPlatformの"APIとサービス"を選択
- ライブラリを選択し、"Google Play Android Developer API"で検索し、でてきたものを有効にする
"The current user has insufficient permissions to perform the requested operation."エラーが出るとき
エラー詳細
Google API エラー: {
"error": {
"code": 401,
"message": "The current user has insufficient permissions to perform the requested operation.",
"errors": [
{
"message": "The current user has insufficient permissions to perform the requested operation.",
"domain": "androidpublisher",
"reason": "permissionDenied"
}
]
}
}
