r/PHPhelp • u/chaos232 • Apr 29 '25
Create contact via API using PHP
Hello everyone,
I am currently trying to create a contact via an API using PHP. But somehow I can't get any further and can't narrow down the error.
Here is my code:<?php
// Daten$firstname = 'test';$lastname = 'test';
// API-Endpunkt und API-Key$api_url = 'https://xyz.com/api/v1/contact'; $api_key = 'xxx';
// API-Daten vorbereiten
$data = '{"firstName" => $firstname,"lastName" => $lastname}';
// Header für die Anfrage$headers = ['AuthenticationToken: Bearer $api_key','Content-Type: application/json','Content-Length: ' . strlen($data)];
// cURL für API-Anfrage$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_POST, true);curl_setopt($ch, CURLOPT_POSTFIELDS, $data);curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);curl_setopt($ch, CURLOPT_ENCODING , 'gzip');curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0');
// Anfrage ausführen und Antwort erhalten$response = curl_exec($ch);
// Den HTTP-Statuscode abfragen$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);curl_close($ch);
// Statusif ($response === false) {echo "Fehler bei der Anfrage an xyz.com";} else {// Ausgabe des HTTP-Statuscodes und der Antwortecho "HTTP-Statuscode: " . $http_code . "<br>";//echo "status von Weclapp: " . $response[status];echo "Antwort von xyz.com: " . $response. "<br>";
}
?>
When I do this, I get the HTTP status code 200 back. But a 201 should come back, then the contact would have been created. I've already looked through the API documentation, but unfortunately I can't get any further because I don't get any error messages.
Perhaps someone has a tip on how I can proceed?
View all comments
Show parent comment
3
u/Lumethys Apr 29 '25
on that note, it seems
is also wrong, since single-quoted string cannot be interpolated