MrHappySandwich
MrHappySandwich

Reputation: 188

Webmaster Tools API

I've been having an issue with the Webmaster Tools API. I am trying to make the script have no user interaction and get information that I need. I've got Google Analytics working with Service Accounts but this isn't supported for the Webmaster Tools.

I'm currently trying to use a API Server Key however when I try to query the API it returns :

Code 403: "User does not have sufficient permission for site"

However I am owner of the site I am trying to query. I have checked www.google.com/webmasters/tools/home and the site is verified.

So I'm asking is my code correct?

$KEY_FILE_LOCATION = "privateKey.json";
$viewID = "view id"; //Website View ID - including ga:
$scopes = array(
    "https://www.googleapis.com/auth/analytics.readonly",
    "https://www.googleapis.com/auth/webmasters.readonly"
);

$emailAddr = 'Email';  //Got off google developer console
$apiKey = 'API Server Key'; //Got off google developer console

//Create Google Client
$client = new Google_Client();
$client->setApplicationName('Logging in Attempt');
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes($scopes);
$client->setAccessType('offline');
$client->setDeveloperKey($apiKey);

//Creating Webmaster Service
$webmastersService = new Google_Service_Webmasters($client);

//Creating Request
$request = new Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$request->setStartDate('2016-07-01');
$request->setEndDate('2016-07-10');
$request->setDimensions( array('query') );

$requestWebsite = 'Website'; //The website I have access to

//Querying Webmaster
$qsearch = $webmastersService->searchanalytics->query($requestWebsite, $request);

$rows = $qsearch->getRows();

echo "<pre>",print_r($rows),"</pre>";

Upvotes: 1

Views: 529

Answers (1)

MrHappySandwich
MrHappySandwich

Reputation: 188

Found out where I went wrong. The code was fine, the problem was that on the search console. The website was verified however I needed to add the email address from the Service Account into the website and gave it restricted access. Once that was in there the script worked.

Upvotes: 1

Related Questions