【问题标题】:Spotify API - Retrieving Valid Access Token in Google Apps ScriptsSpotify API - 在 Google Apps 脚本中检索有效的访问令牌
【发布时间】:2018-10-31 17:43:57
【问题描述】:

这里是 Spotify API 的文档(我使用的是隐式授权流程):https://beta.developer.spotify.com/documentation/general/guides/authorization-guide/#implicit-grant-flow

我正在尝试在 Google 表格中编写脚本。我专注于基本设置,但似乎无法让访问令牌正常工作。

已解决:

我目前收到以下错误(这似乎是我的 我的 fetch 方法的参数设置不正确):

"error":"unsupported_grant_type","error_description":"grant_type 必须是 client_credentials、authorization_code 或 refresh_token"

解决方案:

根据 Google 的规定,grant_type 必须列为有效负载 脚本方法 UrlFetchApp.fetch(请参阅下面的更新代码)

--

已解决:

正如您在下面看到的,我在尝试获取 令牌(尽管文档指定了“帖子”),因为帖子 方法始终返回 405 错误。我认为这是我要迈出的一步 搞砸了。我假设我不应该使用 csrf_token 作为访问令牌。

解决方案:

https://accounts.spotify.com/token 应该是 https://accounts.spotify.com/api/token

以下更新的工作代码:

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

【问题讨论】:

  • 您可以参考这个thread。您遇到该错误可能是因为您提供的访问令牌已过期。发生这种情况时,您需要获取新的访问令牌。您可能需要重新检查Spotify's developer site 上解释的授权流程。
  • 我认为令牌不会过期,我的代码运行时间不到 10 秒。 client_id 和 client_secret 没有变化(我已经在 Spotify 上检查了我的开发仪表板是否有任何变化)。我正在获取令牌(csrf_token)并立即使用它。
  • 我们可以询问您使用 POST 方法请求时的错误消息吗?
  • @Tanaike 这是 ContentText:{"error":"server_error","error_description":"Unexpected status: 405"}
  • 感谢您的回复。错误来自replaceResponse?

标签: javascript json google-apps-script spotify


【解决方案1】:

我按照文档的curl -X "POST" -H "Authorization: Basic ZjM4ZjAw...WY0MzE=" -d grant_type=client_credentials https://accounts.spotify.com/api/token 修改了用于检索访问令牌的脚本。你能试试这个修改过的脚本吗?

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())

参考:

如果回复信息有变化,请告诉我。

【讨论】:

  • 你打败了我!刚刚以同样的方式更新了我的代码并测试了它是否可以正常工作。谢谢!
  • 很高兴您的问题已完全解决。我也可以从你的问题中学习。也谢谢你。
猜你喜欢
  • 2015-11-11
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多