几天来我一直在查看 Spotify api 和示例源代码,但我仍然无法弄清楚如何获取访问 token 来访问用户的播放列表数据。我已经到了拉起登录窗口,用户登录,然后我收到授权码的地步。在这一点上,我尝试做这样的事情:
window.open("https://accounts.spotify.com/api/token?
grant_type=authorization_code&code="+code+"&redirect_uri=myurl&client_id=3137b15
2f1424defa2c6020ae5c6d444&client_secret=mysecret");
和
$.ajax(
{
url: "https://accounts.spotify.com/api/token?grant_type=authorization_code&code="+code+"&redirect_uri=myurl&client_secret=mysecret&client_id=myid",
success: function(result){
alert("foo");
}
}
);
但无论哪种方式,我都会得到这样的结果:
{"error":"server_error","error_description":"Unexpected status: 405"}
而不是 token 。我敢肯定这很简单,但我在 JS 方面很糟糕。请帮忙!谢谢!
(编辑)我忘了说:
api 身份验证指南链接:https://developer.spotify.com/web-api/authorization-guide/
我卡在了第 4 步。我看到有一种替代方法可以发送“ header 参数”或 cURL 请求,这可能会起作用。但是由于我不知道如何做这些事情,我一直坚持发送 client_id 和 client_secret 作为正文请求参数,就像我之前为用户登录/代码所做的那样。
PS:我只使用我为自己编写的这个应用程序。有没有一种方法可以在不经过此过程的情况下对 token 进行硬编码?
最佳答案
When the authorization code has been received, you will need to exchange it with an access token by making a POST request to the Spotify Accounts service, this time to its /api/token endpoint:
因此您需要向 Spotify API 发出 POST 请求,请求正文中包含参数:
$.ajax(
{
method: "POST",
url: "https://accounts.spotify.com/api/token",
data: {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": myurl,
"client_secret": mysecret,
"client_id": myid,
},
success: function(result) {
// handle result...
},
}
);
(作为旁注,“Unexpected status: 405” 指的是 HTTP 状态代码 405 Method Not Allowed,表示您尝试的请求方法是 GET请求——该 URL 不允许。)
关于javascript - 如何获得访问 token Spotify API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39887342/