close

步驟1 登入Google developers Console 

Create New Project

Step1  

與其他Google API相同,設定一下分析部分權限

然後選擇建立Service accounts(Web application)

產生p12 key(私有key),然後記住產生的Email

步驟2

登入Google分析後台,點選Admin

然後選擇View->User management 

(註:account跟View是不一樣的)

 加入剛剛Service account裡面一大串的Email

這樣才可以正常存取有權限

step2  

PHP部分Code如下:

require_once APPPATH.'libraries/google-api-php-client/src/Google/autoload.php';

$client_email = '可從Google admin後台取得';
$private_key = file_get_contents('可從Google admin後台取得');
$scopes = array('https://www.googleapis.com/auth/analytics');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);

$client = new Google_Client();
$client->setAssertionCredentials($credentials);
//$analytics = new apiAnalyticsService($client);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$token = json_decode($client->getAccessToken());
$google_token = $token->access_token;

 

得到的token就是用在前端的Javascript,然後ga記得是要填View的id不是accountid

剩下的就直接參考這裡,這裡也有python 的範例

唯一要注意的是ga:後面接的是View Id

arrow
arrow

    Matt 發表在 痞客邦 留言(0) 人氣()