LoginSignup
71
71

More than 5 years have passed since last update.

PHPでGoogle Analytics APIをアクセスしてみました。

Last updated at Posted at 2015-12-06

Note: 今回使ったのは google-api-php-client v1 のバージョンです。

phpからapiにアクセスし、データをブラウザーで出力できるまでのステップを書いてます。

必要なもの:
- composer
- php > 5.2
- google developerアカウント
- 使っているgoogle analyticsアカウント

Step: 1 - Google Developer Consoleでプロジェクトの作成

  • https://console.developers.google.com/ からログインします。
  • プロジェクトの作成をクリックします。 gapi-01.png  
  • プロジェクト名を記入して作成ボタンをクリックします。 gapi-02.png

Step: 2 - APIの設定

  • メニューからAPI Managerに入ります。 gapi-03.png gapi-04.png  
  • Analytics APIをクリックし APIを有効にします。 gapi-05.png gapi-06.png

Step: 3 - 認証情報の設定

  • 認証情報まだ設定してないので、このようにメッセージが出てきます。認証情報に進みます。 gapi-07.png  
  • 先にOAuth同意画面のサービス名を設定します。 gapi-08.png  
  • 次は認証情報のサービスアカウントを追加します。 gapi-09.png  
  • P12を選択してキーを作成します。 gapi-10.png  
  • 作成したプライベートキーは自動的にパソコンにダウンロードされます。(Safariで作成するときうまくダウンロードされない場合がございますのでChromeをお勧めします。)この唯一のファイルを後でphp使っているサーバーにアップロードして、PHPコードで引用します。 gapi-11.png  
  • それから、アカウントのメールアドレスも自動で作成されます。このアドレスをGoogle Analyticsの設定とPHPコード、2つの場所で使います。 gapi-12.png

Step: 4 - Google Analyticsの設定

  • https://analytics.google.com/からアカウントにログインします。
  • アナリティクス設定でPHPからアクセスしたいアカウントのユーザー管理のところに入ります。 gapi-13.png  
  • Step3で作成されたメールアドレスを「表示と分析」の権限で追加します。 gapi-14.png

Step: 5 - Composerでgoogle-api-php-clientのインストール

  • サーバーにログインし、Webrootでcomposer.jsonファイルを作成します。
composer.json
{
    "require": {
        "google/apiclient": "1.*"
    }
}
  • composer install を実行したらAPIのインストールが始まります。

(Note: composerがない場合、https://getcomposer.org/doc/00-intro.mdからcomposerをインストールするか、https://github.com/google/google-api-php-client/tree/v1-masterからソースコードを直接ダウンロードします。

Step: 6 - APIをアクセスするPHPコード

  • step3で作成したプライベートキーをアップロードし、コードで引用します。
googleanalytics.php
<?php
function getService()
{
  // Creates and returns the Analytics service object.

  // Load the Google API PHP Client Library.
  require_once 'vendor/autoload.php';

  // Use the developers console and replace the values with your
  // service account email, and relative location of your key file.
  $service_account_email = 'step3で作成されたメールアドレスを入力';
  $key_file_location = 'step3で作成されたプライベートキーの場所';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("MyAnalyticsApp");
  $analytics = new Google_Service_Analytics($client);

  // Read the generated client_secrets.p12 key.
  $key = file_get_contents($key_file_location);
  $cred = new Google_Auth_AssertionCredentials(
      $service_account_email,
      array(Google_Service_Analytics::ANALYTICS_READONLY),
      $key
  );
  $client->setAssertionCredentials($cred);
  if($client->getAuth()->isAccessTokenExpired()) {
    $client->getAuth()->refreshTokenWithAssertion($cred);
  }

  return $analytics;
}

function getFirstprofileId(&$analytics) {
  // Get the user's first view (profile) ID.

  // Get the list of accounts for the authorized user.
  $accounts = $analytics->management_accounts->listManagementAccounts();

  if (count($accounts->getItems()) > 0) {
    $items = $accounts->getItems();
    $firstAccountId = $items[0]->getId();

    // Get the list of properties for the authorized user.
    $properties = $analytics->management_webproperties
        ->listManagementWebproperties($firstAccountId);

    if (count($properties->getItems()) > 0) {
      $items = $properties->getItems();
      $firstPropertyId = $items[0]->getId();

      // Get the list of views (profiles) for the authorized user.
      $profiles = $analytics->management_profiles
          ->listManagementProfiles($firstAccountId, $firstPropertyId);

      if (count($profiles->getItems()) > 0) {
        $items = $profiles->getItems();

        // Return the first view (profile) ID.
        return $items[0]->getId();

      } else {
        throw new Exception('No views (profiles) found for this user.');
      }
    } else {
      throw new Exception('No properties found for this user.');
    }
  } else {
    throw new Exception('No accounts found for this user.');
  }
}

function getResults(&$analytics, $profileId) {
  // Calls the Core Reporting API and queries for the number of sessions
  // for the last seven days.
   return $analytics->data_ga->get(
       'ga:' . $profileId,
       '7daysAgo',
       'today',
       'ga:sessions');
}

function printResults(&$results) {
  // Parses the response from the Core Reporting API and prints
  // the profile name and total sessions.
  if (count($results->getRows()) > 0) {

    // Get the profile name.
    $profileName = $results->getProfileInfo()->getProfileName();

    // Get the entry for the first entry in the first row.
    $rows = $results->getRows();
    $sessions = $rows[0][0];

    // Print the results.
    print "First view (profile) found: $profileName\n";
    print "Total sessions: $sessions\n";
  } else {
    print "No results found.\n";
  }
}

$analytics = getService();
$profile = getFirstProfileId($analytics);
$results = getResults($analytics, $profile);
printResults($results);

?>
  • ファイルを保存して、ブラウザーから http://webrootの場所/googleanalytics.php にアクセスしたら、First view (profile) found: アナリティクスのビューID Total sessions: 合計セッション数 が表示されます。
return $analytics->data_ga->get(
       'ga:' . $profileId,
       '7daysAgo',
       'today',
       'ga:sessions');

は、最初見つかったアナリティクスビューの先週分のセッション数をゲットします。
別のビューのデータを見る場合、$profileIdをそのビューのIDに変わります。

他のプロパティをゲットする場合もこちらのパラメータを変更することができます。

Dimensions&Metricsプロパティ参考:https://developers.google.com/analytics/devguides/reporting/core/dimsmets

71
71
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
71
71