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

Dosnt work examples in Management API --- exeptions


Goals: list

None of the examples work. Although the client library is installed.

At the same time, Google_Service_AnalyticsReporting works without errors.

<?php
require_once __DIR__ . '/goo/vendor/autoload.php';

$analytics = initializeAnalytics();

$VIEW_ID = "206215735";
$ACCOUNT_ID = '152594033';
$PROPERTY_ID = 'UA-152594033-1';

function initializeAnalytics()
{
    $KEY_FILE_LOCATION = __DIR__ . '/goo/My Project.json';

    $client = new Google_Client();
    $client->setApplicationName("Bottom table");
    $client->setAuthConfig($KEY_FILE_LOCATION);
    $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']);
    $analytics = new Google_Service_AnalyticsReporting($client);

    return $analytics;
}

    $goals = $analytics->management_goals->listManagementGoals($ACCOUNT_ID,$PROPERTY_ID,'~all');

Result Fatal error: Uncaught Error: Call to a member function listManagementGoals() on null in D:\OpenServer\domains\htdg.local\google1.php:30 Stack trace: #0 {main} thrown in D:\OpenServer\domains\htdg.local\google1.php on line 30

Why errors occur


Solution

  • All of the examples work. You are using the wrong service.

    Your code is using the library for the Google analytics reporting api

    $analytics = new Google_Service_AnalyticsReporting($client);
    

    Yet you are attempting to use a method which is part of the google analytics core reporting api v3 and the managment api which is in a different library.

    $analytics = new Google_Service_Analytics($client);
    

    You should probably be following the PHP tutorial for the proper api Hello Analytics API: PHP quickstart for web applications

    $client = new Google_Client();
    $client->setAuthConfig(__DIR__ . '/client_secrets.json');
    $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
    
    $analytics = new Google_Service_Analytics($client);
    $goals = $analytics->management_goals->listManagementGoals($ACCOUNT_ID,$PROPERTY_ID,'~all');