You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python自动获取Spotify API的Authorization Code?

如何自动提取Spotify授权回调URL中的code参数

要自动获取回调URL里的授权码(code),你需要在本地启动一个临时HTTP服务器,接收Spotify跳转的回调请求并解析参数。以下是修改后的完整实现代码:

import webbrowser
import urllib.parse
import base64
import requests as req
from http.server import BaseHTTPRequestHandler
from socketserver import TCPServer

# credentials
client_id = "xxx..."
client_secret = "xxx..."

# urls
redirect_uri = "http://localhost:7777/callback"
auth_url = "https://accounts.spotify.com/authorize?"
token_url = "https://accounts.spotify.com/api/token"

# data scopes
scopes = "user-read-private user-read-email"

# 存储授权码的全局变量
auth_code = None

# 自定义回调请求处理器
class CallbackHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        global auth_code
        # 解析请求URL的查询参数
        url_components = urllib.parse.urlparse(self.path)
        query_params = urllib.parse.parse_qs(url_components.query)
        
        if 'code' in query_params:
            auth_code = query_params['code'][0]
            # 给浏览器返回成功提示
            self.send_response(200)
            self.send_header('Content-Type', 'text/html')
            self.end_headers()
            self.wfile.write(b'<h1>授权成功!请关闭此页面返回程序。</h1>')
        else:
            # 处理没有code的情况
            self.send_response(400)
            self.end_headers()
            self.wfile.write(b'<h1>错误:未获取到授权码,请重新发起授权。</h1>')

# 启动授权流程
print("正在打开授权页面,请在浏览器中完成登录授权...")
webbrowser.open(auth_url + urllib.parse.urlencode({
    "client_id": client_id,
    "response_type": "code",
    "redirect_uri": redirect_uri,
    "scope": scopes
}))

# 启动临时本地服务器,等待回调
with TCPServer(('', 7777), CallbackHandler) as httpd:
    print("等待授权回调...")
    # 只处理一次请求就关闭服务器
    httpd.handle_request()

if not auth_code:
    raise Exception("未能获取到授权码,请检查配置后重试")

# 获取授权令牌
encoded_creds = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode('utf-8')
token_headers = {
    "Authorization": f"Basic {encoded_creds}",
    "Content-Type": "application/x-www-form-urlencoded"
}
token_data = {
    "grant_type": "authorization_code",
    "code": auth_code,
    "redirect_uri": redirect_uri
}
r = req.post(token_url, data=token_data, headers=token_headers)

# 打印令牌响应
print(r.json())

关键逻辑说明

  • 临时HTTP服务器:通过TCPServer和自定义CallbackHandler监听本地7777端口,对应你设置的redirect_uri端口
  • 参数解析:在do_GET方法中,用urllib.parse解析请求URL的查询参数,提取出code并保存到全局变量
  • 单次请求处理:httpd.handle_request()只处理一次回调请求就关闭服务器,避免程序一直阻塞
  • 浏览器提示:处理完请求后给浏览器返回直观的提示,方便用户知道授权完成

注意事项

  • 确保Spotify开发者后台配置的重定向URI和代码中的http://localhost:7777/callback完全一致,包括端口和路径
  • 启动程序前确认本地7777端口未被其他程序占用
  • 如果授权过程中出现错误,服务器会返回对应的提示,可根据提示排查问题

内容的提问来源于stack exchange,提问作者Jai Amin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:45:22