【问题标题】:How do I send info to this API using cURL and PUT?如何使用 cURL 和 PUT 向此 API 发送信息?
【发布时间】:2020-04-30 17:05:39
【问题描述】:

我正在使用此处记录的 API:https://cutt.ly/BygHsPV

文档有点薄,但我正在尽我所能理解它。下周中旬之前不会有来自 API 创建者的开发人员,我希望在此之前完成工作。

基本上我要做的是更新客户的同意。据我从 API -> Customer 下的文档了解,我需要通过 PUT 将信息发送到 /customers/{customerId}。该对象有一个名为“communicationChoices”的数组。

进入对象 -> CustomerUpdate 我发现“communicationChoices”被指定为“类型:CommunicationChoiceRequest 列表”。该对象如下所示:

{
  "choice": true,
  "typeCode": ""
}

尽我所能理解这一点,我做了这个功能:

function update_customer_consent() {
    global $userPhone, $username, $password;

    // Use phone number to get correct user
    $url = 'https://apiurlredacted.com/api/v1/customers/' . $userPhone .'?customeridtype=MOBILE';

    // Initiate cURL.
    $ch = curl_init( $url );

    // Specify the username and password using the CURLOPT_USERPWD option.
    curl_setopt( $ch, CURLOPT_USERPWD, $username . ":" . $password );

    // Tell cURL to return the output as a string instead
    // of dumping it to the browser.
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

    // Data to send

    $data = [
        "communicationChoices" => [
            "communicationChoiceRequest" => [
                "choice" => true,
                "typeCode" => "SMS"
            ]
        ]
    ];

    $json_payload = json_encode($data);

    print_r($json_payload);

    // Set other options
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($json_payload)));
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_payload);

    // Execute the cURL request

    $response = curl_exec($ch);

    // Check for errors.
    if( curl_errno( $ch ) ) :
       // If an error occured, throw an Exception.
       throw new Exception( curl_error( $ch ) );
    endif;

    if (!$response)
    {
        return false;
    } else {
        // Decode JSON
        $obj = json_decode( $response );
    }

    print_r($response);

}

我知道,如果不知道 API 中发生了什么并且文档有限,这很难调试,但我认为在这里询问还是值得一试的。

基本上,$json_payload 似乎是一个完美的 JSON 对象。然而,来自 API 的响应是一个错误代码,表示未知错误。所以我一定做错了什么。也许有人对 API 和此类文档有更多经验,并且可以看到我真正应该发送什么以及如何发送。

任何帮助或指导将不胜感激!

【问题讨论】:

  • 他们在 API 文档中说:添加注释 ApiResponseObject 以记录返回的对象。也许你可以这样做,不知道如何

标签: php json put


【解决方案1】:

在测试代码之前,您可以使用 API 文档中提供的表单。

当您导航到API > Customers > /customers/{customerId} (GET) 时,您将在页面右侧看到一个表单(向上滚动)。您需要在表单上提供所需的值,然后点击提交按钮。根据提交按钮下方的响应文本部分的结果,您肯定会得到communicationChoices 的有效数据。

现在,按照您从结果中获得的communicationChoices 对象的数据结构,并在API > Customers > /customers/{customerId} (PUT) 表单上尝试相同的操作。

使用 API 表单,您可以立即从您的输入(数据结构)中看到成功或错误,然后将其转换为您的代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-18
    • 1970-01-01
    • 2016-01-06
    • 2014-11-02
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2021-01-14
    相关资源
    最近更新 更多