【发布时间】:2020-02-17 21:51:46
【问题描述】:
我正在尝试连接到 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 成功链接到隐式授权客户端方法 - 所以我知道这已正确列入白名单。我在上面发布的代码中使用了这个 URI,得到了同样的错误。我还使用了我能想到的所有其他组合,无论是使用:%2F%2F、%3A%2F%2F、斜杠、%3A 等。每次都出现同样的错误!
有什么想法吗?
edit2:如果我使用 $redirect_uri = 'http://localhost:8000';我得到一个不同的错误:
result: {"error":"invalid_request","error_description":""}
【问题讨论】:
-
你试过不带端口吗?
-
是的,如果代码中有非法重定向uri,只是将其添加到白名单中没有效果。
-
发现一个可能重复的问题here
-
我想 $redirect_uri 应该是未编码的形式,即
$redirect_uri = 'http://localhost:8000';http_build_query 应该为你编码。 -
确实不应该在用法中对 URI 进行编码