我如何获得访问令牌Spotify API

How can I get an access token Spotify API?

本文关键字:Spotify API 访问令牌 何获得      更新时间:2023-09-26

我已经看了Spotify api几天了,现在和示例源代码,我仍然不知道如何获得访问令牌来访问用户的播放列表数据。现在我打开登录窗口,用户登录,然后我收到一个授权码。在这一点上,我尝试做这样的事情:

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"}

而不是标记。我相信这很简单,但我在JS很糟糕。请帮助!谢谢你!

(编辑)我忘了说:

api认证指南链接:https://developer.spotify.com/web-api/authorization-guide/

我卡在第4步了。我看到有另一种方法可以发送"头参数"或cURL请求,这可能会起作用。但是看到我不知道如何做这些事情,我坚持发送client_id和client_secret作为body请求参数,就像我之前为用户登录/代码所做的那样。

PS:我只使用我为自己写的这个应用程序。有没有一种方法,我可以硬编码一个令牌,而不经过这个过程?

当收到授权码时,您需要通过向Spotify Accounts服务发出POST请求,将其与访问令牌交换,这次是到它的/api/令牌端点:

所以你需要用请求体中的参数向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上不被允许。)