使用客户端凭据流刷新 spotify 令牌
Posted
技术标签:
【中文标题】使用客户端凭据流刷新 spotify 令牌【英文标题】:Refresh spotify token with Client Credential flow 【发布时间】:2018-12-14 11:24:37 【问题描述】:我已经设置了正确的客户端凭据流,并且我可以获得我的令牌来拨打我的电话,但是在 3600 之后我想获得新的(我的应用程序仅使用“公共”spotify 端点) 我用https://github.com/thelinmichael/spotify-web-api-node。
对不起我的英语。
const express = require('express');
const router = express.Router();
const SpotifyWebApi = require('spotify-web-api-node');
// Create the api object with the credentials
const spotifyApi = new SpotifyWebApi(
clientId: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxx'
);
// Retrieve an access token.
spotifyApi.clientCredentialsGrant().then(
function(data)
console.log('The access token expires in ' + data.body['expires_in']);
console.log('The access token is ' + data.body['access_token']);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body['access_token']);
// console.log('The refresh token is ' + spotifyApi.getRefreshToken());
,
function(err)
console.log('Something went wrong when retrieving an access token', err);
);
router.get('/getArtistAlbums', function(req, res, next)
const user_id = req.query['id'];
spotifyApi
.getArtistAlbums(user_id,
limit: 10,
offset: 20
)
.then(
function(data)
res.send(data.body);
,
function(err)
console.error(err);
);
);
【问题讨论】:
【参考方案1】:而不是刷新获得的令牌(使用clientCredentialsGrant时无法刷新,只需请求一个新令牌即可。
//This function will create a new token every time it's called
function newToken()
spotifyApi.clientCredentialsGrant().then(
function(data)
...
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body['access_token']);
,
function(err)
... //Error management
);
//When the app starts, you might want to immediately get a new token
newToken();
//And set an interval to "refresh" it (actually creating a new one) every hour or so
tokenRefreshInterval = setInterval(newToken, 1000 * 60 * 60);
【讨论】:
以上是关于使用客户端凭据流刷新 spotify 令牌的主要内容,如果未能解决你的问题,请参考以下文章
无法通过具有客户端凭据流的 CloudFlare Worker 对 Spotify API 进行 OAuth