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

使用Python生成Spotify Token后调用API遇Invalid username错误的解决求助

问题描述

我使用以下Python程序通过Spotify API生成token:

import requests

CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
CLIENT_SECRET = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyy'

AUTH_URL = 'https://accounts.spotify.com/api/token'

# POST
auth_response = requests.post(AUTH_URL, {
    'grant_type': 'client_credentials',
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
})

# convert the response to JSON
auth_response_data = auth_response.json()

# save the access token
access_token = auth_response_data['access_token']

print("token is ")
print(access_token)

该程序成功输出了token,但尝试用此token调用接口获取当前播放曲目时:

curl -X "GET" "https://api.spotify.com/v1/me/player/currently-playing?market=ES" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer xxxxxxxxxxxxxxxxxxxGenrated Tokenxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

返回了如下错误:

{
  "error" : {
    "status" : 404,
    "message" : "Invalid username"
  }
}

请问该如何解决这个问题?

解决方案

核心问题是你使用的client_credentials授权模式生成的token不具备用户权限。这种模式仅用于应用自身访问公开Spotify数据,无法调用需要关联特定用户的接口(比如获取当前播放曲目)。

要解决这个问题,必须改用**授权码流程(Authorization Code Flow)**获取带用户权限的token,步骤如下:

  • 配置重定向URI
    登录Spotify开发者后台,找到你的应用,进入"Edit Settings"页面,添加一个重定向URI(例如http://localhost:8080/callback),保存修改。

  • 获取授权码
    构造并打开以下URL(替换YOUR_CLIENT_ID和YOUR_REDIRECT_URI为实际值):

    https://accounts.spotify.com/authorize?response_type=code&client_id=YOUR_CLIENT_ID&scope=user-read-currently-playing&redirect_uri=YOUR_REDIRECT_URI
    

    登录你的Spotify账号并完成授权后,浏览器会跳转到设置的重定向URI,地址栏中的code参数即为授权码。

  • 换取用户授权的token
    使用授权码发送POST请求获取token,示例Python代码如下:

    import requests
    
    CLIENT_ID = 'YOUR_CLIENT_ID'
    CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
    AUTH_CODE = '获取到的授权码'
    REDIRECT_URI = '你设置的重定向URI'
    
    auth_response = requests.post('https://accounts.spotify.com/api/token', data={
        'grant_type': 'authorization_code',
        'code': AUTH_CODE,
        'redirect_uri': REDIRECT_URI,
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
    })
    
    access_token = auth_response.json()['access_token']
    print(access_token)
    
  • 调用目标接口
    使用新生成的token执行原curl命令,即可正常获取当前播放曲目。

额外注意事项:

  • 授权码只能使用一次,过期后需要重新获取
  • 请求授权时必须包含user-read-currently-playing权限范围,否则仍会出现权限错误

内容的提问来源于stack exchange,提问作者ganeshredcobra

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:35:25