Skip to content

Instantly share code, notes, and snippets.

@codemasher
Created September 22, 2022 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codemasher/cacbc109755a597cf193932cdfc75d58 to your computer and use it in GitHub Desktop.
Save codemasher/cacbc109755a597cf193932cdfc75d58 to your computer and use it in GitHub Desktop.
Spotify lyrics API fetch proof of concept
<?php
/**
* spotify lyrics proof-of-concept
*
* @created 22.09.2022
* @author smiley <smiley@chillerlan.net>
* @copyright 2022 smiley
* @license MIT
*/
use chillerlan\HTTP\HTTPOptions;
use chillerlan\HTTP\Psr18\CurlClient;
use chillerlan\HTTP\Psr7\Request;
use chillerlan\HTTP\Psr7\Uri;
use Psr\Http\Client\ClientInterface;
use function chillerlan\HTTP\Utils\decompress_content;
use function chillerlan\HTTP\Utils\get_json;
use function chillerlan\HTTP\Utils\message_to_string;
require_once __DIR__.'/../vendor/autoload.php';
// invoke http client
// @see https://github.com/chillerlan/php-httpinterface
$options = new HTTPOptions([
'ca_info' => __DIR__.'/../config/cacert.pem', // https://curl.haxx.se/ca/cacert.pem
'user_agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36',
]);
$http = new CurlClient($options);
// fetch an anonymous access token
$token = fetch_token($http);
// https://open.spotify.com/track/2OcLJRW0pTyYAxT43N5ccm
$trackID = '2OcLJRW0pTyYAxT43N5ccm?si=b27ec99fa3f14edf';
$json = get_lyrics($http, $token, $trackID);
if(isset($json->lyrics->lines)){
var_dump(implode(PHP_EOL, array_column($json->lyrics->lines, 'words')));
}
// end - static function declarations below
exit;
/**
* @throws \Exception
*/
function fetch_token(ClientInterface $http):string{
$tokenRequest = new Request('GET', new Uri('https://open.spotify.com/get_access_token'));
$tokenResponse = $http->sendRequest($tokenRequest);
if($tokenResponse->getStatusCode() !== 200){
throw new Exception('could not obtain token');
}
$token = get_json($tokenResponse);
return $token->accessToken;
}
/**
* @return mixed
* @throws \Exception
*/
function get_lyrics(ClientInterface $http, string $token, string $trackID){
$apiUri = (new Uri('https://spclient.wg.spotify.com/color-lyrics/v2/seo/track/'.$trackID))
->withQuery(http_build_query(['market' => 'from_token']))
;
$request = (new Request('GET', $apiUri))
->withHeader('Accept', 'application/json')
->withHeader('Accept-Encoding', 'gzip, deflate')
->withHeader('Authorization', sprintf('Bearer %s', $token))
;
$response = $http->sendRequest($request);
if($response->getStatusCode() !== 200){
throw new Exception(sprintf(
"request failed (HTTP/%s)\n\n%s%s\n",
$response->getStatusCode(),
message_to_string($request),
message_to_string($response),
));
}
return json_decode(decompress_content($response));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment