谷歌索引API错误的json文件

问题描述

您好,我正在尝试使用 Google 索引 API。我使用了本教程 - https://developers.google.com/search/apis/indexing-api/v3/prereqs

我使用了这个 PHP 库 - 不同的分支 - v1-master 因为我不使用 composer 所以我不得不使用 autoload.PHP https://github.com/googleapis/google-api-php-client/tree/master

这是我的代码

require_once($_SERVER["DOCUMENT_ROOT"] . '/assets/google-api-PHP-client/src/Google/autoload.PHP');
require_once($_SERVER["DOCUMENT_ROOT"] . '/assets/google-api-PHP-client/examples/templates/base.PHP');

$client = new Google_Client();

// service_account_file.json is the private key that you created for your service account.
$client->setAuthConfig($_SERVER["DOCUMENT_ROOT"] . '/assets/google-api-PHP-client/serviceAccount');
$client->addScope('https://www.googleapis.com/auth/indexing');

// Get a Guzzle HTTP Client
$httpClient = $client->authorize();
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';

// Define contents here. The structure of the content is described in the next step.
$content = '{
  "url": "http://example.com/jobs/42","type": "URL_UPDATED"
}';

$response = $httpClient->post($endpoint,[ 'body' => $content ]);
$status_code = $response->getStatusCode();
  1. 我创建了服务帐号
  2. 下载的服务帐户 json 文件 这是 json 的样子

enter image description here

  1. 如上所示添加了 json 的路径
  2. 我在 console.developers.google.com 中为我的项目启用了 Indexing API
  3. json 加载

但我收到错误未捕获的 Google_Exception:客户端机密 JSON 文件无效。

主题与 - google-api-php-client: Invalid client secret JSON file

但我无法解决它,我卡住了

解决方法

问题已解决,根据此处的问题 - https://github.com/googleapis/google-api-php-client/issues/2025#issuecomment-762634717,自动加载已被删除,整个包依赖于 composer 的自动加载器(如果您正在使用它)。 如果您不使用它,作者在此处指向带有自动加载器的最后一个可用版本

https://github.com/googleapis/google-api-php-client/releases/tag/v2.8.2

下载此版本并在您的代码中只包含一个 autoload.php

require_once($_SERVER["DOCUMENT_ROOT"] . '/assets/google-api-php-client/vendor/autoload.php');

完整代码在这里

require_once($_SERVER["DOCUMENT_ROOT"] . '/assets/google-api-php-client/vendor/autoload.php');

$client = new Google_Client();

// service_account_file.json is the private key that you created for your service account.
$client->setAuthConfig($_SERVER["DOCUMENT_ROOT"] . '/assets/google-api-php-client/mykey-pre-10b793743427.json');
$client->addScope('https://www.googleapis.com/auth/indexing');

// Get a Guzzle HTTP Client
$httpClient = $client->authorize();
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';

// Define contents here. The structure of the content is described in the next step.
$content = '{
  "url": "https://my-site.sk/news.php?ID=157","type": "URL_UPDATED"
}';

$response = $httpClient->post($endpoint,[ 'body' => $content ]);
$status_code = $response->getStatusCode();
return $status_code;

另外不要忘记通过单击设置 - 用户和权限 - 单击帐户旁边的点 - 单击管理所有者 - 添加新的所有者(将其添加到以前站点中的用户),将您的 json 中的 client_email 添加到 Search Console 所有者中还不够) - 你会得到 403 代码。 如果操作成功,您将获得代码 200,但在 Search Console 中不会有任何变化,因为您启动了索引作业,该作业可能会在几个小时内运行