4
votes

I use Google Analytics Managment API Account User Links: list

I'm trying to get the account user 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();
}

I get the following error

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

In the Google Analytics I set all permissions

Edit Collaborate Read & Analyze Manage Users

For example:

$analytics->management_goals ->listManagementGoals  - work

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

How to fix it?

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',
],
];

service-account-credentials

 {
"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
Welcome to stack i can see this is your first time here. You may want to read stackoverflow.com/help/how-to-ask. We are not a forum all of the information that you give us to help us help you must be added to your own question you should not be posting them as answers unless its an actual answer to your question. You should edit your question and add additional information.DaImTo

2 Answers

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

Means exactly that you do not have permission to do what it is you are trying to do.

Account User Links: list requires the following scopes

Goals.list requires the following scopes.

You need to fix your authentication and request additional scopes of the user in order to use the first method. Once you have added the additional scopes to your request you will then need to authenticate your user again.

Example:

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

I am not sure where you got the code you are using from. I would recommend using googles official samples. Service accounts need to have their access granted at the account level. I have shown added an example that shows how to set the scopes. You just need to find where in your code you are setting your scopes I cant see it in anything you have posted so far. I also have some samples that i have created ServiceAccount.php

0
votes

Try inserting the Account ID found in the Analytics Account Settings instead of "123456" in this line of code:

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

Also the Service Account needs to have access permissions on the account level.