在 public 端点上使用 file_get_contents 时出现 400 错误

400 Error Using file_get_contents on public endpoint

我正在尝试访问 Coinbase 的这个端点 API:

https://api.pro.coinbase.com/currencies

注意终点是 public/unauthenticated,并且 API documentation 确认

$coinbase_coins = file_get_contents('https://api.pro.coinbase.com/currencies');
$coinbase_coins = json_decode($coinbase_coins, true);

以上代码抛出 400 错误。我正在努力解决这个问题。我可以在浏览器中很好地访问端点。我可以访问不同 API 中的其他 public 个端点,所以我认为这不是服务器上的问题。

我也尝试过 cURL,但没有成功。

有人可以偶然在 PHP 中展示一个工作示例吗?谢谢!

这似乎是服务器端问题;它在没有浏览器 UA 的情况下阻止请求。你可以设置一个,它似乎工作正常。

$ctx = stream_context_create(["http"=>["user_agent"=>"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:63.0) Gecko/20100101 Firefox/63.0"]]);
$coinbase_coins = file_get_contents('https://api.pro.coinbase.com/currencies', true, $ctx);
$coinbase_coins = json_decode($coinbase_coins, true);

print_r($coinbase_coins);