2015-10-05 66 views
1

的API V3我目前使用此代碼做的GET請求的搜索jQuery中:YouTube視頻搜索與使用curl返回錯誤

$.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." 
     } 
} 

如何解決呢?

+0

這是我的公開API密鑰,並被配置爲只能在配置的域上工作,所以,我沒有看到問題分享這個... – Igor

+1

您可以使用'CURLOPT_REFERER'設置標題的'Referer' – Federkun

+0

它的工作@Federico 。 Thx兄弟!作出回答,以便我可以將其標記爲已解決 – Igor

回答

2

錯誤的原因是請求需要啓用Referer。您可以通過將CURLOPT_REFERER選件添加到您的curl_setopt_array配置中進行設置。