how to do Curl -X POST -d in PHP

Asked

Viewed 128 times

0

I’m doing an integration with an api that brings real estate

In the documentation, it looks like this:

curl -X POST -d "client_id=1234&client_secret=abcd&grant_type=client_credentials" \
https://www.linkapi.com.br/oauth/token

However I do not know how to do in PHP, I did the way below, but returned empty({}bool(true)):

$client_id="1234";
$client_secret="abcd";
$url ="https://www.linkapi.com.br/oauth/token";

$process = curl_init($url);
$data = json_encode(array('grant_type' => 'client_credentials', 'client_id' => $client_id, 'client_secret' => $client_secret));
curl_setopt($process, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($process, CURLOPT_POST, true);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($process);

1 answer

1


The data is in x-www-form-urlencoded, and not in JSON.

-d "client_id=1234&client_secret=abcd&grant_type=client_credentials"

This is a urlencoded, and not a JSON.


To have exactly the same effect, you’d have to use:

$data = http_build_query(['grant_type' => 'client_credentials', 'client_id' => $client_id, 'client_secret' => $client_secret]);

$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, ["Content-Type: application/x-www-form-urlencoded"]); // O -d utiliza `application/x-www-form-urlencoded` por padrão.
curl_setopt($process, CURLOPT_POST, true);
curl_setopt($process, CURLOPT_POSTFIELDS, $data);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true); // Para "salvar" a resposta no curl_exec (o $resp).
$resp = curl_exec($process);

The only difference is the removal of json and the use of http_build_query.

  • perfect, gave right, thanks! just for me to learn the urlencoded is because of the -X?

  • e outra coisa, ele printou na tela {"access_token":"q95b","token_type":"Bearer","expires_in":31535701,"scope":"basic_info building_list building_details feedback","created_at":1586782560} como pego o acess_token?

  • @Leandroteraoka That’s because of the -d, and due to the type of data being sent. It is a number of factors. If you were like -d '{"client_id": 1234, "client_secret": abc}' would be a JSON, you acknowledge that this is JSON. While a client_id=1234&client_secret=abcd is a urlencoded, if it were to use the -F would be a multipart/form-data. But specifically about JSON, I would probably also use -H "Content-Type: application/json" to overwrite the Content-Type.

  • @Leandroteraoka You must use the CURLOPT_RETURNTRANSFER so that the $resp has the value of the answer. That’s, curl_setopt($process, CURLOPT_RETURNTRANSFER, true);, edited the answer to include this.

  • gave it right, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.