加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Google Analytic API insufficientPermissions 403错误

发布时间:2020-12-13 16:10:50 所属栏目:PHP教程 来源:网络整理
导读:我使用Google Analytics Managment API Account User Links: list 我正在尝试获取帐户用户列表… try { $accountUserlinks = $analytics-management_accountUserLinks-listManagementAccountUserLinks('123456'); } catch (apiServiceException $e) { print
我使用Google Analytics Managment 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']);
    }
}
}

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"
}

解决方法

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

意味着你没有权限去做你想要做的事情.

Account User Links: list需要以下范围

> https://www.googleapis.com/auth/analytics.manage.users
> https://www.googleapis.com/auth/analytics.manage.users.readonly

Goals.list需要以下范围.

> https://www.googleapis.com/auth/analytics
> https://www.googleapis.com/auth/analytics.edit
> https://www.googleapis.com/auth/analytics.readonly

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

例:

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创建的样本

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读