为博客添加 Spotify 状态显示卡片的步骤

·

2 min read

Get Refresh_Token

import base64
import requests
import webbrowser

# Spotify API 配置
CLIENT_ID = "your_client_id"  # 替换为你的 Client ID
CLIENT_SECRET = "your_client_secret"  # 替换为你的 Client Secret
REDIRECT_URI = "http://localhost/callback"  # 替换为你的重定向 URI
TOKEN_URL = "https://accounts.spotify.com/api/token"
SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"

# 定义需要的权限(Scopes)
SCOPES = "user-read-private user-read-email playlist-modify-private playlist-modify-public"


# 获取授权码(Authorization Code)
def get_auth_code():
    auth_url = (
        f"{SPOTIFY_AUTH_URL}?client_id={CLIENT_ID}&response_type=code"
        f"&redirect_uri={REDIRECT_URI}&scope={SCOPES}"
    )
    webbrowser.open(auth_url)
    print(f"请访问以下链接并授权:\n{auth_url}")
    # 从用户输入中获取重定向后的 code 参数
    return input("请输入重定向后的 URL 中的 code 参数值:")


# 使用授权码获取 Access Token 和 Refresh Token
def get_tokens(auth_code):
    headers = {
        "Authorization": f"Basic {base64.b64encode(f'{CLIENT_ID}:{CLIENT_SECRET}'.encode()).decode()}"
    }
    data = {
        "grant_type": "authorization_code",
        "code": auth_code,
        "redirect_uri": REDIRECT_URI,
    }
    response = requests.post(TOKEN_URL, headers=headers, data=data)
    if response.status_code == 200:
        return response.json()
    else:
        print("获取 Token 失败:", response.json())
        return None


# 使用 Refresh Token 刷新 Access Token
def refresh_access_token(refresh_token):
    headers = {
        "Authorization": f"Basic {base64.b64encode(f'{CLIENT_ID}:{CLIENT_SECRET}'.encode()).decode()}"
    }
    data = {
        "grant_type": "refresh_token",
        "refresh_token": refresh_token,
    }
    response = requests.post(TOKEN_URL, headers=headers, data=data)
    if response.status_code == 200:
        return response.json().get("access_token")
    else:
        print("刷新 Token 失败:", response.json())
        return None


# 主流程
if __name__ == "__main__":
    # Step 1: 获取 Authorization Code
    print("正在获取 Authorization Code...")
    authorization_code = get_auth_code()

    # Step 2: 使用 Authorization Code 获取初始 Tokens
    print("正在获取 Access Token 和 Refresh Token...")
    tokens = get_tokens(authorization_code)

    if tokens:
        access_token = tokens.get("access_token")
        refresh_token = tokens.get("refresh_token")
        print(f"Access Token: {access_token}")
        print(f"Refresh Token: {refresh_token}")

        # Step 3: 测试刷新 Access Token
        print("测试刷新 Access Token...")
        new_access_token = refresh_access_token(refresh_token)
        if new_access_token:
            print(f"新的 Access Token: {new_access_token}")

Install astro-spotify

npm install astro-spotify

Create .env

# Spotify API Configuration
SPOTIFY_CLIENT_ID=your_client_id_here
SPOTIFY_CLIENT_SECRET=your_client_secret_here
SPOTIFY_REFRESH_TOKEN=your_refresh_token_here

Create src/components/SpotifyCard.astro

---
import { CurrentlyPlaying } from "astro-spotify";
---
<div class="bg-white dark:bg-zinc-900 dark:text-zinc-200 p-4 rounded-lg shadow-md">
  <div class="flex items-center gap-2 mb-3">
    <svg class="w-5 h-5 text-[#1DB954]" viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z"/>
    </svg>
    <h2 class="text-lg font-bold">正在收听</h2>
  </div>

<CurrentlyPlaying
  clientID={import.meta.env.SPOTIFY_CLIENT_ID}
  clientSecret={import.meta.env.SPOTIFY_CLIENT_SECRET}
  refreshToken={import.meta.env.SPOTIFY_REFRESH_TOKEN}
/>