facebook twitter hatena line email

Php/GooglePlayApi

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

準備

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

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

gcpでGoogle Play Android Developer APIを有効に

  1. GoogleCloudPlatform(https://console.cloud.google.com/ )で、"APIとサービス"を選択
  2. ライブラリを選択し、"Google Play Android Developer API"で検索し、でてきたものを有効にする

PlayConsoleにサービスアカウントの権限を追加

  1. PlayConsole( https://play.google.com/console/developers )のユーザーと権限を開く
  2. "新しいユーザを招待"を選択して、上の項目で作った、サービスアカウント(例:purchase@appname1.iam.gserviceaccount.com)を追加する
  3. 権限の項目のアプリ追加を選択し、売上を見たいアプリを選択する
  4. その際、"アプリ情報の閲覧(読み取り専用)"、"売上データの表示"、"注文と定期購入"の管理の3つにチェックを付ける。
  5. アカウント権限タブじゃなくて、アプリ権限の指定アプリの詳細の方に権限がついてることを確認。

参考:https://zenn.dev/altiveinc/articles/how-to-google-service-account

参考:https://blog.sat.ne.jp/2025/01/24/google-play-developer-api%E3%82%92%E5%88%A9%E7%94%A8%E3%81%97%E3%81%9F%E3%83%AC%E3%82%B7%E3%83%BC%E3%83%88%E6%A4%9C%E8%A8%BC%E3%81%AE%E5%AE%9F%E8%A3%851/

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のアプリのパッケージ名
$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";
}

成功したとき

購入情報を取得しました:
Google\Service\AndroidPublisher\ProductPurchase Object
(
    [internal_gapi_mappings:protected] => Array
        (
        )

    [modelData:protected] => Array
        (
        )

    [processed:protected] => Array
        (
        )

    [acknowledgementState] => 1
    [consumptionState] => 1
    [developerPayload] =>
    [kind] => androidpublisher#productPurchase
    [obfuscatedExternalAccountId] =>
    [obfuscatedExternalProfileId] =>
    [orderId] => GPA.xxxx-xxxx-xxxx-xxxxx
    [productId] =>
    [purchaseState] => 0
    [purchaseTimeMillis] => 1742661667350
    [purchaseToken] =>
    [purchaseType] => 0
    [quantity] =>
    [refundableQuantity] =>
    [regionCode] => JP
)

参考:https://blog.sat.ne.jp/2025/01/30/google-play-developer-api%e3%82%92%e5%88%a9%e7%94%a8%e3%81%97%e3%81%9f%e3%83%ac%e3%82%b7%e3%83%bc%e3%83%88%e6%a4%9c%e8%a8%bc%e3%81%ae%e5%ae%9f%e8%a3%852/

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

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

"Google Play Android Developer API has not been used in project" エラーと出るとき

  1. GoogleCloudPlatformの"APIとサービス"を選択
  2. ライブラリを選択し、"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"
      }
    ]
  }
}

android端末で決済情報を受け取って、purchaseTokenを渡してるか確認。

数日待つ必要があるかもしれない。

参考:https://pakapaka.jp/inapp-google-auth-error-401/

参考:https://stackoverflow.com/questions/52451445/getting-401-response-in-google-developer-api-only-when-query-get-subscriptions

purchase_tokenは1時間有効。

参考:https://qiita.com/k1nakayama/items/395aa655c9f311d2efac

権限を付与したりサービス アカウントにリンクしたりする前にアプリ内製品を追加した場合は、「アプリ内製品」を開いて何かを変更する必要があるという情報もある。

参考:https://stackoverflow.com/questions/43536904/google-play-developer-api-the-current-user-has-insufficient-permissions-to-pe

"The document type is not supported."エラーが出るとき

Google API エラー: {
  "error": {
    "code": 404,
    "message": "The document type is not supported.",
    "errors": [
      {
        "message": "The document type is not supported.",
        "domain": "androidpublisher",
        "reason": "unsupportedDocType",
        "location": "token",
        "locationType": "parameter"
      }
    ]
  }
}

詳細: The document type is not supported.

定額課金のときに401エラー状態になって、ロールを選択から、"トークン作成者"で検索して、"サービスアカウント トークン作成者"を選択して、完了ボタンを押して追加すると、404のこのエラーが発生するようになった。そこからproductIdを都度課金に変更したら、成功してエラー解決した。