PHP 中的 Spotify API 身份验证 - 无效的重定向 URI

Spotify API auth in PHP - Invalid redirect URI

我正在尝试连接到 Spotify API。

我通过以下方式获得授权码:

<?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/>

到目前为止一切顺利,我得到了代码。然后我尝试用以下方式交换令牌:

$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);

而且我已经在 Spotify 控制面板中列出了我能想到的 http://localhost:8000 的所有变体:

但是我得到这个错误:

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

编辑:奇怪的是我可以使用重定向 URI http:%2F%2Flocalhost%3A8000 成功地 link 使用隐式授权客户端方法 - 所以我知道这是正确的白名单。我在上面发布的代码中使用了这个 URI,但得到了同样的错误。我还使用了我能想到的所有其他组合,无论是使用 :%2F%2F、%3A%2F%2F、尾部斜线、尾部 %3A 等等。每次都出现同样的错误!

有什么想法吗?

edit2:如果我使用 $redirect_uri = 'http://localhost:8000';我得到一个不同的错误:

result: {"error":"invalid_request","error_description":""}

现在您已经停止对 redirect_uri 进行编码,它正在抱怨参数无效。

根据文档,client_id 和秘密并不意味着与其他参数一起发送,它们需要通过授权 header 添加到 headers ]:

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>