0

I am trying to post some data to the magento api using curl and then get a response. I have searched around a bit and made a short code snippit that should do the job but it returns a blank string. I should receive a oauth_token from magento or at least an error message.

The code below is what i came up with:

function file_get_contents_curl($url, $test, $data) {

    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

$url contains the url an $data contains the data that needs to be sent.

the code bellow is the line that triggers this function

$response = file_get_contents_curl($endpoint->getAbsoluteUri(), false, $context);

If anyone sees the problem please let me know!

1 Answer 1

0

Check if the below example helps, It does works as expected in my local env. Moreover you can create the actual magento rest api in the postman and just export as php - cUrl code snippet

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => 'http://example.com/admin/token',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS =>'{
    "username": "test",
    "password": "test123"
}',
  CURLOPT_HTTPHEADER => array(
    'Content-Type: application/json'
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.