【问题标题】:Spotify API OauthSpotify API 认证
【发布时间】:2020-06-20 10:34:15
【问题描述】:

我正在尝试创建一个网站,让登录的用户可以从他们各自的 Spotify 帐户收听他们的播放列表。我关注了web-playback-sdk

我能够将我的 spotify 帐户与浏览器连接起来。但我希望每个用户都能从他们的 Spotify 帐户中收听最喜欢的歌曲。为此,我想使用 spotify Oauth,但我对阅读文档感到困惑。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: api spotify


    【解决方案1】:

    这里有两个函数可以帮助您使用 Implicit Grant Flow 初始化 Spotify Web Playback SDK 以获取临时 OAuth 令牌。 如果想要可刷新的用户授权,需要使用Authorization Code Flow

    function logInWithSpotify() {
      const clientId = '<insert-client-id>'; // Get ClientID from https://developer.spotify.com/dashboard/
      const redirectUrl = '<insert-redirect-uri>'; // Add redirect URIs to the whitelist in the settings https://developer.spotify.com/dashboard/
      const scopes = ['streaming', 'user-read-email', 'user-read-private']; // Required scopes
    
      // Implicit Grant Authorization Flow
      // More info: https://developer.spotify.com/documentation/general/guides/authorization-guide/#authorization-code-flow
      window.location = [
        'https://accounts.spotify.com/authorize',
        `?client_id=${clientId}`,
        `&scope=${encodeURIComponent(scopes.join(' '))}`,
        `&redirect_uri=${encodeURIComponent(redirectUrl)}`,
        '&response_type=token',
        '&show_dialog=true',
      ].join('');
    }
    
    function getOAuthToken(cb) {
      const hash = window.location.hash
        .substring(1)
        .split('&')
        .reduce((values, item) => {
          if (item) {
            const [key, value] = item.split('=');
            values[key] = decodeURIComponent(value);
          }
          return values;
        }, {});
      // Clear the hash
      window.location.hash = '';
    
      const accessToken = hash.access_token;
      if (!accessToken) logInWithSpotify();
      cb(accessToken);
    }
    
    const player = new Spotify.Player({
      name: 'Web Playback SDK Quick Start Player',
      getOAuthToken: getOAuthToken,
    });
    

    这里是关于如何使用 Spotify Web Playback SDK 的更详细的要点:https://gist.github.com/lundgren2/4a5c7a1ba7916bbcf460901620166ab2

    【讨论】:

      猜你喜欢
      • 2016-11-02
      • 2020-07-05
      • 2020-06-18
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 2015-08-06
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多