首页 > 解决方案 > 通过 cURL 的 POST 数组没有给我正确的格式

问题描述

我正在使用 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 接受我发送的数据?

标签: phpapicurl

解决方案


换行:

$fields_string = http_build_query($fields);

进入这个:

$fields_string = json_encode($fields);

因为 API 需要 JSON 正文,所以当您发送非 JSON 帖子正文时,API 将不知道它是什么并拒绝


推荐阅读