首页 > 解决方案 > 无法使用 Google API PHP 客户端验证服务帐户

问题描述

我是新手,所以我从各种官方文档中获取提示,创建了一个服务帐户等,并使用 PHP 客户端 for 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方法本身会引发错误,我不知道它到底是什么,我找不到详细的指南。有任何想法吗?

标签: google-api-php-clientservice-accountsgoogle-indexing-api

解决方案


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

您将需要切换到 Oauth2。


推荐阅读