Google Analytic API权限不足403错误

时间:2018-10-02 12:56:25

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

我使用Google Analytics(分析)Management API Account User Links: list

我正在尝试获取帐户用户列表...

try {
    $accountUserlinks = $analytics->management_accountUserLinks->listManagementAccountUserLinks('123456');
    } 
catch (apiServiceException $e) {
     print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();

} catch (apiException $e) {
    print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}

我收到以下错误

  

{“错误”:{“错误”:       [{“ domain”:“ global”,“ reason”:“ insufficientPermissions”,“ message”:“       权限不足“}],”代码“:403,”消息“:”权限不足“}}

在Google Analytics(分析)中,我设置了所有权限

编辑协作以读取和分析管理用户

例如:

$analytics->management_goals ->listManagementGoals  - work

$analytics->management_accountUserLinks>listManagementAccountUserLinks -  get 403 insufficientPermissions error

如何解决?

AnalyticsServiceProvider

class AnalyticsServiceProvider extends ServiceProvider
{
/**
 * Bootstrap the application events.
 */
public function boot()
{
    $this->publishes([
        __DIR__.'/../config/analytics.php' => 
config_path('analytics.php'),
    ]);
}

/**
 * Register the service provider.
 */
public function register()
{
    $this->mergeConfigFrom(__DIR__.'/../config/analytics.php', 
'analytics');

    $this->app->bind(AnalyticsClient::class, function () {
        $analyticsConfig = config('analytics');

        return 
    AnalyticsClientFactory::createForConfig($analyticsConfig);
    });

    $this->app->bind(Analytics::class, function () {
        $analyticsConfig = config('analytics');

        $this->guardAgainstInvalidConfiguration($analyticsConfig);

        $client = app(AnalyticsClient::class);

        return new Analytics($client, $analyticsConfig['view_id']);
    });

    $this->app->alias(Analytics::class, 'laravel-analytics');
}

protected function guardAgainstInvalidConfiguration(array 
$analyticsConfig = null)
{
    if (empty($analyticsConfig['view_id'])) {
        throw InvalidConfiguration::viewIdNotSpecified();
    }
    if 
(is_array($analyticsConfig['service_account_credentials_json'])) {
        return;
    }
    if (! 
file_exists($analyticsConfig['service_account_credentials_json'])) 
{
        throw InvalidConfiguration::credentialsJsonDoesNotExist
($analyticsConfig['service_account_credentials_json']);
    }
}
}

analytics.php

return [

/*
 * The view id of which you want to display data.
 */
'view_id' => env('ANALYTICS_VIEW_ID'),

/*
 * Path to the client secret json file. Take a look at the README 
 of this package
 * to learn how to get this file. You can also pass the credentials 
 as an array
 * instead of a file path.
 */
'service_account_credentials_json' => 
storage_path('app/analytics/service-account-credentials.json'),

/*
 * The amount of minutes the Google API responses will be cached.
 * If you set this to zero, the responses won't be cached at all.
 */
'cache_lifetime_in_minutes' => 60 * 24,

 /*
 * Here you may configure the "store" that the underlying 
 Google_Client will
 * use to store it's data.  You may also add extra parameters that 
 will
 * be passed on setCacheConfig (see docs for google-api-php- 
 client).
 *
 * Optional parameters: "lifetime", "prefix"
 */
'cache' => [
    'store' => 'file',
],
];

服务帐户凭据

 {
"type": "service_account",
"project_id": "buyers-analytic",
"private_key_id": "*****",
"private_key": "-----BEGIN PRIVATE KEY-----\*******",
"client_email": "buyeranalytic@buyers- 
analytic.iam.gserviceaccount.com",
"client_id": "***********",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": 
"https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": 
"https://www.googleapis.com/robot/v1/metadata/x509/***.iam.gservi
ceaccount.com"
}

2 个答案:

答案 0 :(得分:1)

"error":{  
   "errors":[  
      {  
         "domain":"global",
         "reason":"insufficientPermissions",
         "message":" Insufficient Permission"
      }
   ],
   "code":403,
   "message":"Insufficient Permission"
}

完全表示您无权执行您要执行的操作。

Account User Links: list需要以下作用域

Goals.list需要以下作用域。

您需要修正身份验证并请求用户的其他范围才能使用第一种方法。将其他范围添加到请求后,您将需要再次验证用户身份。

示例:

function initializeAnalytics()
{
  // Creates and returns the Analytics Reporting service object.

  // Use the developers console and download your service account
  // credentials in JSON format. Place them in this directory or
  // change the key file location if necessary.
  $KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';

  // Create and configure a new client object.
  $client = new Google_Client();
  $client->setApplicationName("Hello Analytics Reporting");
  $client->setAuthConfig($KEY_FILE_LOCATION);
  $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/analytics.manage.users.readonly']);
  $analytics = new Google_Service_Analytics($client);

  return $analytics;
}

我不确定您从哪里获得了使用的代码。我建议使用googles official samples。服务帐户需要在帐户级别授予访问权限。我已经显示了一个示例,该示例显示了如何设置范围。您只需要找到在代码中设置范围的位置,就目前为止您发布的任何内容都看不到它。我也有一些我创建的示例ServiceAccount.php

答案 1 :(得分:0)

尝试在此代码行中插入在Google Analytics(分析)帐户设置中找到的帐户ID,而不是“ 123456”:

... management_accountUserLinks->listManagementAccountUserLinks('**123456**');

此外,服务帐户还需要在帐户级别具有访问权限。