Google 书籍 API:"Cannot determine user location for geographically restricted operation."

Google Books API: "Cannot determine user location for geographically restricted operation."

三天后,我在尝试访问 google 本书 api 时收到上述错误消息,尽管我的 IP 没有改变。我可以用一个简单的

在命令行上重现它

curl "https://www.googleapis.com/books/v1/volumes?q=frankenstein"

所以这不是我的代码。可以修复添加国家代码:

curl "https://www.googleapis.com/books/v1/volumes?q=frankenstein&country=DE"

现在如何在 PHP 客户端中执行此操作?

我尝试将国家/地区添加为可选参数:


$client = new Google_Client();
$client->setApplicationName("My_Project");
$client->setDeveloperKey( $google_books_api_key );
$service = new Google_Service_Books($client);
$optParams = array(
    'country' => 'DE'
);
$results = $service->volumes->listVolumes($terms, $optParams);

但这给了我

{"error": {"errors": [{"domain": "global","reason": "backendFailed","message": "Service temporarily unavailable.","locationType": other","location": "backend_flow"}],"code": 503,"message": "Service emporarily anavailable."}}

我在某处找到的将用户 IP 设置为我确实可以访问的 IP 的解决方案仍然给了我 'geographically restricted' 错误消息。

$optParams = array(
    'userIp' => '91.64.137.131'
);

我为 PHP 以外的客户找到了解决方案,例如 Java? or Ruby or C#,但他们似乎对我没有帮助。

在 PHP 客户端中 setCountry($country) 方法存在于 'class Google_Service_Books_VolumeAccessInfo extends Google_Model' 中,但我不知道如何访问该方法。有人知道怎么解决吗?

您可以通过使用中间件以类似于您共享的其他语言示例的方式完成此操作:

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Middleware;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlHandler;

// Set this value to the country you want.
$countryCode = 'DE';

$client = new Google_Client();
$client->setApplicationName("My_Project");
$client->setDeveloperKey( $google_books_api_key );
$service = new Google_Service_Books($client);
$optParams = [];

$handler = new CurlHandler;
$stack = HandlerStack::create($handler);
$stack->push(Middleware::mapRequest(function ($request) use ($countryCode) {
    $request = $request->withUri(Uri::withQueryValue(
        $request->getUri(),
        'country',
        $countryCode
    ));

    return $request;
}));
$guzzle = new Client([
    'handler' => $stack
]);

$client->setHttpClient($guzzle);

$results = $service->volumes->listVolumes($terms, $optParams);

中间件是一组用于修改请求和响应的函数。此示例添加了一个请求中间件,它会在发送请求之前将 country=$countryCode 添加到 URI 查询字符串。

此示例在一定程度上进行了简化,您需要稍作修改。最大的问题是这个中间件会将国家代码添加到从 Google_Client 的这个实例发送的 每个 请求中。我建议添加额外的逻辑来限制对这个请求的修改。