DiDebru
DiDebru

Reputation: 163

Get Google Search API PHP with google-api-client

I am trying to get gsc data via -> https://github.com/google/google-api-php-client

I am project owner at -> https://developers.google.com/

And restricted user at -> https://www.google.com/webmasters/tools/home?hl=de

I've created a service account with the role project owner at https://developers.google.com/ and stored the json on my server.

My code so far =

// Fetch GoogleSearchConsole data and store it.
  putenv('GOOGLE_APPLICATION_CREDENTIALS=' . getcwd() . '/../my-service-account-creds.json');
  $client = new Google_Client();
  $client->setApplicationName('my-project');
  $client->useApplicationDefaultCredentials();
  $client->addScope([Google_Service_Webmasters::WEBMASTERS_READONLY, Google_Service_Webmasters::WEBMASTERS]);
  $service = New Google_Service_Webmasters($client);
  $query = New Google_Service_Webmasters_SearchAnalyticsQueryRequest();
  $query->setStartDate(strtotime('2018-01-15'));
  $query->setEndDate(strtotime('2018-01-22'));
  $query->setDimensions(['page']);
  $hmm = $service->searchanalytics->query('http://www.mysite.io', $query);

The Response is always

    {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "forbidden",
    "message": "User does not have sufficient permission for site 'http://www.mysite.io/'. See also: https://support.google.com/webmasters/answer/2451999."
   }
  ],
  "code": 403,
  "message": "User does not have sufficient permission for site 'http://www.mysite.io/'. See also: https://support.google.com/webmasters/answer/2451999."
 }
}

I even get an access token if I call

$client->fetchAccessTokenWithAssertion($my_http_client);

Edit: I will test this answer and report back if I have success with it https://stackoverflow.com/a/20961008/4732699

Upvotes: 2

Views: 1012

Answers (1)

DiDebru
DiDebru

Reputation: 163

I had to add my service account to my webmasters property as user.

Upvotes: 1

Related Questions