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

时间:2019-10-21 18:54:24

标签: php spotify

我正在尝试连接到Spotify API。

我获得的授权码为:


class Test(np):

    def __hash__(self):
      # function

到目前为止,我已经掌握了代码。然后,我尝试用以下方式交换令牌:

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

我可以想象到http://localhost:8000的所有变化都已在Spotify仪表板中列入白名单:

enter image description here

但是我得到这个错误:

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

edit:奇怪的是,我可以使用重定向URI http:%2F%2Flocalhost%3A8000与隐式授予客户端方法成功链接,因此我知道这已被正确列入白名单。我在上面发布的代码中使用了此URI,并得到了相同的错误。我还使用了我能想到的所有其他组合,无论使用的是%2F%2F,%3A%2F%2F,斜杠,%3A等等等。每次都出现相同的错误!

有什么想法吗?

edit2:如果我使用$ redirect_uri ='http://localhost:8000';我收到另一个错误:

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

1 个答案:

答案 0 :(得分:1)

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

根据文档,client_id和secret并非要与其他参数一起发送,它们需要通过Authorization标头添加到标头中:

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>