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

使用Spotify Web API PKCE流程时,授权码换访问令牌报400错误

解决Spotify PKCE授权换Token返回400 Bad Request的问题

1. 修复getAccessToken函数的响应处理

你的getAccessToken函数未处理API响应,既没有返回令牌数据,也没有捕获错误详情。Spotify的Token接口返回400时,响应体里会给出具体错误原因(比如code失效、verifier不匹配等),修改函数如下:

export async function getAccessToken(clientId, code) {
  const verifier = localStorage.getItem("verifier");

  const params = new URLSearchParams();
  params.append("client_id", clientId);
  params.append("grant_type", "authorization_code");
  params.append("code", code);
  params.append("redirect_uri", "http://localhost:5173/home");
  params.append("code_verifier", verifier);

  const result = await fetch("https://accounts.spotify.com/api/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: params,
  });

  // 非200状态时解析错误信息并抛出
  if (!result.ok) {
    const error = await result.json();
    throw new Error(`获取Token失败: ${error.error_description || error.error}`);
  }

  // 返回解析后的access token
  const data = await result.json();
  return data.access_token;
}

2. 避免重复发起Token请求

在Home.jsx中,直接在组件顶层调用fetchAccessToken会导致组件每次渲染都发起请求,而Spotify的authorization code仅能使用一次,重复请求会导致code失效返回400。需要把请求放到useEffect中,限定执行条件:

import React, { useEffect, useState } from "react";
import { getAccessToken } from "../config/authWithPKCE";

// 替换为你在Spotify开发者后台获取的Client ID
const clientId = "你的ClientID";

export const Home = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const code = urlParams.get("code");
  const [accessToken, setAccessToken] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 仅当code存在且未获取到token时执行请求
    if (code && !accessToken) {
      const fetchToken = async () => {
        try {
          const token = await getAccessToken(clientId, code);
          setAccessToken(token);
        } catch (err) {
          setError(err.message);
        }
      };
      fetchToken();
    }
  }, [code, accessToken]);

  return (
    <>
      <h1>Logged In</h1>
      {error && <p style={{color: 'red'}}>{error}</p>}
      {accessToken ? (
        <p>Access Token: {accessToken}</p>
      ) : !error ? (
        <p>Fetching access token...</p>
      ) : null}
    </>
  );
};

3. 关键检查项

  • 填写正确的Client ID:代码中clientId为空字符串,必须替换为你在Spotify开发者后台创建应用的真实Client ID。
  • 保证redirect_uri完全一致:redirectToAuthCodeFlow和getAccessToken中的redirect_uri必须完全相同,且与Spotify开发者后台应用设置里的重定向URI完全匹配(包括协议、端口、路径)。
  • 检查code_verifier存储:确认verifier已正确存入localStorage,未被清空或篡改。

完成以上修改后,若仍有问题,可通过错误提示定位具体原因;无异常则能成功获取access token。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:28:15