質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Google Cloud Platform

Google Cloud Platformは、Google社がクラウド上で提供しているサービス郡の総称です。エンドユーザー向けサービスと同様のインフラストラクチャーで運営されており、Webサイト開発から複雑なアプリ開発まで対応可能です。

Google Analytics

Google AnalyticsはGoogleが開発した無料のウェブ分析のソリューションです。複数のクライアント側のAPIとデータをエクスポートし管理するREST APIも格納されています。

WordPress

WordPressは、PHPで開発されているオープンソースのブログソフトウェアです。データベース管理システムにはMySQLを用いています。フリーのブログソフトウェアの中では最も人気が高く、PHPとHTMLを使って簡単にテンプレートをカスタマイズすることができます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Google Analytics API

Google Analytics APIは、アクセス解析機能が行える API(Application Programming Interface)です。

Q&A

解決済

1回答

927閲覧

PHPコードを用いたGoogle Analytics API導入におけるサービスアカウント認証について

chibi_fish

総合スコア1

Google Cloud Platform

Google Cloud Platformは、Google社がクラウド上で提供しているサービス郡の総称です。エンドユーザー向けサービスと同様のインフラストラクチャーで運営されており、Webサイト開発から複雑なアプリ開発まで対応可能です。

Google Analytics

Google AnalyticsはGoogleが開発した無料のウェブ分析のソリューションです。複数のクライアント側のAPIとデータをエクスポートし管理するREST APIも格納されています。

WordPress

WordPressは、PHPで開発されているオープンソースのブログソフトウェアです。データベース管理システムにはMySQLを用いています。フリーのブログソフトウェアの中では最も人気が高く、PHPとHTMLを使って簡単にテンプレートをカスタマイズすることができます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Google Analytics API

Google Analytics APIは、アクセス解析機能が行える API(Application Programming Interface)です。

0グッド

0クリップ

投稿2022/05/23 15:45

こんばんは。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

1<?php 2 3// Load the Google API PHP Client Library. 4require_once __DIR__ . '/vendor/autoload.php'; 5 6$analytics = initializeAnalytics(); 7$profile = getFirstProfileId($analytics); 8$results = getResults($analytics, $profile); 9printResults($results); 10 11function initializeAnalytics() 12{ 13 // Creates and returns the Analytics Reporting service object. 14 15 // Use the developers console and download your service account 16 // credentials in JSON format. Place them in this directory or 17 // change the key file location if necessary. 18 $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json'; 19 20 // Create and configure a new client object. 21 $client = new Google_Client(); 22 $client->setApplicationName("Hello Analytics Reporting"); 23 $client->setAuthConfig($KEY_FILE_LOCATION); 24 $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); 25 $analytics = new Google_Service_Analytics($client); 26 27 return $analytics; 28} 29 30function getFirstProfileId($analytics) { 31 // Get the user's first view (profile) ID. 32 33 // Get the list of accounts for the authorized user. 34 $accounts = $analytics->management_accounts->listManagementAccounts(); 35 36 if (count($accounts->getItems()) > 0) { 37 $items = $accounts->getItems(); 38 $firstAccountId = $items[0]->getId(); 39 40 // Get the list of properties for the authorized user. 41 $properties = $analytics->management_webproperties 42 ->listManagementWebproperties($firstAccountId); 43 44 if (count($properties->getItems()) > 0) { 45 $items = $properties->getItems(); 46 $firstPropertyId = $items[0]->getId(); 47 48 // Get the list of views (profiles) for the authorized user. 49 $profiles = $analytics->management_profiles 50 ->listManagementProfiles($firstAccountId, $firstPropertyId); 51 52 if (count($profiles->getItems()) > 0) { 53 $items = $profiles->getItems(); 54 55 // Return the first view (profile) ID. 56 return $items[0]->getId(); 57 58 } else { 59 throw new Exception('No views (profiles) found for this user.'); 60 } 61 } else { 62 throw new Exception('No properties found for this user.'); 63 } 64 } else { 65 throw new Exception('No accounts found for this user.'); 66 } 67} 68 69function getResults($analytics, $profileId) { 70 // Calls the Core Reporting API and queries for the number of sessions 71 // for the last seven days. 72 return $analytics->data_ga->get( 73 'ga:' . $profileId, 74 '7daysAgo', 75 'today', 76 'ga:sessions'); 77} 78 79function printResults($results) { 80 // Parses the response from the Core Reporting API and prints 81 // the profile name and total sessions. 82 if (count($results->getRows()) > 0) { 83 84 // Get the profile name. 85 $profileName = $results->getProfileInfo()->getProfileName(); 86 87 // Get the entry for the first entry in the first row. 88 $rows = $results->getRows(); 89 $sessions = $rows[0][0]; 90 91 // Print the results. 92 print "First view (profile) found: $profileName\n"; 93 print "Total sessions: $sessions\n"; 94 } else { 95 print "No results found.\n"; 96 } 97} 98
  1. 2.でダウンロードしておいた鍵ファイルを「service-account-credentials.json」という名前に変更して、同じくGoogle Client Libraryのフォルダ内にアップロードしました。

7.テーマファイルのfunction.php内、最下部に下記記述を挿入しました。

php

1include(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の使用状況を見たところ、作成したサービスアカウントからリクエストが行われていることは確認できました。

ネットでエラーメッセージを検索してもほとんど引っかかる記事がなく、途方に暮れています。どうかお力添えをいただけますでしょうか。

・参考にしたサイト:

  1. https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/service-php?hl=ja

  2. https://www.karakaram.com/google-analytics-api-batch/#create-new-project

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

新出のGoogle Analytics Data API(GA4)をドキュメントを参考に使用したところ、解決しました。

投稿2023/03/02 10:38

chibi_fish

総合スコア1

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問