Getting a 400 error when exchanging authorization code for access token in Spotify API integration

  Kiến thức lập trình

I’m working on integrating Spotify API into my web application using the Authorization Code with PKCE Flow. I’ve followed the documentation provided by Spotify, but I’m encountering a 400 error when trying to exchange the authorization code for an access token.

Here’s a summary of what I’ve done:

  • Implemented the PKCE extension to generate a code verifier and code challenge.
  • Redirected the user to Spotify’s authorization page with the appropriate parameters, including the code challenge.
  • After the user grants permission, received the authorization code in the callback URL.
  • Attempted to exchange the authorization code for an access token using a POST request to Spotify’s token endpoint.

However, the POST request to exchange the authorization code for an access token is failing with a 400 error. I’ve double-checked the parameters, including client_id, grant_type, redirect_uri, code_verifier, and code, and they all seem to be correct.

Here’s a simplified version of the code I’m using:

const clientId = [YOUR_CLIENT_ID];
const redirectUri = 'http://localhost:3000';

const generateAuthCode = async () => {
  // Generate code verifier
  const codeVerifier = 'generated_code_verifier';

  // Redirect user to Spotify authorization page
  const authUrl = 'https://accounts.spotify.com/authorize';
  const params = {
    response_type: 'code',
    client_id: clientId,
    scope: 'playlist-modify-public playlist-modify-private',
    code_challenge_method: 'S256',
    code_challenge: 'generated_code_challenge',
    redirect_uri: redirectUri,
  };
  const queryString = new URLSearchParams(params).toString();
  window.location.href = `${authUrl}?${queryString}`;
};

const generateAccessToken = async (code, setUserInfo) => {
  // Exchange authorization code for access token
  const url = 'https://accounts.spotify.com/api/token';
  const payload = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      client_id: clientId,
      grant_type: 'authorization_code',
      code,
      redirect_uri: redirectUri,
      code_verifier: 'stored_code_verifier',
    }),
  };

  try {
    const response = await fetch(url, payload);
    const responseData = await response.json();
    setUserInfo((prevInfo) => ({
      api_key: responseData.access_token,
      userId: prevInfo.userId,
    }));
  } catch (error) {
    console.log('Error:', error);
  }
};

export { generateAuthCode, generateAccessToken };

I’ve also logged the response from the server, but it doesn’t provide much information beyond the 400 status code.

Any insights or suggestions on what might be causing this issue would be greatly appreciated. Thank you!

New contributor

jmill29 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT