2012-01-06 15 views
2

私はfreshbooks APIでcURLを使用して周りを囲んでいます。それには、OpenAuthとトークンベースの2つの認証方法があります。トークンベースのメソッドを使用しようとしています。以前はcURLを使用しましたが、認証資格は常にXMLに渡されていました。 FreshBooksは付きphp curl header

が、それは私が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

ああ素晴らしいだろう。だから、私はちょうど$ヘッダー配列の '承認'項目を削除する必要があり、私は行くべき良いはずですか? – David

+0

マニュアルに記載されているように、パスワードをスキップすることもできます。セキュリティのために「X」を示唆するようなランダムな文字列に置き換えることができます。 – Ranty

+0

が完璧です。ありがとう! – David