添加曲目到播放列表spotify api web

时间:2017-01-30 20:35:13

标签: javascript php ajax spotify

我尝试将曲目添加到协作播放列表,这是我的访问令牌代码

$credentials = 'client_id:client_secret';

$headers = array(
           'Accept: */*',
           'Content-Type: application/x-www-form-urlencoded',
           'User-Agent: runscope/0.1',
           'Authorization: Basic '.base64_encode($credentials));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token');
curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'grant_type=client_credentials');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$response = json_decode($response, true);
echo $token = $response['access_token'];
curl_close($ch);

在我的页面中,用户未被记录,因此我创建了协作播放列表

这是我的add playlist函数

var addplaylist = function (id,token) {

      $.ajax({
        dataType: 'text',
        type: 'post',
        url: 'https://api.spotify.com/v1/users/entelperú/playlists/6sU8XOS7BLicR3COsc0Rhp/tracks?uris=spotify:track:'+ id,
        headers: {
          Authorization: "Bearer "+token,
        },success: function (response) {
          alert(response);
        }
    });
  };

但它会返回此

  

{     “错误”:{       “状态”:403,       “message”:“此请求需要用户身份验证。”     }   }

我不知道发生了什么,我已经创建了访问令牌。

1 个答案:

答案 0 :(得分:1)

  

{"错误" :{" status" :403," message" :"此请求需要用户   。认证#&34; }}

您正在向Add a Track to a Playlist发出的请求需要一个与用户相关联的访问令牌。

您正在使用的访问令牌可以来自三个不同的oAuth 2.0流程。其中一个流(Client Credentials流)返回匿名访问令牌。或者更确切地说,访问仅与任何用户无关的令牌。阅读Authorization Guide中有关流量的更多信息。

对于某些端点,使用匿名访问令牌是可以的。就像检索播放列表一样。但是很多动作,例如添加曲目,跟随艺术家和保存曲目,都要求用户明确允许您的应用程序代表他们行事。此权限也称为Scopes

因此,您需要的是使用与您现在使用的不同的oAuth 2.0流程。哪一个取决于您正在构建的应用程序类型。重要的是您需要用户批准您的应用程序正在执行的操作。