I have been trying to get my spotify access tokens and refresh tokens for my react native application and its been giving me serious issues. https://docs.expo.dev/guides/authentication/#spotify I was able to get my code and state using the useAuthRequest. Now i have tried using the code to get my access tokens and refresh tokens for my application on the client but i keep encountering the error 400. So checking other stack overflow issues i realized handling it on the server would be better so i decided to create an express server to try and get the access code
router.post('/get-spotify-access-code',(req: Request, res: Response)=>{
console.log(req.body)
const accessCode = req.body;
var authOptions:AuthOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: accessCode,
redirect_uri: redirectUri,
grant_type: 'authorization_code'
},
headers: {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + Buffer.from(clientID + ':' + clientSecret).toString('base64')
},
json: true
};
request.post(authOptions, (error: any, response:any, body:any)=>{
console.log(error);
console.log(response)
if(!error && response.statusCode === 200){
const access_token = body.access_token;
const refresh_token = body.refresh_token;
const expires_in = body.expires_in;
res.json({
'access_token': access_token,
'refresh_token': refresh_token,
'expires_in': expires_in
});
}
})
})
But i am still getting the error 400 and i can't seem to figure it out. Please i would really appreciate a response. Here is how i handled the code on my react native application
const [request2, response2, promptAsync2] = useAuthRequest({
clientId: clientID,
clientSecret: clientSecret,
scopes: [
'user-read-playback-state',
'user-modify-playback-state',
'user-read-currently-playing',
'streaming',
'playlist-read-private',
'playlist-read-collaborative',
'playlist-modify-private',
'playlist-modify-public',
'user-follow-modify',
'user-follow-read',
'user-read-playback-position',
'user-library-modify',
'user-library-read',
'user-read-email',
'user-read-private'
],
usePKCE: false,
redirectUri: makeRedirectUri({
scheme: undefined
})
},
discovery
)
useEffect(() => {
if (response2?.type === 'success') {
// get spotify access code
const { code } = response2.params;
const getSpotifyCode = async() =>{
const code2 = {
code
}
await axios.post('http://localhost:8005/get-spotify-access-code', code2).then(
response =>{
console.log(response);
}
).catch(error =>{
console.log(error)
})
}
getSpotifyCode()
}
}, [response2])
You should be match same port
Between running Expo port and Redirect URI of port in Spotify Developer Dashboard.
My redirect URL port is 3000
Expo running port is 3000
In package.json
Demo code
App.jspackage.jsonInstall dependencies
Run it
Result