我使用swifdil api通过curl从html表单创建用户。
API需要接收某种格式(json),但我不知道如何实现API所寻找的格式。
API的示例代码:
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://sandbox.swiftdil.com/v1/customers",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "{\r\n \"type\" : \"INDIVIDUAL\",\r\n \"email\" : \"Maria@Papakiriakou.com\",\r\n \"first_name\" : \"Maria\",\r\n \"last_name\" : \"Papakiriakou\"\r\n}",
我需要通过HTML表单提交值,因此我执行了以下操作:
function createNewUser()
{
// First we get all the information from the fields we need to pass on to swiftdill.
$type = $_POST['type'];
$email = $_POST['email'];
$first_name = $_POST['firstname'];
$last_name = $_POST['lastname'];
$fields = array(
'type' => $type,
'email' => $email,
'first_name' => $first_name,
'last_name' => $last_name
);
json_encode($fields);
$fields_string = http_build_query($fields);
$curl = curl_init();
// Set the options for the curl.
curl_setopt($curl, CURLOPT_URL, "https://sandbox.swiftdil.com/v1/customers");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURL_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer " .$newToken. "",
"Cache-Control: no-cache",
"Content-Type: application/json",
"Postman-Token: 0c513fa9-667d-4065-8531-8c4556acbc67"
));
我的代码输出如下:
type=Individual&email=test%40mail.nl&first_name=John&last_name=Doe
当然,这并没有按照api要求的方式格式化,即:
CURLOPT_POSTFIELDS => "{\r\n \"type\" : \"INDIVIDUAL\",\r\n \"email\" : \"Maria@Papakiriakou.com\",\r\n \"first_name\" : \"Maria\",\r\n \"last_name\" : \"Papakiriakou\"\r\n}",
当然,cURL错误如下所示:
{"id":"xxxx-xxxx-xxxx-xxxx-xxxxxxxxx","type":"malformed_content","message":"Content of the request doesn't conform to specification"}
我的php代码需要做什么才能让API接受我发送的数据?
答案 0 :(得分:2)
更改行:
$fields_string = http_build_query($fields);
进入这个:
$fields_string = json_encode($fields);
因为API期待JSON正文,因为您发送非JSON帖子正文,API将不知道它是什么并拒绝
答案 1 :(得分:0)
为什么不首先通过POSTMAN尝试响应,方法是根据API的要求设置数据并测试API的实际需求。
根据提供的信息,您似乎应删除以下行并仅发布json_encoded数据。
$fields_string = http_build_query($fields);