• Exchanges authorization code for access and refresh tokens

    Parameters

    • code: string

      Authorization code from OAuth callback

    • redirectUri: string

      OAuth callback URI (must match authorization request)

    Returns Promise<SpotifyTokens>

    Promise resolving to token response

    Error if token exchange fails

    export async function exchangeCodeForTokens(
    code: string,
    redirectUri: string,
    ): Promise<SpotifyTokens> {
    ensureCredentialsSet();

    const { clientId, clientSecret } = getCredentials();

    try {
    const response = await axios.post(
    TOKEN_URL,
    querystring.stringify({
    grant_type: "authorization_code",
    code,
    redirect_uri: redirectUri,
    client_id: clientId,
    client_secret: clientSecret,
    }),
    {
    headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    },
    },
    );

    const { access_token, refresh_token, expires_in } = response.data;

    // Store tokens internally
    setTokens(access_token, refresh_token, expires_in);

    saveLog("Successfully exchanged code for tokens", "DEBUG");
    return response.data;
    } catch (error: unknown) {
    const err = error as Error;
    saveLog(`Failed to exchange code for tokens: ${err.message}`, "ERROR");
    throw new Error(`Failed to exchange code for tokens: ${err.message}`);
    }
    }