Created
July 12, 2023 10:23
-
-
Save Chr15t1an/65f3d9bd05f80b9a98e18810c2307d80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example spotify class | |
// const spotifyAPI = new SpotifyAPI('<Your Client ID>', '<Your Client Secret>', '<Your Redirect URI>'); | |
// spotifyAPI.getAuthToken().then(() => { | |
// spotifyAPI.setTokenInCookie(); | |
// spotifyAPI.search('Song Name').then(tracks => { | |
// console.log(tracks); | |
// }); | |
// }); | |
class SpotifyAPI { | |
constructor(clientId, clientSecret, redirectUri) { | |
this.clientId = clientId; | |
this.clientSecret = clientSecret; | |
this.redirectUri = redirectUri; | |
this.token = null; | |
} | |
async getAuthToken() { | |
const response = await fetch('https://accounts.spotify.com/api/token', { | |
method: 'POST', | |
headers: { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Authorization': 'Basic ' + btoa(this.clientId + ':' + this.clientSecret), | |
}, | |
body: new URLSearchParams({ | |
'grant_type': 'client_credentials' | |
}) | |
}); | |
const data = await response.json(); | |
this.token = data.access_token; | |
return this.token; | |
} | |
setTokenInCookie() { | |
document.cookie = `spotifyAuthToken=${this.token}; path=/`; | |
} | |
async search(query) { | |
const response = await fetch(`https://api.spotify.com/v1/search?q=${query}&type=track`, { | |
method: 'GET', | |
headers: { | |
'Authorization': 'Bearer ' + this.token, | |
} | |
}); | |
const data = await response.json(); | |
return data.tracks.items; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment