php - Google Analytic API insufficientPermissions 403错误

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

我使用 Google Analytics 管理 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();
}

出现以下错误

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

在 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']);
    }
}
}

分析.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"
}

最佳答案

"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

关于php - Google Analytic API insufficientPermissions 403错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52608817/

相关文章:

android analytics v4 最简化

javascript - 提交事件未触发

php - urlManager 配置中的 Yii 2 规范 URL

php - PDO 调试 - 绑定(bind)后查看查询?

python - 来自 Colab 的 Google API 问题

google-apps-script - 分析 Google App 脚本的性能

php - 使用自定义 SQL 的学说子查询

google-api - Gmail API 推送通知重复消息 ID

oauth-2.0 - 从本地主机发送请求时,Google Oauth2 redirect_uri_mismatch

python - 如何按 Google Analytics API 中的自定义参数进行过滤?