【问题标题】:Google Books API: "Cannot determine user location for geographically restricted operation."Google Books API:“无法确定地理限制操作的用户位置。”
【发布时间】:2019-07-22 11:15:38
【问题描述】:

三天以来,我在尝试访问 google book 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 设置为我可以访问的地址的解决方案,但仍然给了我“地理限制”错误消息。

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

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

在 PHP 客户端中,“class Google_Service_Books_VolumeAccessInfo extends Google_Model”中有一个 setCountry($country) 方法,但我不知道如何访问该方法。有谁知道如何解决这个问题?

【问题讨论】:

  • 我们不在这里的标题中使用“SOLVED”。您可以回答并接受您的问题,也可以删除问题
  • 虽然我确实理解将解决方案呈现为我的解决方案或删除问题的原因,因为它在不同的地方被问了很多次。如果他也在这里发帖,我会问解决它的人。

标签: php google-cloud-platform google-api-client google-books


【解决方案1】:

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

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 实例发送的每个请求中。我建议添加额外的逻辑来限制对这个请求的修改。

【讨论】:

    猜你喜欢
    • 2017-09-07
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 2019-11-05
    相关资源
    最近更新 更多