Instantly share code, notes, and snippets.

Embed
What would you like to do?
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