使用spotify api和laravel无法获得刷新的access_token



首次在Laravel中使用HTTP客户端和Spotify API。

第一步是通过访问获得代码https://accounts.spotify.com/authorize?client_id=c1990...deed3& response_type = code& redirect_uri 3 = http % % 2 f % 2 fexample.test % 2的范围= user-read-currently-playing % 20 user-top-read

然后在重定向后从url复制代码。

然后使用curl -

curl -H "Authorization: Basic YzE5OT...Q2ZjA=" -d grant_type=authorization_code -d code=AQBX...X5zg -d redirect_uri=http%3A%2F%2Fexample.test%2F https://accounts.spotify.com/api/token

以JSON格式返回刷新令牌-

{"access_token"BQBQL……vNDQ"token_type"Bearer"expires_in" 3600,"refresh_token"AQCy……areM"scope"user-read-currently-playing user-top-read"}

但是我似乎不能使用refresh_token获得访问令牌。

我收到了"错误请求"。statusCode: 400 in my app

$response = Http::withHeaders([
'Authorization' => `Basic YzE5O...Q2ZjA`,
'Content-Type' => 'application/x-www-form-urlencoded'
])
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);

这里是文档https://developer.spotify.com/documentation/general/guides/authorization/code-flow/。

有没有人在Laravel之前实现过这个,如果是的话,是如何实现的?

我不知道Spotify API,但我99%确定您的错误是->asForm(),您将其作为表单而不是正常请求发送…所以你的代码可能需要像这样:

$response = Http::withToken('YzE5O...Q2ZjA')
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);

看到我已经删除了->asForm()Content-Type(不知道你为什么要使用它,这是一个正常的API…和->asForm()已经设置了相同的内容,你手动设置…

这是Spotify API,我没有看到任何需要设置Conetnt-Type


哎呀,你需要设置->asForm(),所以代码应该是:

$response = Http::withToken('YzE5O...Q2ZjA')
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 'AQC7...YphY'
]
);

但我仍然认为你错过了一些东西。检查你的refresh_token是否正确。还要查找更多的调试输出

这对我很有效。

的内容类型=比;'application/x-www-form-urlencoded'从withHeaders中删除

$response = Http::withHeaders([
'Authorization' => 'Basic ' . 123...123,
])
->asForm()
->post(
'https://accounts.spotify.com/api/token',
[
'grant_type' => 'refresh_token',
'refresh_token' => 123...456
]
);

最新更新