Google Analytics API Login Error

I have a strange problem that I was trying to solve, but I tried all day and it just doesn't work, so I hope someone can help me with this.

I created a CMS, and after logging in, you see a panel. In this dashboard, you can click the button to connect your Google account, because I want my customers to be able to connect their Google Analytics account.

Everything works fine, I have tokens and an update token, and everything works. Even when I request the data of my user profile, I get it on my screen as an array. But when I try to get the accounts available for viewing for the connected user, I get this error:

Uncaught exception 'Google_Service_Exception' with message 'Error calling GET
https://www.googleapis.com/analytics/v3/management/accounts/~all/webproperties
key=xxxxxxxxxxxxxxxxxxxxxxxxxx: (401) Login Required'

I just don't understand why I got the "Login required" message. Below you can see my script.

require_once('/Google/Client.php');
require_once('/Google/Service/Analytics.php');

// call object
$client = new Google_Client();
$client->setApplicationName("Google Analytics - CMS title");
$client->setClientId('xxxxxxxxxxxxxxxxx');
$client->setClientSecret('xxxxxxxxxxxxxxxx');
$client->setRedirectUri('xxxxxxxxxxxxxxxxxxx');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxx');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array(
    'https://www.googleapis.com/auth/userinfo.profile',
    'https://www.googleapis.com/auth/analytics'
));

// decode
$token = $token; // this comes from my database and it json encoded

// connect
$client->setAccessToken($token);

// call service
$service    =   new Google_Service_Analytics($client);

// get accounts from analytics
$accounts   = $service->management_accounts->listManagementAccounts();

When I try to use var_dump $ accounts, I don’t see anything because the error has already occurred (login required)

I think you are going to ask me if my token is right, but that is because I tested it with other api calls .. it just does not work for this particular analytics request.

Hope someone can help me.

Thanks Pim vd Molen

UPDATE: Something really strange happened. I do not know how this is possible, but the error simply changed to another error:

Uncaught exception 'Google_Service_Exception' with message 'Error calling GET 
https://www.googleapis.com/analytics/v3/management
/accounts?key=xxxxxxxxxxxxxxxxxx: (403) Access Not Configured. 
Please use Google Developers Console to activate the API for your project.

I have enabled Google Analytics, but I don’t know which one I also need to enable.

+4
source share

Source: https://habr.com/ru/post/1523421/


All Articles