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、ソースコード
<?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、ソースコードについての補足
- エラーメッセージは、jsonです。
- typeの「URL_UPDATED」「URL_DELETED」では、最後の「D」を忘れないように。
- Google_Http_Batchクラスの中身はこちら →https://github.com/googleapis/google-api-php-client/blob/master/src/Google/Http/Batch.php
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