使用Spotify API尝试使用webapp。对Spotify Developer网站上的所有数据设置都满意(client_id,client_secret等)。 当我在控制台中运行以下内容时......
curl -H "Authorization: Bearer <the actual access token>" https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V
......它完美无缺。即使直接在浏览器中运行以下URL也可以:
https://api.spotify.com/v1/tracks/2TpxZ7JUBn3uw46aR7qd6V?access_token=<the actual access token>
我尝试在下面的方法中将访问令牌标记到url,但没有运气。如果我尝试在标题和网址中使用访问令牌,我会收到错误,告诉我使用其中一个。
<?php
session_start();
class SpotifyClientCredentials
{
public $url = 'https://accounts.spotify.com/api/token';
public $client_id = '<the client id>';
public $client_secret = '<the client secret>';
public $token = false;
public function __construct()
{
if(isset($_SESSION['token'])) $this->token = $_SESSION['token'];
}
public function connect()
{
$enc = base64_encode($this->client_id. ':' . $this->client_secret);
$header = "Authorization: Basic $enc";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $this->url,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER => false, //workaround prevent CA error
CURLOPT_HTTPHEADER => [$header],
CURLOPT_POSTFIELDS => 'grant_type=client_credentials'
));
$result = curl_exec($ch);
if ($result === false)
{
print_r('Curl error: ' . curl_error($ch));
}else{
$data = json_decode($result,true);
$this->token = $data['access_token'];
$_SESSION['token'] = $this->token;
}
curl_close($ch);
}
public function request($requestUrl)
{
if(!$this->token) $this->connect();
$header = "Authorization: Bearer {$this->token}";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => $requestUrl,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER => false, //workaround prevent CA error
CURLOPT_HTTPHEADER => [$header]
));
$result = curl_exec($ch);
if ($result === false)
{
print_r('Curl error: ' . curl_error($ch));
}else{
$data = json_decode($result, true);
print_r($data);
}
curl_close($ch);
}
}
$spfy = new SpotifyClientCredentials;
$spfy->request('https://api.spotify.com/v1/albums/4aawyAB9vmqN3uQ7FjRGTy');
摆脱CURLOPT_POST => true
,提供 502 Bad Gateway 。
我没有得到任何响应/输出代码,如上所述。
如上所述,将访问令牌标记为requestUrl:
CURLOPT_URL => $requestUrl . '?access_token=' . $this->token,
给出以下卷曲响应:
Array ( [error] => Array ( [status] => 400 [message] => Must not use more than one method for including an access token ) )
如果我然后评论CURLOPT_HTTPHEADER
,我再一次得不到答复。
访问令牌看起来有效,因为当我不包含它时,我收到一条错误消息。真的不知所措 - 感谢任何帮助。