命令行cURL到PHP cURL

时间:2013-04-24 03:36:08

标签: php curl

我无法将命令行cURL转换为php cURL。我已经阅读了关于这个主题的其他链接,我仍然感到困惑,并希望得到任何帮助。

我正在尝试自动将网络表单中的联系信息放入在线CRM中。

API信息:http://karmacrm.zendesk.com/entries/23648323-Contacts

我的代码:

$header = array('contact[first_name]=aaaaaaa','API-KEY: XXXXXXXXX');
$pageurl = "https://app.karmacrm.com/api/v2/contacts.json";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $pageurl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERPWD, 'mXXXX@gmail.com:7iNXXXXXXXXXX');
curl_setopt($ch, CURLOPT_HEADER, TRUE); // -i
curl_setopt($ch, CURLOPT_VERBOSE, TRUE); // -v
curl_setopt($ch, CURLOPT_CUSTOMEREQUEST, "POST"); //-X
curl_setopt($ch, CURLOPT_BINARYTRANSFER, FALSE); // --data-binary, -d
$output = curl_exec($ch); 
curl_close($ch);
echo $output;

回应:

HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8 
Transfer-Encoding: chunked 
Connection: keep-alive 
Status: 401 
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.11 
Strict-Transport-Security: max-age=31536000 
X-UA-Compatible: IE=Edge,chrome=1 
Cache-Control: no-cache, private 
X-Request-Id: 8d9397e1c2d43580db7XXXXXXXXXXXX 
X-Runtime: 0.004153 
Date: Wed, 24 Apr 2013 03:14:27 GMT 
X-Rack-Cache: miss 
Server: nginx/1.2.3 + Phusion Passenger 3.0.11 (mod_rails/mod_rack)

{"error":"You need to sign in or sign up before continuing."}1

感谢您的帮助,我很感激。

3 个答案:

答案 0 :(得分:2)

您将POST值作为HTTP标头传递,这是不一样的。

使用此:

$data = array('contact[first_name]' => 'aaaaaaa', 'api_token' => 'XXXXXXXXX');
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data);

并删除CURLOPT_HTTPHEADER选项。

正如旁注:链接的API描述没有说明向API发送登录详细信息 - 只有API令牌(通常用于API)。

答案 1 :(得分:0)

未经授权的内容类型:application / json

我认为API服务器没有返回您想要的正确内容类型。

答案 2 :(得分:-1)

示例:

$url = 'link_to_api';
$params = array('username'=>'admin','password'=>'passw0rd');


    public function call_ws_post($url = '', $params = array()){
    $service_url = $url;
    $curl = curl_init($service_url);
    $curl_post_data = $params;
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
    $curl_response = curl_exec($curl);
    if ($curl_response === false) {
        $info = curl_getinfo($curl);
        curl_close($curl);
        die('error occured during curl exec. Additional info: ' . var_export($info));
    }
    curl_close($curl);
    $decoded = json_decode($curl_response);
    if (isset($decoded->response->status) && $decoded->response->status == 'ERROR') {
        die('error occured: ' . $decoded->response->errormessage);
    }
    return $decoded;
}