From 53790cc8e281d02e36b3a53673c5e7b1ccad5442 Mon Sep 17 00:00:00 2001 From: xtrullor73 Date: Thu, 2 May 2024 15:38:42 -0700 Subject: [PATCH] feat(authentication): implement Spotify API token retrieval function --- src/api/spotifyAuth.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/api/spotifyAuth.js diff --git a/src/api/spotifyAuth.js b/src/api/spotifyAuth.js new file mode 100644 index 0000000..9a77ac1 --- /dev/null +++ b/src/api/spotifyAuth.js @@ -0,0 +1,31 @@ +import axios from 'axios'; +import qs from 'qs'; + +const client_id = process.env.SPOTIFY_CLIENT_ID; +const client_secret = process.env.SPOTIFY_CLIENT_SECRET; + +export default function getSpotifyAccessToken() { + const authOptions = { + method: 'POST', + url: 'https://accounts.spotify.com/api/token', + headers: { + Authorization: `Basic ${Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`, + 'Content-Type': 'application/x-www-form-urlencoded', + }, + data: qs.stringify({ + grant_type: 'client_credentials', + }), + }; + + return axios(authOptions) + .then((response) => { + if (response.status === 200) { + return response.data.access_token; + } + return Promise.reject(new Error(`Could not get access token for ${response.status}`)); + }) + .catch((error) => { + console.error('Auth Error:', error); + throw error; + }); +}