-
Notifications
You must be signed in to change notification settings - Fork 499
/
access-token-refresh.js
86 lines (76 loc) · 2.76 KB
/
access-token-refresh.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const SpotifyWebApi = require('../');
/**
* This example refreshes an access token. Refreshing access tokens is only possible access tokens received using the
* Authorization Code flow, documented here: https://developer.spotify.com/spotify-web-api/authorization-guide/#authorization_code_flow
*/
/* Retrieve an authorization code as documented here:
* https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
* or in the Authorization section of the README.
*
* Codes are given for a set of scopes. For this example, the scopes are user-read-private and user-read-email.
* Scopes are documented here:
* https://developer.spotify.com/documentation/general/guides/scopes/
*/
const authorizationCode =
'<insert authorization code with user-read-private and user-read-email scopes>';
/**
* Get the credentials from Spotify's Dashboard page.
* https://developer.spotify.com/dashboard/applications
*/
const spotifyApi = new SpotifyWebApi({
clientId: '<insert client id>',
clientSecret: '<insert client secret>',
redirectUri: '<insert redirect URI>'
});
// When our access token will expire
let tokenExpirationEpoch;
// First retrieve an access token
spotifyApi.authorizationCodeGrant(authorizationCode).then(
function(data) {
// Set the access token and refresh token
spotifyApi.setAccessToken(data.body['access_token']);
spotifyApi.setRefreshToken(data.body['refresh_token']);
// Save the amount of seconds until the access token expired
tokenExpirationEpoch =
new Date().getTime() / 1000 + data.body['expires_in'];
console.log(
'Retrieved token. It expires in ' +
Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) +
' seconds!'
);
},
function(err) {
console.log(
'Something went wrong when retrieving the access token!',
err.message
);
}
);
// Continually print out the time left until the token expires..
let numberOfTimesUpdated = 0;
setInterval(function() {
console.log(
'Time left: ' +
Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) +
' seconds left!'
);
// OK, we need to refresh the token. Stop printing and refresh.
if (++numberOfTimesUpdated > 5) {
clearInterval(this);
// Refresh token and print the new time to expiration.
spotifyApi.refreshAccessToken().then(
function(data) {
tokenExpirationEpoch =
new Date().getTime() / 1000 + data.body['expires_in'];
console.log(
'Refreshed token. It now expires in ' +
Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) +
' seconds!'
);
},
function(err) {
console.log('Could not refresh the token!', err.message);
}
);
}
}, 1000);