簡體   English   中英

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 成功鏈接到隱式授權客戶端方法 - 所以我知道這已正確列入白名單。 我在上面發布的代碼中使用了這個 URI,得到了同樣的錯誤。 我還使用了我能想到的所有其他組合,無論是使用:%2F%2F、%3A%2F%2F、斜杠、%3A 等。每次都出現同樣的錯誤!

有任何想法嗎?

編輯2:如果我使用 $redirect_uri = ' http://localhost:8000 '; 我得到一個不同的錯誤:

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

現在您已經停止對 redirect_uri 進行編碼,它正在抱怨無效參數。

根據文檔,client_id 和 secret 並不意味着與其他參數一起發送,它們需要通過 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM