dongyuan1983 2016-05-16 16:08
浏览 106
已采纳

如何使用google-api-php-client查询Google AnalyticsAPI

I tried use Google Analytics with google-api-php-client
I used version 1 (older, but it in Analytics Core Reporting API and API Client Library for PHP examples ) and version 2.

"google/apiclient": "1.0.*@beta": Code:

    $service_account_email = 'pd*******@crucial-subset-******.iam.gserviceaccount.com';
    $key_file_location = \Yii::getAlias('@common/data/google-analitics/DEMO PROJECT-*******.p12');

    // Create and configure a new client object.
    $client = new \Google_Client();
    $client->setApplicationName("HelloAnalytics");
    $analytics = new \Google_Service_Analytics($client);

    // Read the generated client_secrets.p12 key.
    $key = file_get_contents($key_file_location);
    $cred = new \Google_Auth_AssertionCredentials(
        $service_account_email,
        array(\Google_Service_Analytics::ANALYTICS_READONLY),
        $key
    );
    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $results = $analytics->data_ga->get(
        'ga:10****',
        '7daysAgo',
        'today',
        'ga:sessions');

Response:

Exception 'Google_Service_Exception' with message  
'Error calling GET https://www.googleapis.com/analytics/v3/data/ga?ids=ga%3A10****&start-date=7daysAgo
&end-date=today&metrics=ga%3Asessions: 
(403) User does not have any Google Analytics account.'

google/apiclient:^2.0.0@RC: Code:

$client = new \Google_Client();
    putenv('GOOGLE_APPLICATION_CREDENTIALS=' .   \Yii::getAlias('@common/data/google-         analitics/DEMO PROJECT-************.json'));
$client->useApplicationDefaultCredentials();

$user_to_impersonate = 'denis********@******.com';
$client->setSubject($user_to_impersonate);
$scopes = [\Google_Service_Analytics::ANALYTICS_READONLY];
$client->setScopes($scopes);

if( $client->isAccessTokenExpired();) {
    $client->refreshTokenWithAssertion();
}

$service = new \Google_Service_Analytics($client);
$results = $service->data_ga->get(
    'ga:******',
    '7daysAgo',
    'today',
    'ga:sessions');

Response:

Exception 'GuzzleHttp\Exception\ClientException' with message 'Client error: `POST https://www.googleapis.com/oauth2/v4/token` resulted in a `401 Unauthorized` response:
{
 "error": "unauthorized_client",
 "error_description": "Unauthorized client or scope in request."
}
  • 写回答

1条回答 默认 最新

  • douyi1779 2016-08-04 19:33
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)