使用 API V3 使用 curl 返回错误的 YouTube 视频搜索

YouTube videos search with the API V3 using curl returning error

我目前正在使用此代码通过 jQuery 中的 GET 请求进行搜索:

$.get("https://www.googleapis.com/youtube/v3/videos?id=c8a3_9ecqBA&key=MYAPIKEY&part=snippet,contentDetails", function(data) {
    console.log(data);
});

并且数据在控制台中正确返回。但是我想在PHP中做同样的事情(使用AJAX),所以我一直在尝试:

// Get cURL resource
$curl = curl_init();

// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => "https://www.googleapis.com/youtube/v3/videos?q=Eminem&key=MYAPIKEY&part=snippet&type=video&maxResults=20",
    CURLOPT_USERAGENT => "Simple Test"
));

// Send the request & save response to $resp
$resp = curl_exec($curl);

// Close request to clear up some resources
curl_close($curl);

echo $resp;

但响应是:

 {
  "error": {
      "errors": [
           {
              "domain": "usageLimits",
              "reason": "ipRefererBlocked",
              "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.",
              "extendedHelp": "https://console.developers.google.com"
            }
      ],
      "code": 403,
      "message": "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed."
      }
 }

如何解决?

错误原因是请求需要一个启用的Referer。您可以通过在 curl_setopt_array 配置中添加 CURLOPT_REFERER 选项来设置它。