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

时间:2015-10-05 19:40:14

标签: php curl youtube youtube-api youtube-data-api

我目前正在使用此代码通过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."
      }
 }

如何解决?

1 个答案:

答案 0 :(得分:2)

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