I have to send a request to API
from wordpress
contact us form. I have write the following code in PHP
and test it. It was working fine. But when I add this code in a function within wordpress
I become to know that file_get_contents not working. I have tried different wordpress
function like wp_remote_post
etc. Then calling to API going to fail. please help me to send a good request so I can post data.
function send_api_request(){
$postData = array(
"AccessKey" => "xxxxxxxxxx",
"Subject" => "sample subject 1",
"Name" => "sample name",
"Message" => "sample message",
"Phone" => "0000000000",
"Email" => "xxxxxx@gmail.com",
"Company" => "sample company",
"SourceFrom" => 1
);
// Create the context for the request
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => json_encode($postData)
)
));
// Send the request
$response = file_get_contents('http://someURL.com/api/lead', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
return $response;
}
The code which I have tried with wordpress
is as follow.
function send_api_request($name,$email,$phone,$company,$message,$source){
$postData = array(
"AccessKey" => "xxxxx",
"Subject" => "",
"Name" => $name,
"Message" => $message,
"Phone" => $phone,
"Email" => $email,
"Company" => $company,
"SourceFrom" => $source
);
// Create the context for the request
$context = (array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/json",
'content' => json_encode($postData)
)
));
// Send the request
$response = "";
$response = wp_remote_post("http://someURL.com/api/lead", $context);
}