Reputation: 684
I am trying to request an API which has the following details:
Request Headers:
Content-Type: application/x-www-form-urlencoded
apikey: {{Your API Key}}
Request Body:
"channel" : "chat",
"source" : "xxxxxxx",
"destination" : "xxxxxxxx"
"src.name":"DemoApp"
"message" : {
"isHSM":"false",
"type": "text",
"text": "Hi John, how are you?"
}
my current code is as follows:
$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;
I am not getting the message part correct in payload like adding isHSM, type etc..
My current code is:
$message = array(
'isHSM' => true,
'type' => "text",
'text' => "This is a test"
);
Requesting help on how to add the message payload in above curl request...
Upvotes: 0
Views: 29
Reputation: 9145
You need to pass an array into CURLOPT_POSTFIELDS
to make it automatically application/x-www-form-urlencoded
. Just remove the http_build_query()
function and the appropriate header. The method to POST
is also auto set.
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
)
));
The message may be required to be converted into a JSON string.
$message = json_encode(array(
'isHSM' => true,
'type' => "text",
'text' => "This is a test"
));
Upvotes: 1