PHP Google Search Console API "invalid_grant" response

351 Views Asked by At

I am using following PHP code to fetch data through Google Search Consonle API.

It was working fine 2 months ago but now it's showing invalid grand message instead of data. Please! need your help.

 error: '400 - {"error":"invalid_grant","error_description":"Bad Request"}'

I've right credentials included. Also you can see token is saved in file and is being fetched on demand and getting refresh too. I don't why it's stopped working.

Thanks

At the top I've added

 use Google_Client;
 use Google_Service_Webmasters_SearchAnalyticsQueryRequest;
 use Google_Service_Webmasters;

and here is the code

$siteToFetch = (!empty($site)) ? base64_decode($site) : "https://www.siteiamfulluserof.com/";


$client_id = 'XXXXXXXXXXXX-FULL-TOKEN-REMOVED';
$client_secret = 'xxxxxx-xxxxx_xxxxxxxxxxxxxxx-xxxx';
$redirect_uri = 'http://localhost/redirect_url';

$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setAuthConfig(public_path("client_secret_latest.json"));
$client->setScopes("https://www.googleapis.com/auth/webmasters", 'https://www.googleapis.com/auth/webmasters.readonly');

if (file_exists($this->tokenFile)) {
    $accessToken = json_decode(file_get_contents($this->tokenFile), true);
} else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));

    if (isset($_REQUEST['code'])) {
        $authCode = $_REQUEST['code'];
        // Exchange authorization code for an access token.
        $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
        header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));

        if (!file_exists(dirname($this->tokenFile))) {
            mkdir(dirname($this->tokenFile), 0700, true);
        }

        file_put_contents($this->tokenFile, json_encode($accessToken));
    } else {
        exit('No code found');
    }
}

$client->setAccessToken($accessToken);

// Refresh Token if expired.
if ($client->isAccessTokenExpired()) {
    $refreshTokenSaved = $client->getRefreshToken();
    $client->fetchAccessTokenWithRefreshToken($refreshTokenSaved);
}


if ($client->getAccessToken()) {

    $googleQuery = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest();

    $googleQuery->setStartDate(date('Y-m-d', strtotime('-180 days')));
    $googleQuery->setEndDate(date('Y-m-d', strtotime('-3 days')));
    $googleQuery->setDimensions(['page', 'date']);
    $googleQuery->setSearchType('web');

    try {

        $service = new Google_Service_Webmasters($client);

        $response = $service->searchanalytics->query($sitesFetched[0]["site"], $googleQuery);

        $siteData = [];

        foreach ($response as $row) {
            $siteData[] = [
                "site" => $row->keys[0],
                "date" => $row->keys[1],
                "clicks" => $row->clicks,
                "impressions" => $row->impressions,
                "ctr" => $row->ctr,
                "position" => $row->position,
            ];
        }
    } catch (\Exception $e) {
        $error = json_decode($e->getMessage());
        if ($error->error = "invalid_grant") {
            echo "You don't have proper permissions to access this site or data is being fetched.";
        }
    }
}
0

There are 0 best solutions below