javascript - Nodejs - Spotify API 刷新 token

标签 javascript node.js discord.js spotify spotify-app

首先关。我以前没有使用过 API。
我遇到的问题是刷新 token 。作为重定向 URI 的查询参数返回的代码似乎每次都需要手动输入。当我获得该身份验证代码时,下面的代码会为我获取新的访问 token 以及刷新 token 。
我使用的包是spotify-web-api-node下面的代码是遵循他们的自述文件的结果。我也试过spotify-oauth-refresher但我对编码太陌生,无法弄清楚如何使用它。
我也尝试按照 Spotify 自己网站上的指南进行操作。但我自己似乎无法做到这一点。
希望得到一些指导。谢谢。
希望事情清楚。

 var scopes = ['user-read-private', 'user-read-email', 'playlist-read-private', 'playlist-modify-private'],
      redirectUri = '<redirect uri>',
      clientId = '<client id>',
      clientSecret = '<client secret>',
      state = '<random string>';
    
    var spotifyApi = new SpotifyWebApi({
      redirectUri: redirectUri,
      clientId: clientId,
      clientSecret: clientSecret
    });
    
    // Create the authorization URL
    var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
    
    console.log(authorizeURL);
    
    var credentials = {
      clientId: '<client id>',
      clientSecret: '<client secret>',
      redirectUri: '<redirect uri>'
    };
    
    var spotifyApi = new SpotifyWebApi(credentials);
    
    // The code that's returned as a query parameter to the redirect URI
    var code = 'I HAVE TO MANUALLY PUT THIS IN WHEN THE DURATION RUNS OUT';
    
    // Retrieve an access token and a refresh token
    spotifyApi.authorizationCodeGrant(code).then(
      function(data) {
        console.log('The token expires in ' + data.body['expires_in']);
        console.log('The access token is ' + data.body['access_token']);
        console.log('The refresh token is ' + data.body['refresh_token']);
    
        // Set the access token on the API object to use it in later calls
        spotifyApi.setAccessToken(data.body['access_token']);
        spotifyApi.setRefreshToken(data.body['refresh_token']);
      },
      function(err) {
        console.log('Something went wrong!', err);
      }
    );
    
    // clientId, clientSecret and refreshToken has been set on the api object previous to this call.
    spotifyApi.refreshAccessToken().then(
      function(data) {
        console.log('The access token has been refreshed!');
    
        // Save the access token so that it's used in future calls
        spotifyApi.setAccessToken(data.body['access_token']);
      },
      function(err) {
        console.log('Could not refresh access token', err);
      }
    );
编辑:我已经创建了一个可行的解决方案,并将在有时间时提交我的代码。希望今天。

最佳答案

我设法让它工作的方法是通过下面的代码:

const express = require('express');
const SpotifyWebApi = require('spotify-web-api-node');

var generateRandomString = function(length) {
    var text = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    for (var i = 0; i < length; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }

    return text;
};

var scopes = ['user-read-private', 'user-read-email', 'playlist-read-private', 'playlist-modify-private'],
    redirectUri = '<redirect uri>',
    clientId = '<client id>',
    clientSecret = '<client secret>',
    state = generateRandomString(16);

// Setting credentials can be done in the wrapper's constructor, or using the API object's setters.
var spotifyApi = new SpotifyWebApi({
    redirectUri: redirectUri,
    clientId: clientId,
    clientSecret: clientSecret
});

// Create the authorization URL
var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);

// https://accounts.spotify.com:443/authorize?client_id=5fe01282e44241328a84e7c5cc169165&response_type=code&redirect_uri=https://example.com/callback&scope=user-read-private%20user-read-email&state=some-state-of-my-choice
console.log(authorizeURL);

// --------------------------------

var credentials = {
    clientId: '<client id>',
    clientSecret: '<client secret>',
    redirectUri: '<redirect uri>'
};

var spotifyApi = new SpotifyWebApi(credentials);

var app = express();

app.get('/login', function(req, res) {
    res.redirect(authorizeURL);
});

// The code that's returned as a query parameter to the redirect URI
var code = '<authorization code>'; // this does not need to be updated

// Retrieve an access token and a refresh token
spotifyApi.authorizationCodeGrant(code).then(
    function(data) {
        console.log('The token expires in ' + data.body['expires_in']);
        console.log('The access token is ' + data.body['access_token']);
        console.log('The refresh token is ' + data.body['refresh_token']);

        // Set the access token on the API object to use it in later calls
        spotifyApi.setAccessToken(data.body['access_token']);
        spotifyApi.setRefreshToken(data.body['refresh_token']);
    },
    function(err) {
        console.log('Something went wrong!', err);
    }
);
// --------------------------------------------------
// clientId, clientSecret and refreshToken has been set on the api object previous to this call.
function refreshSpotifyToken() {
    spotifyApi.refreshAccessToken().then(
        function(data) {
            console.log('The access token has been refreshed!');

            // Save the access token so that it's used in future calls
            spotifyApi.setAccessToken(data.body['access_token']);
            console.log('The access token is ' + data.body['access_token']);
            console.log('The token expires in ' + data.body['expires_in']);
        },
        function(err) {
            console.log('Could not refresh access token', err);
        });
};
client.on('ready', () => {
    refreshSpotifyToken();
    setInterval(refreshSpotifyToken, 1000 * 59 * 59);
})

关于javascript - Nodejs - Spotify API 刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71833560/

相关文章:

javascript - 使用 node.js 通过 HTTP 将文件加密为字符串

javascript - 在浏览器 (javascript) 中将 Cognito 凭据与 AWS 结合使用时,不断出现 "missing credentials"错误

javascript - NodeJs 将 'net' 套接字转换为基于 SSL/TLS 的套接字?

javascript - 在 discord.js 中的时间限制之前获取收集的消息

javascript - Discord JS 嵌入 react 导致另一个嵌入

javascript - Discord JS - 当我加入更多公会时,使用 client.guilds 的 .cache 属性是否会导致错误?

javascript - 无法对不变多态类的数组进行建模

javascript - 这个 JavaScript/jQuery 语法是如何工作的 : (function( window, undefined ) { })(window)?

windows - Chocolatey、npm 和 grunt-cli 安装问题

node.js - 什么是最好的 node.js 集群?