Announcements

Help Wizard

Step 1

NEXT STEP

Unsure how to get the Currently Playing json to work

Unsure how to get the Currently Playing json to work

Hi,

 

I'm currently trying to figure out why my code isn't getting this json file properly: https://developer.spotify.com/documentation/web-api/reference/get-the-users-currently-playing-track

 

I'm following the beginner guide.

The "Get User's Profile" works fine, but the Currently Playing doesn't.

 

Specifically, I'm looking at the four functions: fetchProfile(), fetchSongInfo(), populateUI() and populateUIPlaying(). I'm not really sure why all of the playing.[anything] returns undefined, even though I seem to be fetching the correct API (

Here's my code: 

const clientId = "[My Client ID Is Here]";
const params = new URLSearchParams(window.location.search);
const code = params.get("code");

if (!code) {
    redirectToAuthCodeFlow(clientId);
} else {
    const accessToken = await getAccessToken(clientId, code);
    const profile = await fetchProfile(accessToken);
    populateUI(profile);
    //console.log(profile);
    const playing = await fetchSongInfo(accessToken);
    populateUIPlaying(playing);
}


export async function redirectToAuthCodeFlow(clientId) {
    const verifier = generateCodeVerifier(128);
    const challenge = await generateCodeChallenge(verifier);

    localStorage.setItem("verifier", verifier);

    const params = new URLSearchParams();
    params.append("client_id", clientId);
    params.append("response_type", "code");
    params.append("redirect_uri", "http://localhost:5173/callback");
    params.append("scope", "user-read-private user-read-email");
    params.append("code_challenge_method", "S256");
    params.append("code_challenge", challenge);

    document.location = `https://accounts.spotify.com/authorize?${params.toString()}`;
}

function generateCodeVerifier(length) {
    let text = '';
    let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for (let i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

async function generateCodeChallenge(codeVerifier) {
    const data = new TextEncoder().encode(codeVerifier);
    const digest = await window.crypto.subtle.digest('SHA-256', data);
    return btoa(String.fromCharCode.apply(null, [...new Uint8Array(digest)]))
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=+$/, '');
}


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/callback");
    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
    });

    const { access_token } = await result.json();
    return access_token;
}

async function fetchProfile(token) {
    const result = await fetch("https://api.spotify.com/v1/me", {
        method: "GET", headers: { Authorization: `Bearer ${token}` }
    });
    return await result.json();
}

async function fetchSongInfo(token) {
    const result = await fetch("https://api.spotify.com/v1/me/player/currently-playing", {
        method: "GET", headers: { Authorization: `Bearer ${token}` }
    });
    return await result.json();
}

function populateUI(profile) {
    document.getElementById("displayName").innerText = profile.display_name;
    if (profile.images[0]) {
        const profileImage = new Image(200, 200);
        profileImage.src = profile.images[0].url;
        document.getElementById("avatar").appendChild(profileImage);
        document.getElementById("imgUrl").innerText = profile.images[0].url;
    }
    document.getElementById("id").innerText = profile.id;
    document.getElementById("email").innerText = profile.email;
    document.getElementById("uri").innerText = profile.uri;
    document.getElementById("uri").setAttribute("href", profile.external_urls.spotify);
    document.getElementById("url").innerText = profile.href;
    document.getElementById("url").setAttribute("href", profile.href);
}

function populateUIPlaying(playing) {
    document.getElementById("songId").innerText = playing.currently_playing_type;
    if (playing.images[0]) {
        const playingImage = new Image(200, 200);
        playingImage.src = playing.item.album.images[0].url;
        document.getElementById("nowplaying").appendChild(playingImage);
    }
}
Any help would be greatly appreciated. Thank you!
Reply
1 Reply

I'm having issues with the current playing too. I've been trying to fetch current playing data but somehow the I'm not being able to provided with the authorization code even though I'm putting in the right scopes required and all permissions seem to be there but it still says that there is Permission missing. 

Suggested posts