1

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
);
sdfgg45
  • 1,232
  • 4
  • 22
  • 42

1 Answers1

1

In PHP, there is no predefined datatype as json if you passing json in data; PHP will consider it as string. So, declare array and convert into json using json_encode and it will work.

Give it a try.

$data = [
  "date"=> "2017-02-22",
  "identifier" => "1337",
  "lines" => [  "test" => "this is a test" ],
  "name"=> "Wolf"
];
$json = json_encode($data);

$register_sale = curl($url,'POST', $json);

Ref.: https://lornajane.net/posts/2011/posting-json-data-with-php-curl

Naincy
  • 2,953
  • 1
  • 12
  • 21