【问题标题】:Spotify "Unexpected status: 400" when refreshing and accessing token - python刷新和访问令牌时的Spotify“意外状态:400”-python
【发布时间】:2017-01-08 20:14:07
【问题描述】:

当尝试使用 python 3 授权 spotify 时,我收到一个带有描述“意外状态:400”的“server_error”。

我使用了正确的授权代码,并且 spotify 文档 (https://developer.spotify.com/web-api/authorization-guide/) 指示我使用带有这些参数的 post 命令。

我在这方面是个菜鸟,我不知道我做错了什么。

代码如下:

import requests

params = {'grant_type': 'authorization_code', 'code': authcode, 'redirect_uri': 'https://example.com/callback','client_id':'example', 'client_secret':'example'}

req=requests.post('https://accounts.spotify.com/api/token', params=params)
print(req.content)

【问题讨论】:

    标签: python python-3.x post spotify


    【解决方案1】:

    根据 spotify 自己的指南(参见步骤 #4):

    https://developer.spotify.com/web-api/authorization-guide/

    请求新令牌的授权信息必须通过“授权”变量进入标头:

    授权:必需。 Base 64 编码的字符串,包含 客户端 ID 和客户端密钥。该字段必须具有以下格式: 授权:基本 base64 编码 client_id:client_secret

    您在请求正文中拥有它。

    所以你应该这样做:

    import requests
    import base64
    
    authcode = 'valid_authcode_from_prev_authorization_step'
    
    params = {'grant_type': 'authorization_code', 'code': authcode, 'redirect_uri': 'https://example.com/callback'}
    
    client_id = 'example_id'
    client_secret = 'example_secret'
    
    b64_val = base64.b64encode("%s:%s" % (client_id, client_secret))
    
    req = requests.post(
        'https://accounts.spotify.com/api/token', params=params,
        headers={'Authorization': b64_val})
    

    但是,要使其正常工作,您需要一个有效的身份验证代码,您只能通过让用户完成令牌获取步骤之前的身份验证步骤来获得该代码。

    此代码将发送到您在应用设置中注册的回调,如果您设置了虚假回调,则该回调将不起作用(即:http://example.com/callback)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-26
      • 2017-08-05
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 2018-08-01
      相关资源
      最近更新 更多