-
-
Notifications
You must be signed in to change notification settings - Fork 9
Example Usage with Code
Kiril Kirkov edited this page Feb 27, 2022
·
1 revision
Install with composer:
composer require kirilkirkov/spotify-webapi-sdk
or download the repository.
Get the refresh token and access token
<?php
require 'vendor/autoload.php';
use SpotifyWebAPI\SpotifyWebApi;
$credentails = [
'clientId' => '2f0f18b01ab0431abdacba3274f0a021',
'clientSecret' => 'a70e287bd86346318ea0814577a466d4',
];
$callBackUrl = 'http://localhost/test/';
// Redirect to spotify for authorization
if(!isset($_GET['code'])) {
try {
$spotifyWebApi = new SpotifyWebApi($credentails);
$url = $spotifyWebApi->getUrlForCodeToken($callBackUrl);
header("Location: {$url}");
} catch(\SpotifyWebAPI\SpotifyWebAPIException $e) {
echo $e->getMessage();
}
}
// Returned from spotify - get access and refresh token
if(isset($_GET['code'])) {
try {
$spotifyWebApi = new SpotifyWebApi($credentails);
$tokens = $spotifyWebApi->getAccessTokenWithCode(
$_GET['code'],
$callBackUrl
);
echo "Token: {$tokens->access_token}<br>";
echo "Refresh token: {$tokens->refresh_token}";
} catch(\SpotifyWebAPI\SpotifyWebAPIException $e) {
echo $e->getMessage();
}
}
Save you tokens, then call whatever you want:
<?php
require 'vendor/autoload.php';
use SpotifyWebAPI\SpotifyWebApi;
function getResults($search) {
try {
$spotifyWebApi = new SpotifyWebApi([
'clientId' => 'YOUR_CLIENT_ID',
'clientSecret' => 'YOUR_SECRED_ID',
'accessToken' => 'YOUR_ACCESS_TOKEN', // comes from variable
'refreshToken' => 'YOUR_REFRESH_TOKEN',
]);
$spotifyWebApi->returnNewTokenIfIsExpired(true);
$response = $spotifyWebApi->api()->provider(
\SpotifyWebAPI\SpotifyServices::search()::search($search, 'artist,album,track,playlist')
)->getResult();
if(property_exists($response, 'access_token')) {
// UPDATE YOUR TOKEN (MAYBE IN DATABASE)
// $response->access_token
return getResults($search);
}
// BOOM! Your results.
var_dump($response);
} catch(\SpotifyWebAPI\SpotifyWebAPIException $e) {
echo $e->getMessage();
}
}
getResults('prodigy');