【问题标题】:PHP Curl Format [closed]PHP卷曲格式[关闭]
【发布时间】:2014-05-31 18:33:46
【问题描述】:

我想使用 FreshDesk API,例如 'create a ticket' 命令。
我以前使用过 POST cUrl,但是那里给出的示例让我感到困惑,我不太确定如何具体进行那里提供的 cUrl 调用,

curl -u user@yourcompany.com:test -H "Content-Type: application/json" -d '{ "helpdesk_ticket": { "description": "Details about the issue...", "subject": "Support Needed...", "email": "tom@outerspace.com", "priority": 1, "status": 2 }, "cc_emails": "ram@freshdesk.com,diana@freshdesk.com" }' -X POST http://domain.freshdesk.com/helpdesk/tickets.json

我注意到这是一个 shell 命令,并且我无权访问 shell 命令
但是,我之前已经成功地能够使用 cUrl POST API(使用 Disqus)。
在那里,API 调用看起来像

$thread = "param1";
$remote_auth_s3 = "param2";
$forum = "param3";
$api = "param4";
$url = 'http://disqus.com/api/3.0/posts/create.json';

$fields = array(
    'api_secret'=>urlencode($api),
    'thread'=>urlencode($thread),
    'remote_auth'=>urlencode($remote_auth_s3),
    'message'=>urlencode($message)
);

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($ch);
curl_close($ch);

$results = json_decode($result, true);
if ($results === NULL) die('Error parsing json');

这看起来很合乎逻辑,但是我应该如何将 shell 命令转换为这种 cUrl 调用格式?
这可能是一个非常愚蠢的问题,但也是一个诚实的问题。我确实发现 two others 有同样的问题,但他们不需要同时包含 POST 参数,所以请不要将其标记为重复。

我希望有人能够解决我的困境。

【问题讨论】:

  • 您的问题到底出在哪里?这相当简单,只需将标题设置为CURLOPT_HTTPHEADER 并将帖子数据设置为CURLOPT_POSTFIELDS 中的数组(如有必要,使用json_encode)。
  • @RenéRoth 这是否意味着我必须将descriptionsubject 等添加为数组本身中的helpdesk_ticket 数组?
  • 我发布了一个完全解决您问题的答案,希望如此。

标签: php shell curl


【解决方案1】:
// set HTTP auth credentials
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
// set Content-Type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
// use POST method
curl_setopt($ch, CURLOPT_POST, true);
// send your JSON string in the request, do not urlencode it
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);

【讨论】:

  • 我得到了你的答案,这确实对我有帮助,但它不是正确的格式,尽管它也是必不可少的。谢谢!
【解决方案2】:

使用curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields)); 向API 发送一个json 编码的数组。

您的示例数组如下所示:

$fields=array(
 'helpdesk_ticket'=>array(
  'description'=>'Details about the issue...',
  'subject'=>'Support needed...',
  'email'=>'tom@outerspace.com',
  'priority'=>1,
  'status'=>2
 ),
 'cc_emails'=>'ram@freshdesk.com,diana@freshdesk.com'
);

【讨论】:

  • 我稍后试试,我现在不能,抱歉:}
  • 如所愿,完美运行!
猜你喜欢
  • 2017-07-21
  • 1970-01-01
  • 2012-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 2015-06-25
  • 1970-01-01
相关资源
最近更新 更多