首页 > 解决方案 > 在 Spotify API 上获取授权码(POST 请求)

问题描述

这是我正在关注的 Spotify文档。在“授权流程”的 3 个选项中,我正在尝试“授权代码流程”。

完成第1 步。让您的应用程序请求授权

卡在第2 步。让您的应用程序请求刷新并访问令牌

它要求发出一个 POST 请求,其中包含在 OAuth 2.0 规范中定义的 'application/x-www-form-urlencoded 中编码的参数:。到目前为止,这是我用我有限的知识和谷歌搜索所做的。

import requests
import base64
from html import unescape 

url = "https://accounts.spotify.com/api/token"

params = {
    "grant_type": "authorization_code",
    "code": <authorization code I got from step 1>,
    "redirect_uri": "http://127.0.0.1:5000/", 
}

headers = {
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",    
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization" : base64.b64encode("{}:{}".format(CLIENT_ID, CLIENT_SECRET).encode('UTF-8')).decode('ascii')
}

html = requests.request('post', url, headers=headers, params=params, data=None) 
print(html.text)

结果,响应代码为 400

{"error":"invalid_client"}

我应该怎么做才能让它工作?我以为我得到了所有的参数。

标签: pythonpostspotify

解决方案


推荐阅读