Google AnalyticsAPI - 无法在经过身份验证后添加服务

时间:2016-08-12 05:12:10

标签: php google-analytics google-api google-analytics-api google-api-php-client

在谷歌控制台中,我为API密钥创建了凭据 - 类型为服务器,为类型为其他的Oauth创建。

对于开发人员密钥,我使用的是API密钥凭证,对于客户端ID /秘密,我使用的是Oauth证书

我正在使用php sdk进行google analytics api:

$client = new Google_Client();
$client->setApplicationName('Schedule GA');
$client->setAccessType('offline');
$client->setUseObjects(true);

$ganalytics_settings = wp_get_custom_field_for_current_user('ganalytics_settings', 'ga_settings');

$ganalytics_settings['google_api_key'] = 'c0f3d189e82938128ndoea1a426ee4e264e4b0b0';
$ganalytics_settings['google_client_id'] = '17381202384367-gejnedh2aijuq1660f0lvl5uvj6roloo4.apps.googleusercontent.com';
$ganalytics_settings['google_client_secret'] = '**Secret key**';

$client->setClientId("17381202384367-gejnel2aijuq1060f0lvl5uvj6roloo4.apps.googleusercontent.com");
$client->setClientSecret("QclsDKOSLcsrbpJD_KLbIUtQ");
$client->setDeveloperKey("c0f3d189e82938128ndoea1a426ee4e264e4b0b0");
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$analytics = new Google_AnalyticsService($client); //the error occurs here!!!

// Setting Access Token

$access_token = $ganalytics_settings['google_access_token'];
if ($access_token) {
    $client->setAccessToken($access_token);
}
else {
    if ($ganalytics_settings['google_auth_code']) {
        $client->authenticate($ganalytics_settings['google_auth_code']);
        $ganalytics_settings['google_access_token'] = $client->getAccessToken();

        // update_option('ganalytics_settings', $ganalytics_settings);
        ga_settings_exists_else_update();
    }
}

但是,我收到以下错误消息:

Cant add services after having authenticated

有什么建议我做错了吗?

感谢您的回复!

1 个答案:

答案 0 :(得分:4)

您需要先设置范围,例如:

$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);

This教程可能会在将来帮助您。