I'm having a weird issue with the Google Search Console API Client (PHP). Last night it was working (eventually) and then this morning, the exact same code is no longer working. Instead of getting Search Analytics data, I'm getting a 401 error, 'Invalid Credentials'.
Edit: I have setSubject commented out as it was working without that last night. I have tried today with that commented and uncommented and neither work.
Edit 2: I thought I had this fixed. I changed the scopes so it had both types of scope for the Search Console API. It started downloading the data again. Then an hour or two later it started returning 'Invalid Credentials' errors again. I then swapped the position of the scopes in the $scopes array and it started working again. There seems like there is something wrong somewhere.
Here is my code:
namespace App\Services;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
class Google {
private function googleApiAuthorise()
{
$client = new \Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=/keys/Tool-xxxxxxxxxx.json');
$client->useApplicationDefaultCredentials();
//$client->setSubject('bob@example.com');
$scopes = ['https://www.googleapis.com/auth/webmasters.readonly'];
$client->setScopes($scopes);
if( $client->isAccessTokenExpired()) {
$client->refreshTokenWithAssertion();
}
return $client;
}
public function getSearchAnalytics()
{
$client = Google::googleApiAuthorise();
$service = new \Google_Service_Webmasters($client);
$request = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest;
$request->setStartRow(0);
$request->setStartDate('2016-06-01');
$request->setEndDate('2016-10-02');
$request->setSearchType('web');
$request->setRowLimit(100);
$request->setDimensions(array('query','country','device','page'));
$query_search = $service->searchanalytics->query("http://www.example.com/", $request);
$rows = $query_search->getRows();
return $rows;
}
}
I then have a controller:
$result = $google->getSearchAnalytics();
var_dump($result);
When I visit the route that triggers this controller I get a 401 'Invalid Credentials'. I'd like to re-iterate that last night, this code as working and returning results for Google's Search Console API.
This is due to the fact that the google clients access token has expired. The authentication tokens work for 3600 seconds only. After that they expire and you will have to retrieve a new one using the refresh token (which was sent to you in the initial request and wich does not expire). So the problem is not at all bound to your application but to how you deal with accessing the Google API.
I am in the same situation but have not found a proper solution yet. Not sure if i have to create a new service account because i missed saving the refresh token. Tried with new keys but this did not work.