spotify应用程序请求授权

时间:2018-01-04 21:45:49

标签: ajax api web spotify access-token

我正在尝试访问令牌'来自spotify,使用以下代码。

=IF(AND(H2="Burn",I2="Yes"),"Outcome 1",IF(AND(H2="Burn",I2="No"),"Outcome 2",IF(AND(H2="Fixed",I2="Yes"),"Outcome 3",IF(AND(H2="Fixed",I2="No"),"Outcome 4"))))

但是我一直都会遇到错误:

    var encoded = btoa(client_id+':'+client_secret);
    function myOnClick() {
       console.log('clikced!');
       $.ajax({
       url: 'https://accounts.spotify.com/api/token',
       type: 'POST',
       data: {
            grant_type : "client_credentials",
           'Content-Type' : 'application/x-www-form-urlencoded'
       },
       headers: {
           Authorization: 'Basic ' + encoded
       },
       dataType: 'json'
       }).always((data)=> console.log(data));
       }

和         readyState:0,status:0

2 个答案:

答案 0 :(得分:4)

来自Spotify的Arielle。

看起来您正在使用客户端凭据流,这是您可以与Spotify API一起使用的3个身份验证流之一。 (你可以看看所有3 here

客户端凭据仅供服务器端使用,不应在前端使用,因为它需要您不应泄露的客户端密码!

您应该使用隐式授权流,而不是在浏览器中使用。它也很容易启动和运行!

// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
  if (item) {
    var parts = item.split('=');
    initial[parts[0]] = decodeURIComponent(parts[1]);
  }
  return initial;
}, {});
window.location.hash = '';

// Set token
let _token = hash.access_token;

const authEndpoint = 'https://accounts.spotify.com/authorize';

// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const redirectUri = 'http://localhost:8888';
const scopes = [
  'user-read-birthdate',
  'user-read-email',
  'user-read-private'
];

// If there is no token, redirect to Spotify authorization
if (!_token) {
  window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token`;
}

要点:https://gist.github.com/arirawr/f08a1e17db3a1f65ada2c17592757049

这是关于Glitch的一个例子,您可以“重新混音”制作副本并开始制作您的应用:https://glitch.com/edit/#!/spotify-implicit-grant

希望有所帮助 - 快乐的黑客攻击!

答案 1 :(得分:0)

const result = await axios({
  url: this.apiLoginUrl,
  method: 'post',
  data: "grant_type=client_credentials",
  headers: {
    'Authorization': `Basic ${Buffer.from(this.clientId + ":" + this.clientSecret).toString('base64')}`,
  },
});
相关问题