6
7

More than 3 years have passed since last update.

【PHP(Laravel6.0)+Google Indexing API】で、URLを一括送信するArtisanコマンド作成

Last updated at Posted at 2019-12-27

1、Googleのライブラリをインストール


$ composer require google/apiclient:"^2.0"

vendor内にインストールされる。
※参照:https://github.com/googleapis/google-api-php-client

2、Google APIのコンソールから、認証情報が書かれたjsonファイルを取得

公式:https://developers.google.com/search/apis/indexing-api/v3/prereqs?hl=ja
公式のとおりにやって上手くいきました。

ただし、注意点は、「Search Console でサイトの所有権を確認する」の部分。
ここで、サイト所有者に追加するのは、自分のアカウントではなく、新しく作成したサービスアカウントです。
サービスアカウントの権限が、「フル」でなく、「オーナー」になることが必要です。

3、Artisanコマンド作成

$ php artisan make:command GoogleIndex

「GoogleIndex」は、クラス名なのでご自由に決めて下さい。
※参照:https://readouble.com/laravel/6.x/ja/artisan.html

4、ソースコード

app/Console/Commands/GoogleIndex.php
<?php

namespace App\Console\Commands;
//vendor内に入ったクラスを使う
use Google_Client;
use Google_Http_Batch;
use Google_Service_Exception;
use Google_Service_Indexing;
use Google_Service_Indexing_UrlNotification;
use Illuminate\Console\Command;

class GoogleIndex extends Command
{
    /**
     * The name and signature of the console command.
     * 好きなコマンド名を付ける
     * @var string
     */
    protected $signature = 'google:index';

    /**
     * The console command description.
     * php artisan help google:indexと打つと表示される説明
     * @var string
     */
    protected $description = 'Google IndexingAPIを利用して、指定するページをインデックスする';

     // 中略

    public function handle()
    {
        $client = new Google_Client();
        // 取得したjsonファイルを置いたパスを指定
        $client->setAuthConfig('google_config/hoge.json');
        // IndexAPIを使う場合は、このスコープをクライアントに追加
        $client->addScope("https://www.googleapis.com/auth/indexing");
        // バッチ(一括送信)を使う宣言
        $client->setUseBatch(true);
        // バッチクラスのインスタンス化
        $batch = new Google_Http_Batch($client, false, 'https://indexing.googleapis.com');

        $example_url_arr = array(
            "https://example.jp/job/1",
            "https://example.jp/job/2"
        );
        foreach ($example_url_arr as $url) {
            $postBody = new Google_Service_Indexing_UrlNotification();
            $postBody->setType('URL_UPDATED'); //登録・更新
            //$postBody->setType('URL_DELETED'); //削除
            $postBody->setUrl($url);
            $service = new Google_Service_Indexing($client);
            $request = $service->urlNotifications->publish($postBody);
            $batch->add($request);
        }
        // バッチの実行
        $results = $batch->execute();
        // エラーメッセージ出力
        $err_flg = 0;
        foreach ($results as $v) {
            if ($v instanceof Google_Service_Exception) {
                echo "---エラーメッセージ---\n", $v->getMessage(), "\n";
                $err_flg++;
            }
        }
        // 結果出力
        echo "送ったリクエスト合計数:", count($results), "\n";
        echo "エラー合計数:", $err_flg;
    }
}

※参照:https://blog.tkouen.mydns.jp/wordpress/699

5、ソースコードについての補足

6、一括送信の注意点

デフォルトの上限は、1日当たり200リクエストです。

たとえば、10 個のリクエストを 1 つの HTTP リクエストにまとめた場合、10 個のリクエストとして割り当てにカウントされます。割り当て量の増加をリクエストする場合は、申し込みが必要
申込について→https://developers.google.com/search/apis/indexing-api/v3/quota-pricing?hl=ja#request-more-quota

※引用元:https://developers.google.com/search/apis/indexing-api/v3/using-api?hl=ja#batching

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7