LoginSignup
4
3

More than 5 years have passed since last update.

XAMPP(OS X MAC 向け)v5.6.15でのGoogle Analytics APIの利用手順(公式:チュートリアル)備忘録(PHP)※Composerを使いません

Posted at

前提

  • XAMPPのバージョン 5.6.15
  • 使用PC MAC
  • ローカル環境のみ検証

XAMPPでGoogle Analytics APIをPHPから叩こうと思ったら、いきなりつまずいたので、備忘録として残しておきます。参考にしてください。

つまずいた内容

  • そもそもComposerを導入していない(Google公式ページではComposerの利用が前提説明)
  • Composerでライブラリの依存関係をインストールしていないため、venderというフォルダが存在しない。
  • google-api-php-clientをGitHubからDLしても直下にautoload.phpが無い
  • XAMPP内(特にhtdocs)のPermission設定が変
  • XAMPP内で完結するかとおもいきやMacのプライベートゾーン(隠しフォルダ)に勝手にmkdir(PHPからのディレクトリ生成)するので、これまたPermission問題
  • autoload.phpのディレクトリ移動予告によるPHPからのwarningが出る。

ざっとこれだけのために結構な時間を費やしてしまいました。

おおよそ、AWS・GDなどのIaaS環境やルート権限をバリバリ弄くれる環境と人なら、
エラー出るたびにすぐ対処できると思います。

気をつけていただきたい内容

Composerを使用しません。する場合はGoogle公式ページのほうが早いでしょう。Qitta参考ページ

後半でMAC自体のプライベートゾーンフォルダのPermission(権限)を開放します。
このフォルダには、Mac OS自体の重要なフォルダになっていますので、間違って削除してしまわないように気をつけてください。
backup(TimeMachine等)は事前におこなってください。

手順

略Google Developer:GD

  • Google公式 or Qitta参考ページより、下記を実行する
    • GDコンソールより、API有効化
    • サービスアカウントキー生成(秘密鍵P12タイプ)
    • サービスアカウントのメールアドレス(GD)の取得
    • GoogleAnalyticsコンソール画面より、メールアドレス(GD)の登録
    • GoogleAnalyticsコンソール画面より、ビューIDを取得
    • 他・・・
  1. XAMPPのhtdocsの権限をすべて開放します。(今回はすべて権限0777)にしました。(~$ chmod -R 777 /Applications/XAMPP/htdocs)
  2. Terminalから、/var/folderまでチェンジディレクトリコマンド(~$ cd /var/folders)まで行き、ndフォルダmd5形式名の隠しフォルダ(例:a1q2sw3ed4rf5tg6yh7uj8ik9的なSomething)右クリック情報情報を見る→下段の「共有とアクセス権」のEVERYONEの権限を読み/書きに変更
  3. google-api-php-clientのv1-masterをダウンロード
  4. 任意のXAMPPDirectoryに3でダウンロードし解凍したものと、P12キーファイルをおいてください。そして適当な(ga.phpなど).phpファイルを生成してください。
  5. 下記を設定してphpファイルにブラウザよりアクセスするとAPIが利用できます。
ga.php
<?php
function getService()
{
  // Creates and returns the Analytics service object.
  // Load the Google API PHP Client Library.
  require_once 'google-api-php-client/src/Google/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 = '<Replace with your service account email address.>';
  $key_file_location = '<Replace with /path/to/generated/client_secrets.p12>';
  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("HelloAnalytics");
  $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);
?>

Google公式チュートリアルより引用

4
3
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
4
3