0
votes

I'm trying to connect to the Spotify API.

I get the authorization code with:

<?php
$redirect_uri = 'http%3A%2F%2Flocalhost%3A8000';
?>
<a href="https://accounts.spotify.com/authorize?client_id=<?php echo $client_id;?>&response_type=code&redirect_uri=<?php echo $redirect_uri; ?>&scope=user-read-private%20user-read-email&state=34fFs29kd09">Get code</a><br/><br/>

So far so good, I get the code. Then I try to exchange for a token with:

$redirect_uri = 'http%3A%2F%2Flocalhost%3A8000';
$url = 'https://accounts.spotify.com/api/token';
$fields = [
  'grant_type' => 'authorization_code',
  'code' => $code,
  'redirect_uri' => $redirect_uri,
  'client_id' => $client_id,
  'secret' =>   $secret
];
$fields_string = http_build_query($fields);
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);

And I've got every variation I can imagine of http://localhost:8000 whitelisted in the Spotify dashboard:

enter image description here

But I get this error:

result: {"error":"invalid_grant","error_description":"Invalid redirect URI"}

edit: What's weird is I CAN successfully link up with the implicit grant client side method, using the redirect URI http:%2F%2Flocalhost%3A8000 - so I know that this is whitelisted properly. I've used this URI in the code I posted above, and get the same error. I've also used every other combination I can think of, whether that's using :%2F%2F, %3A%2F%2F, a trailing slash, a trailing %3A etc etc. Same error every time!

Any ideas?

edit2: if I use $redirect_uri = 'http://localhost:8000'; i get a different error:

result: {"error":"invalid_request","error_description":""}
1
Have you tried it without the port?GrumpyCrouton
Yep, illegal redirect uri if it's in the code, just added it to the whitelist with no effect.user43107
Found a possible duplicate question hereGrumpyCrouton
I imagine $redirect_uri should be the unencoded form, i.e. $redirect_uri = 'http://localhost:8000'; http_build_query should be encoding it for you.AaronHolland
Indeed the URI shouldn't be encoded in the usageRoguePlanetoid

1 Answers

1
votes

Now that you have stopped encoding the redirect_uri, it is complaining about invalid parameters.

As per the documentation, the client_id and secret aren't meant to sent along with the other parameters, they need to be added to the headers via the Authorization header:

https://developer.spotify.com/documentation/general/guides/authorization-guide/#2-have-your-application-request-refresh-and-access-tokens-spotify-returns-access-and-refresh-tokens

HEADER PARAMETER 
Authorization 
Base 64 encoded string that contains the client ID and client secret key. 
The field must have the format:
Authorization: Basic <base64 encoded client_id:client_secret>