Skip to content

Instantly share code, notes, and snippets.

@bz0
Last active October 9, 2017 07:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bz0/813d27746e40d27843ce13dc7e520fdd to your computer and use it in GitHub Desktop.
Save bz0/813d27746e40d27843ce13dc7e520fdd to your computer and use it in GitHub Desktop.
GoogleAnalyticsAPIで、ビュー情報を取得する(ウェブサイトのURL・サイト名を取得する)
<?php
class gaViewProfile{
public $clientId;
public $privateKey;
public $viewId;
public function __construct($clientId, $viewId, $privateKeyFilePath){
$this->clientId = $clientId;
$this->viewId = $viewId;
$this->privateKeyRead($privateKeyFilePath);
}
private function privateKeyRead($privateKeyFilePath){
$this->privateKey = @file_get_contents($privateKeyFilePath);
}
public function getService(){
$client = new Google_Client();
$client->setApplicationName("MyAnalyticsApp");
$analytics = new Google_Service_Analytics($client);
$cred = new Google_Auth_AssertionCredentials(
$this->clientId,
array(Google_Service_Analytics::ANALYTICS_READONLY),
$this->privateKey
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
return $analytics;
}
public function getProfile($analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
$res = array();
if (count($accounts->getItems())>0) {
$items = $accounts->getItems();
foreach($items as $i => $item){
$accountId = $item->getId();
$profiles = $analytics->management_webproperties
->listManagementWebproperties($accountId);
if (count($profiles->getItems()) > 0) {
$item = $profiles->getItems();
$json = json_encode($item);
$array = json_decode($json, true);
if ($array[0]['defaultProfileId']==$this->viewId){
$res = $array[0];
}
}
}
}
return $res;
}
}
<?php
//composerで「google/apiclient: "1.*"」をインストール要
//注意:ビューを複数設定している場合、はじめのひとつしか取得できない(未解決)
require_once 'vendor/autoload.php';
//google analytics apiの認証に利用するメルアド
$clientId = '';
//ビューID
$viewId = '';
//秘密鍵のファイルパス
$privateKeyFilePath = dirname(__FILE__) . '/xxxxxxx.p12';
$prof = new gaViewProfile($clientId, $viewId, $privateKeyFilePath);
$analytics = $prof->getService();
//ビューの情報を取得
$profile = $prof->getProfile($analytics);
print_r($profile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment