I'm an absolute beginner when it comes to send an API request using cURL.
I'm trying to get an access token. Everything seems to be fine when I'm testing my request with Reqbin:
endpoint -> https://example.com/oauth/token
method -> POST
content type -> JSON
content:
{
"grant_type": "password",
"client_id": 8,
"client_secret": "myclientsecret",
"username": "test@email.com",
"password": "pass",
"scope": "*"
}
When I send my request I obtain the expected result:
status -> 200 (OK)
content:
{
"token_type": "Bearer",
"expires_in": 172800,
"access_token": "my_access_token",
"refresh_token": "my_refresh_token"
}
However, when I try to use cURL I obtain an unexpected response. This is my PHP code:
<?php
$url = "https://example.com/oauth/token";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = <<<DATA
{
"grant_type": "password",
"client_id": 8,
"client_secret": "myclientsecret",
"username": "test@email.com",
"password": "pass",
"scope": "*"
}
DATA;
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
?>
And this is the $resp content:
string(238) "<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="https://www.example.com/oauth/token">here</a>.</p>
</body></html>
What am I doing wrong? I can't get rid of this error! Thank you!