Search code examples
phpcurlphp-curl

how to get a curl json post statement to work in php


I have a curl post request that posts Json to an api end point but for the life of me I cant get it working in php. Here is the working curl:

curl -v -H "Accept: application/json" -H "Content-type: application/json" -H "Access-Token: **not_telling_you**" -X POST --data '{"import":{"members":[{"organization_customer_identifier":"a number", "program_customer_identifier":"a number", "first_name":"Chris", "member_customer_identifier":"5", "member_status":"OPEN"} ]}}'  https://an_api_endpoint.com/api/v1/imports

Here is the php that does not work:

$org_id = "a number";
$pc_id = "a number";
$user_id = "5";
$api_key = "**not telling you**";
$url = "https://an_api_endpoint.com/api/v1/imports";
$data = json_encode(array('import' => array( 'members' => array( array('organization_customer_identifier' => $org_id, 'program_customer_identifier' => $pc_id, 'member_customer_identifier' => $user_id, 'member_status' => 'OPEN')))));
echo $data;
echo "\n";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Access-Token: '.$api_key));
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
$result = json_decode($output, true);
var_dump($result);

I keep getting errors like {"message":"Invalid JSON in request body, please validate your JSON and try again."}int(1) or upon switching things up a bit it might be:["message"]=>string(29) "Invalid API key () specified."

I thought it would be easier for me to translate curl into php curl but I cant seem to get this one working. I even tried copying and pasting in the json data directly so it would be exactly the same and its not working still. I'm not sure if I'm missing something or my order is bad? Thank you in advance for any help I get solving this one.


Solution

  • You don't use the CURLOPT_HTTPHEADER option multiple times. You use it once with an array of all the headers.

    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Accept: application/json', 
        'Content-Type:application/json', 
        'Access-Token: '.$api_key));
    

    You're also missing the CURLOPT_POST option.

    You might want to use this site. You paste in a curl command and it converts it to PHP.

    https://incarnate.github.io/curl-to-php/