json - easybill REST API POST over PHP
this is my first post here. I hope that I get my question right. I use the google translator from German to English because my English is not that good.
I would like to use the "api" from easybill. GET worked. But unfortunately I can't do it with the POST.
I hope someone can help me.
I would like to create a new customer for testing. My goal is to generate invoices later using PHP. The "api" for easybill can be found here: https://www.easybill.de/api/
I tried the following code but unfortunately I can't find the error.
$url = "https://api.easybill.de/rest/v1/customers";
$data = array(
'first_name' => 'Foo',
'last_name' => 'Bar',
'company_name' => 'FooBar GmbH',
'emails' => array ('foo.bar@foobar.com'
)
);
$postdata = json_encode(array($data));
$accesstoken = "XXXXXXXXXXX";
$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: Bearer '.$accesstoken;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);
Best regards from Germany.
Answer
Solution:
Your mistakes:
Content-length: 0
doesn't make any sense and is utterly wrong here. Afaik you can remove it completely since curl does this for you.$postdata = json_encode(array($data));
will wrap your array in another array, which isn't correct here. It yields in:[{"first_name":"Foo","last_name":"Bar","company_name":"FooBar GmbH","emails":["foo.bar@foobar.com"]}]
where it has to be:
{"first_name":"Foo","last_name":"Bar","company_name":"FooBar GmbH","emails":["foo.bar@foobar.com"]}
just remove the array call:
$postdata = json_encode($data);
Source