Kevin.a
Kevin.a

Reputation: 4286

Posting to API with cURL

I'm trying to post data to an API with cURL. If I do it via the playground of the API provider it works.

But through my code something doesn't seem to work:

$headers = array();
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
$curl = curl_init('testcheckout.buckaroo.nl/json/Transaction');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl,CURLOPT_POSTFIELDS, $post);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);    
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
return $result;

if(curl_error($curl))
{
    echo 'error:' . curl_error($c);
}

curl_close($curl);

I tried error handling with the curl_error function but that doesn't seem to be working either. I never get an error, even if I make some obvious mistakes like purposely changing my API secret to something that doesn't make sense. How do I send the data. How do I post to the API and why am I not getting any errors?

Upvotes: 1

Views: 300

Answers (1)

Syscall
Syscall

Reputation: 19780

Several notes:

  • The return statement should be after to check the errors.
  • To check errors, you should test $result === false.
  • The variable $c is undefined in curl_error().
  • The URL is mal-formed, missing the scheme (eg, http://).
  • The option CURLOPT_URL is redundant, because already defined in curl_init().

Code:

$headers = array();
$headers[] = 'Authorization: hmac ' .$websiteKey.':'.$hmac .':'.$nonce . ':'.$time;
$curl = curl_init('http://testcheckout.buckaroo.nl/json/Transaction');
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl,CURLOPT_POSTFIELDS, $post);
// curl_setopt($curl, CURLOPT_URL, $url); // already defined in curl_init().
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
if($result === false)
{
    echo 'error:' . curl_error($curl);
}
curl_close($curl);
return $result;

Upvotes: 2

Related Questions