I'm working on an app that allows authentication using Spotify
When trying to get the user's access token, i get a 400 bad request 'invalid_client'.
Here is my JS code which fires whenever the user is redirected to the app. The url is localhost:3000/spotify?code=xxxxxxxxxxx&state=xxxxxxxxx
const myHeaders = new Headers();
myHeaders.append('Accept', 'application/json');
myHeaders.append('Access-Control-Allow-Origin', '*');
myHeaders.append('Content-Type', 'application/json');
//gets the param in the url
const paramCode = getParameterByName('code', window.location.href);
const defaultOptions = {
method: 'POST',
headers: myHeaders,
body: JSON.stringify({
code: paramCode,
}),
mode: 'cors',
};
// POST request to the backend at http://localhost:8000/api/spotify/oauth
fetch(LocalAPI.getLocalTokenUrl(), defaultOptions)
.then((response) => {
return response.json();
})
.then((results) => {
console.log('token : ', results.access_token);
// "Client error: `POST https://accounts.spotify.com/api/token`
// resulted in a `400 Bad Request` response:
// {"error":"invalid_client","error_description":"Invalid client"}"
});
And here is my backend PHP code which fires whenever it receives a POST request at /api/spotify/oauth
It requests the user's access token but fails. A 400 bad request error is catched and sent to the JS code.
$code = $request->input('code');
$id = $this->getClientId();
$secret = $this->getClientSecret();
//encodes clientid and secret in base64
$token = \base64_encode("$id:$secret");
$headers = [
'Authorization' => 'Basic '.$token,
'Content-Type' => 'application/x-www-form-urlencoded'
];
try {
$guzzle = new Client();
$results = $guzzle->post($this->getTokenUrl(), [
'headers' => $headers,
'form_params' => [
'code' => $code,
'redirect_uri' => 'http://localhost:3000/spotify',
'grant_type' => 'authorization_code'
]
]);
}
catch (\GuzzleHttp\Exception\ServerException $e) {
echo json_encode($e->getResponse());
}
catch(\GuzzleHttp\Exception\ClientException $e) {
echo json_encode($e->getMessage());
}
catch(\GuzzleHttp\Exception\RequestException $e) {
echo json_encode($e->getResponse());
}
echo \GuzzleHttp\json_encode($results);
According to Spotify API documentation :
https://developer.spotify.com/web-api/user-guide/#response-status-codes
My request could be malformed ...
I tried messing with the Content-Type and set it to application/json. In this case, no errors are catched but i get a "JSON.parse: unexpected character at line 1 column 1 of the JSON data" in my JS code.
Any suggestion would be appreciated.
Best regards.
</div>