2012-01-06 158 views
2

我試圖圍繞使用cURL與freshbooks API的頭部。它有兩種認證方式:基於OpenAuth和令牌。我試圖使用基於令牌的方法。我之前使用過cURL,但我的身份驗證憑據始終在傳遞的xml中。php捲曲標題

隨着新書,似乎我需要通過cURL請求頭的憑據...我認爲。以下是使用OpenAuth方法的一些示例代碼。使用基於令牌的身份驗證,我只是想通過用戶名和密碼。

如何正確地將我的憑據傳遞給我的cURL請求?

http://developers.freshbooks.com/authentication-2/#TokenBased

private function buildAuthHeader() 
    { 
     $params = array(
      'oauth_version' => '1.0', 
      'oauth_consumer_key' => $this->oauth_consumer_key, 
      'oauth_token' => $this->oauth_token, 
      'oauth_timestamp' => time(), 
      'oauth_nonce' => $this->createNonce(20), 
      'oauth_signature_method' => 'PLAINTEXT', 
      'oauth_signature' => $this->oauth_consumer_secret. '&' .$this->oauth_token_secret 
     ); 

     $auth = 'OAuth realm=""'; 
     foreach($params as $kk => $vv) 
     { 
      $auth .= ','.$kk . '="' . urlencode($vv) . '"'; 
     } 

     return $auth; 
    } 


    public function post($request) 
    { 
     $this->fberror = NULL; 
     $headers = array(
        'Authorization: '.$this->buildAuthHeader().'', 
        'Content-Type: application/xml; charset=UTF-8', 
        'Accept: application/xml; charset=UTF-8', 
        'User-Agent: My-Freshbooks-App-1.0'); 

     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, $this->apiUrl()); 
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
     curl_setopt($ch, CURLOPT_POST, 1); 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $request); 

     $response = curl_exec($ch); 
     curl_close($ch); 
     $response = new SimpleXMLElement($response); 

     if($response->attributes()->status == 'ok') 
      return $response; 
     else if($response->attributes()->status == 'fail' || $response->fberror)  
      throw new FreshbooksAPIError($response->error); 
     else throw new FreshbooksError('Oops, something went wrong. :('); 
    } 

回答

4

curl -u命令行例如,在你的鏈接頁面僅僅是使用HTTP基本身份驗證,其中令牌的用戶名。等效的phpcurl將是

curl_setopt($ch, CURLOPT_USERPWD, "$token:$password"); 
+0

哦真棒。所以我應該刪除$ header數組中的'authorization'項目,我應該很好走? – David 2012-01-06 04:20:02

+0

您甚至可以跳過密碼,如手冊中所述。出於安全考慮,它可以用隨機字符串替換,就像他們爲「X」所示的那樣。 – Ranty 2012-01-06 04:27:15

+0

完美。我得到了它的工作,謝謝! – David 2012-01-06 04:28:02