まいける's Tech Blog

LAMP関係のメモなどを不定期に掲載します

PHP で Google Analytics API(Service accounts版)

 Google APIs Client Library for PHP(v1.0.6beta)を使って Google Analytics API(v3) からデータを取得する方法について覚え書き。今回はサーバサイドでの処理を想定して、OAuth のクライアント種別を Service accounts にしています。ゴールは、このサンプルと同様の結果を得ることです。

 以下、コードです。

<?php

require_once 'vendor/autoload.php'; // composer の autoload.phpの場所を指定

$client_id = '(OAuth のクライアント ID を記入)';
$service_account_name = '(OAuth のメールアドレスを記入)'; //Email Address
$key_file_location = 'key.p12'; // OAuth のクライアント ID を作成したときに生成された p12 ファイルをアップロードし、その場所を指定

$client = new Google_Client();
$client->setApplicationName("Analytics_API_Examples");

$client->setClientId($client_id);

$key = file_get_contents($key_file_location);

$cred = new Google_Auth_AssertionCredentials (
    $service_account_name,
    array('https://www.googleapis.com/auth/analytics'),
    $key
);

$client->setAssertionCredentials($cred);

// 以下は上記のサンプルと同内容(Typo のみ修正)

$analytics = new Google_Service_Analytics($client);

runMainDemo($analytics);

function runMainDemo(&$analytics) {
    try {

        // Step 2. Get the user's first view (profile) ID.
        $profileId = getFirstProfileId($analytics);

        if (isset($profileId)) {

            // Step 3. Query the Core Reporting API.
            $results = getResults($analytics, $profileId);

            // Step 4. Output the results.
            printResults($results);
        }

    } catch (apiServiceException $e) {
        // Error from the API.
        print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();

    } catch (Exception $e) {
        print 'There was a general error : ' . $e->getMessage();
    }
}

function getFirstprofileId(&$analytics) {
    $accounts = $analytics->management_accounts->listManagementAccounts();

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

        $webproperties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId);

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

            $profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstWebpropertyId);

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

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

function getResults(&$analytics, $profileId) {
    return $analytics->data_ga->get(
        'ga:' . $profileId,
        '2012-03-03',
        '2012-03-03',
        'ga:sessions');
}

function printResults(&$results) {
    if (count($results->getRows()) > 0) {
        $profileName = $results->getProfileInfo()->getProfileName();
        $rows = $results->getRows();
        $sessions = $rows[0][0];

        print "<p>First view (profile) found: $profileName</p>";
        print "<p>Total sessions: $sessions</p>";

    } else {
        print '<p>No results found.</p>';
    }
}


?>

こんな感じです。

最後にはまったのは、
There was a general error : Error calling GET https://www.googleapis.com/analytics/v3/management/accounts: (403) User does not have any Google Analytics account.
のエラー。OAuth のクライアント ID を作成するときに使用している Google アカウントに Analytics の閲覧権限を与えているのに…と悩んだのですが、OAuth のメールアドレス(上記コードの $service_account_name で指定したメールアドレス)に閲覧権限を与える必要があります。冷静に考えれば当たり前なのですが、気づきにくいかもしれません。