【发布时间】:2021-05-29 19:04:52
【问题描述】:
import requests
import base64
from secrets import USER_CLIENT_ID, USER_CLIENT_SECRET, USER_REDIRECT_URI
# using OAuth we create a link to redirect user to their spotify account
def create_oauth_link():
params = {
"client_id": USER_CLIENT_ID,
"response_type": "code",
"redirect_uri": USER_REDIRECT_URI,
"scope": "user-read-private user-read-email"
}
endpoint = "https://accounts.spotify.com/authorize"
response = requests.get(endpoint, params=params)
url = response.url
return url
# authorization process to exchange code for token
def exchange_code_token(code=None):
message = f"{USER_CLIENT_ID}:{USER_CLIENT_SECRET}"
messageBytes = message.encode("ascii")
base64Bytes = base64.b64encode(messageBytes)
base64Message = base64Bytes.decode("ascii")
headers = {'Authorization': f'Basic {base64Message}'}
params = {
'grant_type': "authorization_code",
"code": code,
"redirect_uri": USER_REDIRECT_URI,
#"client_id": USER_CLIENT_ID,
#"client_secret": USER_CLIENT_SECRET,
}
endpoint = "https://accounts.spotify.com/api/token"
response = requests.post(endpoint, params=params, headers=headers)
print(response.reason)
link = create_oauth_link()
print(f"Follow the link to start the authentication with Spotify: {link}")
code = input("Spotify Code: ")
exchange_code_token(code)
我正在成功生成代码,但是在尝试将其交换为访问令牌时一切都出错了。我收到了错误的请求响应。 我已尝试根据 Spotify 的文档以及通过 base64 编码通过请求参数传递 client_id 和 client_secret,但似乎没有任何效果。 可能是什么问题?
【问题讨论】:
标签: python api post python-requests spotify