You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP调用Spotify API获取播放列表曲目遇404错误求助

Spotify API 获取播放列表曲目返回404错误排查方案

核心排查点与解决办法

1. 先获取Spotify的具体错误响应

你的代码中启用了CURLOPT_FAILONERROR,导致HTTP 4xx错误时curl直接返回false,无法拿到Spotify给出的详细错误原因。先注释掉这个配置,获取完整错误信息:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $access_token"
]);
// 注释该行以获取完整错误响应
// curl_setopt($ch, CURLOPT_FAILONERROR, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

运行后查看$response的JSON内容,Spotify会明确提示错误原因(如权限不足、地区限制、播放列表不可访问等)。

2. 验证Access Token的权限

虽然你的Token能获取歌手/专辑信息,但访问公开播放列表需要playlist-read-public权限:

  • 用JWT解码工具解析你的$access_token,检查scope字段是否包含playlist-read-public。
  • 如果是通过Client Credentials Flow获取的Token,默认包含该权限;如果是其他授权方式(如Authorization Code Flow),需确认授权时请求了该scope。

3. 检查播放列表的地区可用性

你使用的37i9dQZEVXbKyJS56d1pgi是Spotify官方精选播放列表,这类列表可能存在地区限制:

  • 先在Spotify客户端中搜索该ID,确认能否正常打开播放列表。
  • 如果客户端无法访问,说明该列表在你的账号地区不可用,需切换账号地区或使用对应地区的代理。

4. 确认API端点正确性

官方公开播放列表的端点路径是正确的,但需注意:

  • 播放列表ID是否存在拼写错误(你提供的ID看起来是有效的,但可以再次核对)。
  • 避免URL中出现转义字符或多余空格,确保$url拼接后为https://api.spotify.com/v1/playlists/37i9dQZEVXbKyJS56d1pgi/tracks。

调试后的完整代码示例

<?php

// Spotify API credentials
$client_id = 'client_id';
$client_secret = 'client_secret';

$access_token = getAccessToken($client_id, $client_secret);

if (!$access_token) {
    die("Error: Unable to retrieve access token.\n");
}
echo "Access Token: $access_token\n";

// Playlist ID
$playlistId = "37i9dQZEVXbKyJS56d1pgi";
$url = "https://api.spotify.com/v1/playlists/$playlistId/tracks";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $access_token"
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Debugging API response
if ($httpCode === 200) {
    $data = json_decode($response, true);
    print_r($data);
} else {
    echo "Error fetching playlist: HTTP $httpCode\n";
    echo "Response: $response\n";
}

// 补充getAccessToken实现示例(Client Credentials Flow)
function getAccessToken($client_id, $client_secret) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://accounts.spotify.com/api/token');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'grant_type' => 'client_credentials',
        'client_id' => $client_id,
        'client_secret' => $client_secret
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($response, true);
    return $data['access_token'] ?? null;
}
?>

内容的提问来源于stack exchange,提问作者Mário Jorge Rocha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 15:15:05