avatar
Using Google Indexing API With Google API Tool

• Let try with Laravel project and structure the way to implement Google Indexing API. First and foremost, you need to create Service Account from Google Cloud Platform as below:

Note: In while, if you don't know about Google Cloud Platform. Let visit here.

• After you create Service Account successfully, the secret key generate as below

[email protected]

• Open Google Index API service account and create API key as JSON format.

• Access to Google Search Console, navigate to Settings > Users and permissions. We will need to ADD USER as below:

Note: Copy [email protected] and paste in the dialog. You can change Permission from Full to Owner.

• Base these manipulation above, we will save API key as JSON format into storage folder.

Note: To get google_auth_config.json in storage folder, let use storage_path('google_auth_config.json') in Laravel project.

• Sometimes, when you run LaravelGoogleIndexing::create()->update('https://flagtick.com') and will encounter issue as below:

Indexing API has not been used in project 619159056904 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/indexing.googleapis.com/overview?project=619159056904 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.

> So, you need to enable Indexing API from Google Cloud Platform.

• Define class named LaravelGoogleIndexing.php in app folder. We focus on writing logics for connection, update, delete and publish URL.

<?php

namespace App\Package\LaravelGoogle;

use Google_Client;
use Google_Service_Indexing;
use Google_Service_Indexing_UrlNotification;

class LaravelGoogleIndexing
{
    /** @var Google_Client */
    private $googleClient;

    /** @var Google_Service_Indexing */
    private $indexingService;

    public function __construct()
    {
        $this->googleClient = new Google_Client();

        $this->googleClient->setAuthConfig(config('google.auth_config'));

        foreach (config('google.scopes', []) as $scope) {
            $this->googleClient->addScope($scope);
        }

        $this->indexingService = new Google_Service_Indexing($this->googleClient);
    }

    public static function create(): self
    {
        return new static();
    }

    public function status(string $url)
    {
        return $this->indexingService
            ->urlNotifications
            ->getMetadata([
                'url' => urlencode($url),
            ]);
    }

    public function update(string $url)
    {
        return $this->publish($url, 'URL_UPDATED');
    }

    public function delete(string $url)
    {
        return $this->publish($url, 'URL_DELETED');
    }

    private function publish(string $url, string $action)
    {
        $urlNotification = new Google_Service_Indexing_UrlNotification();

        $urlNotification->setUrl($url);
        $urlNotification->setType($action);

        return $this->indexingService
            ->urlNotifications
            ->publish($urlNotification);
    }
}

• Beside, need to declare google.php file in config folder and update some advance options.

<?php

return [
    'auth_config' => storage_path('google_auth_config.json'),
    'scopes' => [
        \Google_Service_Indexing::INDEXING,
    ],
];

Note: To get value from config folder can use config method as below:

$this->googleClient->setAuthConfig(config('google.auth_config'));

• How to use it? You can use one of these methods in LaravelGoogleIndexing class. For instance:

LaravelGoogleIndexing::create()->update(URL::to('/').'/snippets/'.$snippet->slug);

• To know exactly which URL are indexing successfully? You can use method status and test as below:

Note: The type is URL_UPDATED was that means indexing successfully. In the other hand, there are some added URL recently. Then the status method throw exception as below:

[2022-12-24 10:11:57] local.ERROR: {
  "error": {
    "code": 404,
    "message": "Requested entity was not found.",
    "errors": [
      {
        "message": "Requested entity was not found.",
        "domain": "global",
        "reason": "notFound"
      }
    ],
    "status": "NOT_FOUND"
  }
}
 {"exception":"[object] (Google\\Service\\Exception(code: 404): {
  \"error\": {
    \"code\": 404,
    \"message\": \"Requested entity was not found.\",
    \"errors\": [
      {
        \"message\": \"Requested entity was not found.\",
        \"domain\": \"global\",
        \"reason\": \"notFound\"
      }
    ],
    \"status\": \"NOT_FOUND\"
  }
}

Thus, we need another method to handle new URL.

try {
    LaravelGoogleIndexing::create()->status('https://flagtick.com/snippets/using-google-indexing-api-with-google-api');
} catch (Exception $ex) {
    LaravelGoogleIndexing::create()->update('https://flagtick.com/snippets/using-google-indexing-api-with-google-api');
}

Or you can access Google Search Console and manually index URL as below:

• If you get error "Quota exceeded for quota metric 'Publish requests' and limit 'Publish requests per day' of service 'indexing.googleapis.com'". You need update your Indexing API in Google Cloud Platform to extend number of requests per day.

You need to login to do this manipulation!