こんばんは。teratailで質問するのが初めてのため、記述に不慣れな点があるかもしれません。都度ご指摘くだされば幸いです。
■実現したいこと:
Googleアナリティクスを適用させているWordPressサイトにおいて、テーマファイル内(PHPコード記述)で記事をアナリティクスからカウントされる閲覧数順(人気順)に取得したいです。
■行ったこと、発生している事象:
-要約-
Google Develovers Consoleで作成したサービスアカウントからリクエストしてGoogleアナリティクスAPIが動くか試している。公式に配布されているサンプルコードを試したところ、「No properties found for this user.」という例外メッセージが表示される。
-詳細-
1.Google Developers Consoleで新規プロジェクトを作成して、検索窓でAnalytics APIを探して有効化しました。
2.同じくGoogle Develovers Console上で、作成したプロジェクトを選択している状態でサービスアカウントを新規作成しました。新規作成画面で現れる「2.このサービス アカウントにプロジェクトへのアクセスを許可する (省略可):このサービス アカウントに (プロジェクト名) へのアクセス権を付与して、プロジェクト内のリソースに対する特定のアクションを完了する権限を付与します。」と「3.ユーザーにこのサービス アカウントへのアクセスを許可 (省略可)」では何も入力しないで先へ進めました。
※「2.このサービス アカウントにプロジェクトへのアクセスを許可する (省略可)」の仮定で、ロールに「オーナー」を選択して先に進めてもみましたが、以降で記述するような結果と同じでした。
このサービスアカウントの「キー」のページで「鍵を追加」→jsonを選択し、鍵ファイルをローカルにダウンロードしました。
3.Google Analyticsに移動しました。「管理」画面ではすでにアカウントが一つあり、それに対して一つプロパティが紐付けられていることが分かる状態です。ここで、すでにあるアカウントに対して「アカウントのアクセス管理」を選択し、「ユーザーを追加」で、上記2で得られたサービスアカウントのメールアドレスを入力して権限は「閲覧者」とし、「データの制限」には何もチェックを入れずに「追加」を完了させました。
4.Google API Client Library for PHP のページ「https://github.com/googleapis/google-api-php-client/releases」
に移動しました。対象のWordPressサイトのPHPバージョンが7.2.34だったため、7.0のバージョンのGoogle API Client Libraryをダウンロードしました。全て展開して、フォルダごと対象のWordPress使用サーバーのwp-config、 wp-content、wp-includesなどがある場所に並列な位置関係でアップロードしました。フォルダ名は「google-api-php-client」に変更しました。
5.新規でPHPファイルを作成し、下記参考にしたサイトの1番目に記載のサンプルコード HelloAnalytics.phpをそのままコピーして、サーバー上に先程作成したClient Libraryのフォルダ内にアップロードしました。
PHP
<?php // Load the Google API PHP Client Library. require_once __DIR__ . '/vendor/autoload.php'; $analytics = initializeAnalytics(); $profile = getFirstProfileId($analytics); $results = getResults($analytics, $profile); printResults($results); function initializeAnalytics() { // Creates and returns the Analytics Reporting service object. // Use the developers console and download your service account // credentials in JSON format. Place them in this directory or // change the key file location if necessary. $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json'; // Create and configure a new client object. $client = new Google_Client(); $client->setApplicationName("Hello Analytics Reporting"); $client->setAuthConfig($KEY_FILE_LOCATION); $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); $analytics = new Google_Service_Analytics($client); 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"; } }
- 2.でダウンロードしておいた鍵ファイルを「service-account-credentials.json」という名前に変更して、同じくGoogle Client Libraryのフォルダ内にアップロードしました。
7.テーマファイルのfunction.php内、最下部に下記記述を挿入しました。
php
include(ABSPATH . 'google-api-php-client/HelloAnalytics.php');
8(結果).WordPressサイトにアクセスしたところ、下記のようなエラーメッセージが現れました。
Fatal error: Uncaught Exception: No properties found for this user. in /home/xs712760/xs712760.xsrv.jp/public_html/google-api-php-client/HelloAnalytics.php:63 Stack trace: #0 /home/xs712760/xs712760.xsrv.jp/public_html/google-api-php-client/HelloAnalytics.php(7): getFirstProfileId(Object(Google\Service\Analytics)) #1 /home/xs712760/xs712760.xsrv.jp/public_html/wp-content/themes/twentytwentyone/functions.php(644): include('/home/xs712760/...') #2 /home/xs712760/xs712760.xsrv.jp/public_html/wp-settings.php(555): include('/home/xs712760/...') #3 /home/xs712760/xs712760.xsrv.jp/public_html/wp-config.php(107): require_once('/home/xs712760/...') #4 /home/xs712760/xs712760.xsrv.jp/public_html/wp-load.php(50): require_once('/home/xs712760/...') #5 /home/xs712760/xs712760.xsrv.jp/public_html/wp-admin/admin.php(34): require_once('/home/xs712760/...') #6 /home/xs712760/xs712760.xsrv.jp/public_html/wp-admin/index.php(10): require_once('/home/xs712760/...') #7 {main} thrown in /home/xs712760/xs712760.xsrv.jp/public_html/google-api-php-client/HelloAnalytics.php on line 63
以上が試したことと発生している事象です。エラーメッセージの出る原因を究明したいです。公式のガイド(下記、参考にしたサイト1)通りに行いましたが、何か不備があったのでしょうか。Google Cloud PlatformでAPIの使用状況を見たところ、作成したサービスアカウントからリクエストが行われていることは確認できました。
ネットでエラーメッセージを検索してもほとんど引っかかる記事がなく、途方に暮れています。どうかお力添えをいただけますでしょうか。
・参考にしたサイト:
まだ回答がついていません
会員登録して回答してみよう