I have a JSON string that i want to pass along to a API using POST.
When i try to pass along the data i get "JSON not valid". I have manually tested the JSON string using the API's inbuilt test tool and know the string works. The function works with fetching from API using GET.
I suspect the PHP/curl syntax might be wrong when using POST?
function curl($url = null,$method = null,$body = null){
$loginauth = base64_encode('SECRETKEY');
if($method == null){
$method = 'GET';
$headers = array(
'Accept: application/hal+json,application/vnd.error+json',
'Authorization: Basic '.$loginauth
);
}else{
$method = 'POST';
$headers = array(
'Content-Type: application/json',
'Authorization: Basic '.$loginauth
);
}
if($url == null){
$url = 'https://coolapi.com/api/v1/companies';
}
if($body == null){
$body = '';
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $url,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $body
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err){
return $err;
}else{
return json_decode($response);
}
}
My call of function:
$url = 'https://one-url';
$data = '{
"date": "2017-02-22",
"identifier": "1337",
"lines": [
{
"test": "this is a test",
}
],
"name": "Wolf"
}';
$register_sale = curl(
$url,
'POST',
$data
);