无法使用 Google API PHP 客户端验证服务帐户

时间:2021-08-01 15:23:15

标签: google-api-php-client service-accounts google-indexing-api

我是新手,所以我从各种官方文档中得到提示,创建了一个服务帐户等,并使用 PHP 客户端为 Google API 使用该服务帐户的凭据 JSON 发出 HTTP 请求。

但我不确定出了什么问题,它只是不起作用(对于上下文,我正在尝试使用索引 API - https://developers.google.com/search/apis/indexing-api/v3/prereqs#php

require_once ABSPATH . '/googlelibraries/google-api-php-client/vendor/autoload.php';

$client = new Google_Client();
$serviceKeyFile = __DIR__ . '/daxxxxx-b1xxxxxxc8.json';
$client->setAuthConfig( $serviceKeyFile );
$client->useApplicationDefaultCredentials();

$client->setSubject( 'ixxxxxxxxn@gmail.com' );
$client->addScope('https://www.googleapis.com/auth/indexing');
$client->setAccessType('offline');
// $client->createApplicationDefaultCredentials();
// $client->setClientId( '10xxxxxxxxxxx' );
$endpoint = 'https://indexing.googleapis.com/v3/urlNotifications:publish';

这就是我所拥有的,与示例文档中的几乎相同,但是,当我调用 $client->authorize() 来让 Guzzle 客户端进行身份验证以发出请求时,我什么也没看到,一切都变成空白,没有错误,我可以稍后调试它,错误就像 -

Fatal error: Uncaught Exception: Magic request methods require a URI and optional options array
in /var/www/html/googlelibraries/google-api-php-client/vendor/guzzlehttp/guzzle/src/Client.php on line 84

我不在乎它是否通过身份验证,现在的问题是 authorize 方法本身会抛出一个错误,我不知道它到底是什么,没有详细的指南,我会寻找。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

并非所有 google api 都支持服务帐户身份验证。您似乎正在尝试使用索引 api。如果你查看文档 #OAuth2Authorizing 你会发现它只提到了 Oauth2 授权,这是因为这个 api 不支持服务帐户授权。

您需要切换到 Oauth2。