使用 php curl 时传递值

Passing values while using php curl

我正在尝试请求 API,其中包含以下详细信息:

请求Headers:

Content-Type: application/x-www-form-urlencoded
apikey: {{Your API Key}} 

请求Body:

 "channel" : "chat",
"source" : "xxxxxxx",
"destination" : "xxxxxxxx"
"src.name":"DemoApp"
"message" : {
          "isHSM":"false",
        "type": "text",
        "text": "Hi John, how are you?"
} 

我目前的代码如下:

 $payload = [
    'channel' => $channel,
    'source' => $source,
    'destination'   => $destination,
    'message' => $message,
    'src.name' => $appname
    ];
    
    $curl = curl_init();
    curl_setopt_array($curl, array(
    CURLOPT_URL => "https://apiurl/test",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS => http_build_query($payload),
    CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "apikey:" . $apikey,
    "cache-control: no-cache",
    "content-type: application/x-www-form-urlencoded"
    ),
    ));
    $response = curl_exec($curl);
    if(curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
    }
    curl_close($curl);
echo $response;

我没有在有效负载中得到正确的消息部分,例如添加 isHSM、type 等。

我当前的代码是:

$message = array(
            'isHSM' => true,
            'type' => "text",
            'text' => "This is a test"
            );

请求有关如何在上述 curl 请求中添加消息负载的帮助...

您需要将一个数组传递给 CURLOPT_POSTFIELDS 以使其自动 application/x-www-form-urlencoded。只需删除 http_build_query() 函数和适当的 header。 POST的方法也是自动设置的。

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://apiurl/test",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_POSTFIELDS => $payload,
    CURLOPT_HTTPHEADER => array(
    "accept: application/json",
    "apikey:" . $apikey
    )
));

可能需要将消息转换为 JSON 字符串。

$message = json_encode(array(
            'isHSM' => true,
            'type' => "text",
            'text' => "This is a test"
            ));