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


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选项来设置它。