我正在尝试使用 Web API 与 Spotify 进行通信。 情况是这样的。为了从 Spotify 检索任何信息,首先我需要获得 Spotify 的授权。为此,我需要向
https://accounts.spotify.com/api/token
发送包含授权凭证(包含 client_id 和 client_secret)的发布请求,然后作为响应,我应该收到一个访问令牌,稍后我将使用它来检索任何其他信息。
以下是有关 Spotify 工作原理的快速文档:
所以这里的问题是我正在做我应该做的一切,但我没有得到令牌响应。
这是我在 laravel 中使用 Guzzle 包的代码:
我从 Spotify 收到的回报不是访问令牌作为响应,而是这个 HTML 输出(没有任何有关问题的进一步信息和任何错误代码):
您可能误解了这句话?
Authorization: Basic <base64 encoded client_id:client_secret>
看起来你正在这样做:
base64_encode($client_id) . ":" . base64_encode($client_secret)
但也许他们想要这个:
base64_encode($client_id . ":" . $client_secret);
也就是说,假设您对它们进行了 Base 64 编码,因为这实际上并未显示在您的代码中。
此外,文档指出它需要
application/x-www-form-urlencoded
编码。
# 发送表单 URL 编码请求
https://laravel.com/docs/8.x/http-client#sending-form-url-encoded-requests
要满足此要求,您可能需要在请求中添加
asForm()
。
$response = Http::withHeaders(...)->asForm()->post(...);
谢谢...下面是上面的工作代码
use Illuminate\Support\Facades\Http;
$client_id = 'YOUR CLIENT ID';
$client_secret = 'YOUR CLIENT SECRET';
$post = 'https://accounts.spotify.com/api/token';
$clientKeys = base64_encode($client_id . ":" . $client_secret);
$response = Http::withHeaders([
'Authorization' => 'Basic '.$clientKeys
])->asForm()->post($post,[
'grant_type' => 'client_credentials'
]);
$response->json();
$access_token = $response['access_token'];