Here are two functions that might help you initialize the Spotify Web Playback SDK using Implicit Grant Flow to get a temporarily OAuth token.
If you want refreshable user authorization, you need to use Authorization Code Flow.
function logInWithSpotify() {
const clientId = '<insert-client-id>'; // Get ClientID from https://developer.spotify.com/dashboard/
const redirectUrl = '<insert-redirect-uri>'; // Add redirect URIs to the whitelist in the settings https://developer.spotify.com/dashboard/
const scopes = ['streaming', 'user-read-email', 'user-read-private']; // Required scopes
// Implicit Grant Authorization Flow
// More info: https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
window.location = [
'https://accounts.spotify.com/authorize',
`?client_id=${clientId}`,
`&scope=${encodeURIComponent(scopes.join(' '))}`,
`&redirect_uri=${encodeURIComponent(redirectUrl)}`,
'&response_type=token',
'&show_dialog=true',
].join('');
}
function getOAuthToken(cb) {
const hash = window.location.hash
.substring(1)
.split('&')
.reduce((values, item) => {
if (item) {
const [key, value] = item.split('=');
values[key] = decodeURIComponent(value);
}
return values;
}, {});
// Clear the hash
window.location.hash = '';
const accessToken = hash.access_token;
if (!accessToken) logInWithSpotify();
cb(accessToken);
}
const player = new Spotify.Player({
name: 'Web Playback SDK Quick Start Player',
getOAuthToken: getOAuthToken,
});
Here is a more detailed Gist of how to use the Spotify Web Playback SDK: https://gist.github.com/lundgren2/4a5c7a1ba7916bbcf460901620166ab2