$spotify_track = '1HbcclMpw0q2WDWpdGCKdS';
$client_id = '[my_id]';
$client_secret = '[my_secret]';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'https://accounts.spotify.com/api/token' );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($curl, CURLOPT_POST, 1 );
curl_setopt($curl, CURLOPT_POSTFIELDS, 'grant_type=client_credentials' );
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Authorization: Basic '.base64_encode($client_id.':'.$client_secret)));
$response = curl_exec($curl);
$token = json_decode($response)->access_token;
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
curl_close($curl);
} else {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.spotify.com/v1/audio-features/".$spotify_track,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"Authorization: Bearer ".$token,
),
));
$track_info = curl_exec($curl);
var_dump($track_info);
curl_close($curl);
}
I've modified the code suggested on stackoverflow and came up with my own solution. I successfully fetch the song information. However, I wonder if this is the proper way in handling API using curl in php. I also noticed the page reloads a little bit slower compared to without the code aforementioned.