Home > database >  Send APi key and secret key in CURL
Send APi key and secret key in CURL

Time:09-17

I'm trying to convert the line below to be used with PHP whilst also learning how to use CURL!

$ curl -X POST -d 'key=YOUR_KEY&secret=YOUR_SECRET' "https://api.example.co.uk/authenticate" -H "Content-Type: application/x-www-form-urlencoded"

Bellow is what I have so far, however I keep getting HTTP ERROR 403 UnauthorizedException accessing service error, so I think the key and secret and not being sent correctly.

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.example.co.uk/authenticate",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"key\": \"MYKEY\",\"secret\": \"MYSECRET\"}",
  CURLOPT_HTTPHEADER => array(
    "content-type: application/x-www-form-urlencoded"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

CodePudding user response:

Use this tool as it save so much time - https://incarnate.github.io/curl-to-php/

Generated this:

// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.example.co.uk/authenticate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "key=YOUR_KEY&secret=YOUR_SECRET");

$headers = array();
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);
  • Related