我如何使用cURL和PUT向此API发送信息?

问题描述 投票:0回答:1

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

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

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

进入对象-> CustomerUpdate我找到了“ communicationChoices”,它被指定为“ Type: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和此类文档有更多的经验,可以看到我应该发送的内容以及发送的方式。

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

php json put
1个回答
0
投票

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

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

现在,遵循从结果中获得的communicationChoices对象的数据结构,并尝试以API > Customers > /customers/{customerId}(PUT)形式进行操作。

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

© www.soinside.com 2019 - 2024. All rights reserved.