2012-01-06 159 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