2016-09-15 50 views
1

我正在爲此工作2個小時,只是無法弄清楚什麼是錯的。我只是通過URL(帶參數)發出cURL get請求,並且響應預期會是JSON格式的某種access_token,但我不斷收到錯誤:curl_exec()函數返回false。該URL是正確的,因爲直接將準備好的URL粘貼到瀏覽器地址欄會給出適當的access_token。您可能需要知道我正在製作圖表API(Facebook)請求。下面是一些代碼:在簡單的GET請求中返回false的cURL函數

private function getAccessToken() { 
      $uri = $this->prepareTokenUri(); // getting the uri 
      echo "<strong>$uri</strong><br/>"; // printing the uri for debugging purpose 
      $this->setCurlToGet($uri); // explained below 
      $response = curl_exec($this->curl); 
      echo "<b>Here Goes Response</b>"; 
      var_dump($response); // boolean false 
      $response = json_decode($response, true); 
      $this->token_expires = $response['expires_in']; 
      $this->token_type = $response['type']; 
      return $response['access_token']; 
     } 

功能setCurlToGet()只是執行以下操作:

// call this function only when making a GET request 
private function setCurlToGet($url) { 
      $this->unsetCurl(); 
      $this->curl = curl_init(); 
      curl_setopt($this->curl, CURLOPT_URL, $url); 
      curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true); 
      return $this->curl; 
     } 

unsetCurl()方法如下:

private function unsetCurl() { 

      if(!is_null($this->curl)) { 
       curl_close($this->curl); 
       $this->curl = null; 
      } 
     } 

我已經var_dumped()應有盡有, cURL資源變量($this->curl),它實際上是一個捲曲資源變量。致電curl_exec()返回false,我只是不明白爲什麼。再一次,我想重申一下,URL沒有什麼不對,因爲當打印的URL(在行echo "<strong>$uri</strong><br/>";)被複制並粘貼到瀏覽器的地址欄中時,結果就是我需要的access_token。

如果你想看到URI的圖案prepareTokenUri()準備:

https://graph.facebook.com/v2.3/oauth/access_token?client_id={my-appid}&redirect_uri={response-handler-script-uri}&client_secret={app-secret-code}&code={a-long-code}

+3

是否'curl_error()'說明了什麼? – AbraCadaver

+0

應該理想地工作。做私人公開只是爲了檢查 –

+0

@AbraCadaver剛剛檢查過。它說'SSL證書問題:無法獲得本地簽發者證書'。現在該如何解決這件事? – Fresher

回答

2

快速修復:

這些行添加到您的setCurlToGet功能在同一地區的其他curl_setopt方法。

curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, 0); 
curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, 0); 

與此唯一的問題是,如果有人能夠使DNS去他們的服務器,而不是Facebook的從URL預期,你是不是驗證它確實是Facebook的。

所以,如果你擔心的是,正確的解決辦法:

1)https://curl.haxx.se/ca/cacert.pem

2下載cacert.pem)添加以下行爲php.ini,與在那裏你把正確的路徑上述文件

curl.cainfo=/path/to/cacert.pem 

3)刷新apache服務