Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

273
Views
Nodejs: token de actualización de la API de Spotify

Antes que nada. No he trabajado con API antes.

El problema que tengo es actualizar el token. Parece que el código que se devuelve como un parámetro de consulta al URI de redireccionamiento debe ingresarse manualmente cada vez. Cuando obtengo ese código de autenticación, el siguiente código me da el nuevo token de acceso, así como el token de actualización.

El paquete que uso es spotify-web-api-node y el siguiente código es el resultado de seguir su archivo Léame. También probé spotify-oauth-refresher pero soy demasiado nuevo en la codificación para descubrir cómo usarlo.

También intenté seguir la guía en el sitio web de Spotify. Pero no parece ser capaz de hacerlo bien por mí mismo.

Me encantaría alguna orientación. Gracias. Espero que las cosas estén claras.

 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); } );

EDITAR: he creado una solución funcional y enviaré mi código cuando tenga tiempo. Ojalá hoy.

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

La forma en que logré que esto funcionara fue mediante el siguiente código:

 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); })
about 4 years ago · Santiago Trujillo Report

0

Puede encontrar información sobre las mejores prácticas Auth Flow directamente desde Spotify en el siguiente enlace. Incluye fragmentos de código que detallan cómo y cuándo quieren que publique el token de actualización para un nuevo token de acceso.

https://developer.spotify.com/documentation/general/guides/authorization/code-flow/

Este es el punto final que recomiendan para actualizar su token cuando detecta que un token de acceso ha caducado o su solicitud de datos falló debido a un token de acceso caducado.

 app.get('/refresh_token', function(req, res) { var refresh_token = req.query.refresh_token; var authOptions = { url: 'https://accounts.spotify.com/api/token', headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) }, form: { grant_type: 'refresh_token', refresh_token: refresh_token }, json: true }; request.post(authOptions, function(error, response, body) { if (!error && response.statusCode === 200) { var access_token = body.access_token; res.send({ 'access_token': access_token }); } }); });

La respuesta será algo como esto:

 { "access_token": "NgCXRK...MzYjw", "token_type": "Bearer", "scope": "user-read-private user-read-email", "expires_in": 3600, "refresh_token": "NgAagA...Um_SHo" }

TLDR: verifica si su token de acceso ha caducado, si es así, PUBLICAR el token de actualización para recibir un nuevo token de acceso que luego se puede usar nuevamente para OBTENER datos. También recibe un nuevo token de actualización junto con la respuesta de este y el proceso comienza de nuevo.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!