为什么我会收到错误 "This service requires an API key"?

Why I get error "This service requires an API key"?

我正在尝试使用以下 PHP 代码将 post 请求发送到 Google 个地方 API,但出现错误

string(141) "{ "error_message" : "This service requires an API key.", "html_attributions" : [], "results" : [], "status" : "REQUEST_DENIED" } "

<?php
include_once 'configuration.php';

$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json';
$data = array('query' => 'restaurants in Sydney', 'key' => API_KEY);

$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

问题出在哪里?

documentation of text search所述,参数需要在GET方法中。您将其提供为 POST.

A Text Search request is an HTTP URL of the following form:

    https://maps.googleapis.com/maps/api/place/textsearch/output?parameters

...

Certain parameters are required to initiate a search request. As is standard in URLs, all parameters are separated using the ampersand (&) character.

试试这个片段:

<?php
include_once 'configuration.php';

$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=' . urlencode('restaurants in Sydney') . '&key=' . API_KEY;

$result = file_get_contents($url);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

要使用数组参数,请将 $url 更改为:

$data = array('query' => 'restaurants in Sydney', 'key' => API_KEY);
$url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?' . http_build_query($data);