Spotify API - Retrieving Valid Access Token in Goo

2019-07-08 10:52发布

问题:

Here is the documentation for the Spotify API (I'm using the Implicit Grant Flow): https://beta.developer.spotify.com/documentation/general/guides/authorization-guide/#implicit-grant-flow

I'm trying to write a script in Google Sheets. I'm focussing on the basic setup, but I cannot seem to get the access token working.

SOLVED:

I'm currently receiving the following error (it seems like my parameters for my fetch method aren't set properly):

"error":"unsupported_grant_type","error_description":"grant_type must be client_credentials, authorization_code or refresh_token"

SOLUTION:

The grant_type must be listed as a payload according to the Google Scripts method UrlFetchApp.fetch (see updated code below)

--

SOLVED:

As you can see below I'm using the 'get' method when trying to get the token (despite the documentation specifying 'post') because the post method consistently returns a 405 error. I think this is the step I'm screwing up on. I'm assuming that I'm not supposed to be using the csrf_token as the access token.

SOLUTION:

https://accounts.spotify.com/token should have been https://accounts.spotify.com/api/token

Updated working code below:

  var fetchParams = {
    'method':'post',
    'payload':{'grant_type':'client_credentials'},
    'headers':{'Authorization':authorization},
    'muteHttpExceptions':true
  }

  var replaceResponse = UrlFetchApp.fetch('https://accounts.spotify.com/api/token', fetchParams);

  var regExp = /access_token(.*?):/;

  var contentText = replaceResponse.getContentText();
  var access_token = contentText.slice(contentText.search('access_token')+15,contentText.search(',')-1);

  var requestOptions = {
    'headers':{'Authorization':'Bearer '+access_token},
    'muteHttpExceptions':true
  }

  var finalResponse = UrlFetchApp.fetch('https://api.spotify.com/v1/tracks/4dhARBZ8YLvm8oRDnCIeXr', requestOptions);

回答1:

I modified your script for retrieving access token by following curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token of the document. Can you please try this modified script?

var authorization = "Basic "+ Utilities.base64Encode('<client_id>:<client_secret>');
var fetchParams = {
  method: 'post', // Modified
  payload: {'grant_type': 'client_credentials'}, // Modified
  headers: {'Authorization': authorization},
  muteHttpExceptions: true
}
var replaceResponse = UrlFetchApp.fetch("https://accounts.spotify.com/api/token", fetchParams); // Modified
Logger.log(replaceResponse.getContentText())

Reference :

  • Client Credentials Flow

If the response message was changed, please tell me.