使用 Python 进行 Spotify API 身份验证

Pau*_*aul 3 python authentication api django spotify

我正在尝试对 Spotify API 中的用户进行身份验证,但它不断向我返回错误代码“invalid_client”。我正在 Python Django 解决方案上实现它,这是我的代码:

headers = {'Authorization': 'Basic '+standard_b64encode(client_id)+standard_b64encode(client_secret)}
r = requests.post('https://accounts.spotify.com/api/token', {'code': code, 'redirect_uri': redirect_uri, 'grant_type': grant_type, 'headers': headers}).json()
Run Code Online (Sandbox Code Playgroud)

知道为什么它不起作用吗?

NBa*_*nca 6

在 Spotify api 文档中,它是:需要授权。包含客户端 ID 和客户端密钥的 Base 64 编码字符串。该字段必须具有以下格式:授权:基本 base64 编码(client_id:client_secret)

所以我想你应该这样做:

import base64
'Authorization' : 'Basic ' + base64.standard_b64encode(client_id + ':' + client_secret)
Run Code Online (Sandbox Code Playgroud)

它对我有用,所以试试吧。如果它不起作用我的代码是:

@staticmethod
def loginCallback(request_handler, code):
    url = 'https://accounts.spotify.com/api/token'
    authorization = base64.standard_b64encode(Spotify.client_id + ':' + Spotify.client_secret)

    headers = {
        'Authorization' : 'Basic ' + authorization
        } 
    data  = {
        'grant_type' : 'authorization_code',
        'code' : code,
        'redirect_uri' : Spotify.redirect_uri
        } 

    data_encoded = urllib.urlencode(data)
    req = urllib2.Request(url, data_encoded, headers)

    try:
        response = urllib2.urlopen(req, timeout=30).read()
        response_dict = json.loads(response)
        Spotify.saveLoginCallback(request_handler, response_dict)
        return
    except urllib2.HTTPError as e:
        return e
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!

  • 你使用什么作为有效的redirect_uri?我想做的就是提出请求。那么我该如何发出 https get 请求呢?他们给出的所有示例都是无用的curl 调用。 (2认同)