2

我正在尝试将 cURL 与freshbooks API 一起使用。它有两种身份验证方式:OpenAuth 和基于令牌。我正在尝试使用基于令牌的方法。我以前使用过 cURL,但我的身份验证凭据一直在传递的 xml 中。

对于新书,我似乎需要在 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

1 回答 1

4

链接页面中的curl -u命令行示例只是使用 HTTP 基本身份验证,其中令牌是用户名。等效的 phpcurl 将是

curl_setopt($ch, CURLOPT_USERPWD, "$token:$password");
于 2012-01-06T04:07:12.223 回答