0

我正在尝试使用 Spotify 的 API 执行授权代码流,以最终将歌曲添加到播放列表中。我正在从头开始构建它,而不是使用任何库,例如 Spotipy。

我能够成功访问授权端点,但令牌端点存在一些问题。这是我到目前为止的代码:

# URLS
AUTH_URL = 'https://accounts.spotify.com/authorize'
TOKEN_URL = 'https://accounts.spotify.com/api/token'
BASE_URL = 'https://api.spotify.com/v1/'


# Make a request to the /authorize endpoint to get an authorization code
auth_code = requests.get(AUTH_URL, {
    'client_id': CLIENT_ID,
    'response_type': 'code',
    'redirect_uri': 'https://open.spotify.com/collection/playlists',
    'scope': 'playlist-modify-private',
})
print(auth_code)

auth_header = base64.urlsafe_b64encode((CLIENT_ID + ':' + CLIENT_SECRET).encode('ascii'))
headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': 'Basic %s' % auth_header.decode('ascii')
}

payload = {
    'grant_type': 'authorization_code',
    'code': auth_code,
    'redirect_uri': 'https://open.spotify.com/collection/playlists',
    #'client_id': CLIENT_ID,
    #'client_secret': CLIENT_SECRET,
}

# Make a request to the /token endpoint to get an access token
access_token_request = requests.post(url=TOKEN_URL, data=payload, headers=headers)

# convert the response to JSON
access_token_response_data = access_token_request.json()

print(access_token_response_data)

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

当我运行我的脚本时,我在终端中得到这个输出:

{'error': 'invalid_grant', 'error_description': 'Invalid authorization code'}
Traceback (most recent call last):
  File "auth.py", line 48, in <module>
    access_token = access_token_response_data['access_token']
KeyError: 'access_token'```

Can anyone explain to me what I might be doing wrong here?
4

1 回答 1

0

如果我没记错的话,你错过了代码中设置的 CLIENT_ID 和 CLIENT_SECRET 。

这意味着 Spotify 将返回无效的访问令牌,从而导致您无法继续。

您还可以使用 Python 的 Sptipy 库来简化操作。 https://spotipy.readthedocs.io/en/2.16.1/

于 2021-01-10T01:00:13.277 回答