Search code examples
phpgoogle-apigoogle-oauthgoogle-analytics-apigoogle-api-php-client

Google Analytics API V4 does not work with GA4 account


Is it possible to get data from new Google Analytics (GA4) accounts through API V4? It always returns the following error message:

{ "error": { "code": 403, "message": "User does not have sufficient permissions for this profile.", "errors": [ { "message": "User does not have sufficient permissions for this profile.", "domain": "global", "reason": "forbidden" } ], "status": "PERMISSION_DENIED" } }

I can do it perfectly on UA accounts.

Is there any API (web server request - OAuth) specific to this new account type?

property id

Here is the code used (PHP):

require_once __DIR__ . '/vendor/autoload.php';

session_start();

$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/FILE.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);

$client->setAccessToken($_SESSION['access_token']);
$analytics = new Google_Service_AnalyticsReporting($client);
$response = getReport($analytics);
printResults($response);

function getReport($analytics){
    
    $dateRange = new Google_Service_AnalyticsReporting_DateRange();
    $dateRange->setStartDate("7daysAgo");
    $dateRange->setEndDate("today");
    
    $sessions = new Google_Service_AnalyticsReporting_Metric();
    $sessions->setExpression("name");
    $sessions->setAlias("sessions");
    
    $request = new Google_Service_AnalyticsReporting_ReportRequest();
    $request->setViewId('307566943');
    $request->setDateRanges($dateRange);
    $request->setMetrics(array($sessions));
    
    $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
    $body->setReportRequests( array( $request) );
    
    return $analytics->reports->batchGet( $body );
    
}

Solution

  • User does not have sufficient permissions for this profile

    Means that the user you have authenticated your application with. Does not have permission to access the Google analytics view you are trying to extract data from.

    The issue can also be caused if you are trying to use the Google Analytics Reporting API with a Google Analytics GA4 account. As GA4 property IDs are not the same as UA view IDs, the system gets confused and assumes you just don't have access.

    The solution is to authenticate the app with a user that has access to that view or grant the user access. And to check that you are using the correct API for the type of Google Analytics you are trying to access.

    UA vs GA4

    Also remember that to extract dates from a GA4 account, you need to use the Google Analytics Data API. If you have extracted data from UA accounts, you have been using the Google Analytics Reporting API. These are two completely different APIs with different methods.

    Google Analytics Data API Quick Start

    require 'vendor/autoload.php';
    
    use Google\Analytics\Data\V1beta\BetaAnalyticsDataClient;
    use Google\Analytics\Data\V1beta\DateRange;
    use Google\Analytics\Data\V1beta\Dimension;
    use Google\Analytics\Data\V1beta\Metric;
    
    /**
     * TODO(developer): Replace this variable with your Google Analytics 4
     *   property ID before running the sample.
     */
    $property_id = 'YOUR-GA4-PROPERTY-ID';
    
    // Using a default constructor instructs the client to use the credentials
    // specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
    $client = new BetaAnalyticsDataClient();
    
    // Make an API call.
    $response = $client->runReport([
        'property' => 'properties/' . $property_id,
        'dateRanges' => [
            new DateRange([
                'start_date' => '2020-03-31',
                'end_date' => 'today',
            ]),
        ],
        'dimensions' => [new Dimension(
            [
                'name' => 'city',
            ]
        ),
        ],
        'metrics' => [new Metric(
            [
                'name' => 'activeUsers',
            ]
        )
        ]
    ]);
    
    // Print results of an API call.
    print 'Report result: ' . PHP_EOL;
    
    foreach ($response->getRows() as $row) {
        print $row->getDimensionValues()[0]->getValue()
            . ' ' . $row->getMetricValues()[0]->getValue() . PHP_EOL;
    }
    

    Load credentials file directly

    // Authenticate using a keyfile path
    $client = new BetaAnalyticsDataClient([
        'credentials' => $service_account_key_file_path
    ]);