如何让 curl json post 语句在 php 中工作

how to get a curl json post statement to work in php

我有一个 curl post 请求 posts Json 到 api 终点但是对于我来说我无法让它在 php。 这是工作卷曲:

curl -v -H "Accept: application/json" -H "Content-type: application/json" -H "Access-Token: **not_telling_you**" -X POST --data '{"import":{"members":[{"organization_customer_identifier":"a number", "program_customer_identifier":"a number", "first_name":"Chris", "member_customer_identifier":"5", "member_status":"OPEN"} ]}}'  https://an_api_endpoint.com/api/v1/imports

这是不起作用的 php:

$org_id = "a number";
$pc_id = "a number";
$user_id = "5";
$api_key = "**not telling you**";
$url = "https://an_api_endpoint.com/api/v1/imports";
$data = json_encode(array('import' => array( 'members' => array( array('organization_customer_identifier' => $org_id, 'program_customer_identifier' => $pc_id, 'member_customer_identifier' => $user_id, 'member_status' => 'OPEN')))));
echo $data;
echo "\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Access-Token: '.$api_key));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$result = json_decode($output, true);
var_dump($result);

我不断收到类似 {"message":"Invalid JSON in request body, please validate your JSON and try again."}int(1) 的错误 或者稍微改变一下它可能是:["message"]=>string(29) "Invalid API key () specified."

我认为将 curl 翻译成 php curl 对我来说会更容易,但我似乎无法让它工作。我什至尝试直接复制和粘贴 json 数据,这样它就完全一样了,但仍然无法正常工作。 我不确定是我遗漏了什么还是我的订单有误? 预先感谢您为我解决这个问题提供的任何帮助。

您没有多次使用 CURLOPT_HTTPHEADER 选项。您将它与所有 headers.

的数组一起使用一次
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json', 
    'Content-Type:application/json', 
    'Access-Token: '.$api_key));

您还缺少 CURLOPT_POST 选项。

您可能想使用这个网站。您粘贴 curl 命令并将其转换为 PHP.

https://incarnate.github.io/curl-to-php/