Authorization code from OAuth callback
OAuth callback URI (must match authorization request)
Promise resolving to token response
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}`);
}
}
Exchanges authorization code for access and refresh tokens