Bad request on call of lead creation

I try to create a lead onto an existing organization.
I use the beneath function.
I get always a 400 bad request error (whatever is $titre and $orga) and i don’t figure out why.
$orga is the id of a previously created organization.
Nota: Same kind of code for creating organization works well.

function setLead($titre, $orga) {
  $api_token = 'xxxxx';
  $company_domain = 'xxxxx';
  $url = 'https://' . $company_domain . '.pipedrive.com/api/v1/leads?api_token=' . $api_token;
  $data = array(
    'title' => $titre,
    'organization_id' => $orga
  );
  $options = array(
    'http' => array(
      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
      'method'  => 'POST',
      'content' => http_build_query($data)
    )
  );
  $context  = stream_context_create($options);
  $result = file_get_contents($url, false, $context);
  if ($result != FALSE) { 
    echo json_encode (json_decode ($result), JSON_PRETTY_PRINT);
  }
  else {
    echo "ERREUR setLead";
  }
}

Using curl it works :slight_smile:

function setLead($titre, $orga) {
  $url = 'https://' . $company_domain . '.pipedrive.com/api/v1/leads?api_token=' . $api_token;
  $data = '{ "title" : "' . $titre . '", "organization_id": ' . $orga .' }';
  $ch = curl_init($url);
  curl_setopt_array($ch, array(
    CURLOPT_POST => TRUE,
    CURLOPT_RETURNTRANSFER => TRUE,
    CURLOPT_SSL_VERIFYPEER => FALSE,
    CURLOPT_HTTPHEADER => array(
        'Content-Type: application/json'
    ),
    CURLOPT_POSTFIELDS => $data
  ));
  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
}
1 Like