Skip to content

Instantly share code, notes, and snippets.

@hycday
Last active March 2, 2017 23:04
Show Gist options
  • Save hycday/4538dc15f829b2fc847f738d9e47cf36 to your computer and use it in GitHub Desktop.
Save hycday/4538dc15f829b2fc847f738d9e47cf36 to your computer and use it in GitHub Desktop.
Spotify Web API PHP Auth + getMyHistory example
<?php
//file should be named index.php, and placed in callback subdirectories
error_reporting(-1);
ini_set('display_errors', 1);
require '../vendor/autoload.php';
$session = new SpotifyWebAPI\Session('CLIENT_ID', 'CLIENT_SECRET', 'https://mysite.com/callback');
$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
$session->requestAccessToken($_GET['code']);
session_start();
$_SESSION['token'] = $session->getAccessToken();
$_SESSION['expirein'] = time();
header('Location: ../');
} else {
$scopes = [
'scope' => [
'user-read-email',
'user-library-modify',
'user-read-recently-played'
],
];
header('Location: ' . $session->getAuthorizeUrl($scopes));
}
<?php
error_reporting(-1);
ini_set('display_errors', 1);
require 'vendor/autoload.php';
$session = new SpotifyWebAPI\Session('CLIENT_ID', 'CLIENT_SECRET', 'https://mysite.com/callback');
session_start();
$inactive = 3600;
$session_life = time() - $_SESSION['expirein'];
if (isset($_SESSION['token']) && ($session_life < $inactive)) {
$api = new SpotifyWebAPI\SpotifyWebAPI();
$accessToken = $_SESSION['token'];
$api->setAccessToken($accessToken);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Spotify History Tracks</title>
</head>
<style type="text/css">
* {margin: 0; padding: 0;}
div { margin: 20px;}
ul { list-style-type: none; width: 800px;}
h3 { font: bold 16px/1.5 Helvetica, Verdana, sans-serif;}
h1 { font: bold 20px/1.5 Helvetica, Verdana, sans-serif;}
a {color:#000000;}
li img { float: left; margin: 0 15px 0 0;}
li p { font: 200 12px/1.5 Georgia, Times New Roman, serif;}
li { padding: 10px; overflow: auto;}
li:hover { background: #eee; }
</style>
<body>
<div>
<h1>Spotify History Tracks (Descending order)</h1>
<ul>
<?php
$milliseconds = round(microtime(true) * 1000);
$limitfetch = 15;
$artist = $api->getMyHistory(array('limit' => $limitfetch, 'before' => $milliseconds));
function formatSeconds( $input )
{
$uSec = $input % 1000;
$input = floor($input / 1000);
$seconds = $input % 60;
$input = floor($input / 60);
$minutes = $input % 60;
$input = floor($input / 60);
$hours = $input % 60;
$input = floor($input / 60);
$seconds = sprintf("%02d", $seconds);
$minutes = sprintf("%02d", $minutes);
$hours = sprintf("%02d", $hours);
$fullduration = ($hours > 0) ? $hours.'h '.$minutes.'min '.$seconds.'s' : $minutes.'min '.$seconds.'s';
return $fullduration;
}
for ($i=0; $i < $artist->limit ; $i++) {
//link to spotify page
$linkpage = $artist->items[$i]->track->external_urls->spotify;
//to get the album image
$track = $api->getTrack($artist->items[$i]->track->id);
$getlastimageposition = count($track->album->images) - 1; //array is as follow [big, middle, small] so small = -1 / small = -2/ big = -3
$albumcover = $track->album->images[$getlastimageposition]->url;
//to get the featuring list, if more than one artist
$arr_length = count($artist->items[$i]->track->artists);
$artistsfeaturing = '';
for($j=0;$j<$arr_length;$j++) {
$artistsfeaturing .= '<a href="'. $artist->items[$i]->track->artists[$j]->external_urls->spotify
.'" target="_blank">'. $artist->items[$i]->track->artists[$j]->name . '</a>, ';
}
$artistsfeaturing = substr($artistsfeaturing, 0, -2);
//to get trackname + link
$trackname = '<a href="'. $linkpage .'" target="_blank">'. $artist->items[$i]->track->name .'</a>';
//to get duration of track
$duration = formatSeconds($artist->items[$i]->track->duration_ms);
//to get time in nice format (from ISO8601 to Date format) + 7h of time difference
$playeddate = date('d M Y - \a\t G:i:s', (strtotime($artist->items[$i]->played_at)+60*60*7));
echo '<li>';
echo '<a href="'.$linkpage.'" target="_blank">';
echo '<img src="'.$albumcover.'" />';
echo '</a>';
echo '<h3>'.$artistsfeaturing.' - '. $trackname . '</h3>';
echo '<p> Track was played on : '. $playeddate .'</p>';
echo '<p> URI of track is : <a href="'.$artist->items[$i]->track->uri.'">'. $artist->items[$i]->track->uri .'</a></p>';
echo '<p> Track duration : '. $duration .'</p>';
echo '</li>';
}
?>
</ul>
</div>
</body>
</html>
<?php
} else {
$scopes = array(
'scope' => array(
'user-read-email',
'user-library-modify',
'user-read-recently-played'
),
);
header('Location: ' . $session->getAuthorizeUrl($scopes));
} ?>
@hycday
Copy link
Author

hycday commented Mar 2, 2017

added the check on the 3600s expiration on the token, to renew if expired

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment