Installation:
composer require jwilsson/spotify-web-api-php
Add the package to your config/app.php under providers (if using Laravel services).
First Use Case: Authenticate and fetch user's top tracks:
use SpotifyWebApi\SpotifyWebApi;
$spotify = new SpotifyWebApi(
env('SPOTIFY_CLIENT_ID'),
env('SPOTIFY_CLIENT_SECRET'),
env('SPOTIFY_REDIRECT_URI')
);
// After OAuth flow, get an access token and refresh token
$token = $spotify->getAccessToken();
// Set the access token
$spotify->setAccessToken($token);
// Fetch top tracks (time_range: short_term, long_term, medium_term)
$topTracks = $spotify->getMyTopTracks('short_term');
Key Files:
config/spotify.php (if publishing config via service provider).routes/web.php (for OAuth redirect handling).OAuth Flow:
$authUrl = $spotify->getLoginUrl(['scope' => 'user-top-read']);
return redirect($authUrl);
$token = $spotify->getAccessToken('auth_code', $request->code);
session(['spotify_token' => $token]);
API Calls:
$spotify->batch([
['method' => 'GET', 'path' => '/me'],
['method' => 'GET', 'path' => '/me/top/tracks'],
]);
$tracks = $spotify->getMyTopTracks('short_term', ['limit' => 20]);
while ($tracks->next) {
$tracks = $spotify->getNextPage($tracks);
}
Service Integration:
public function register()
{
$this->app->singleton(SpotifyWebApi::class, function ($app) {
return new SpotifyWebApi(
config('spotify.client_id'),
config('spotify.client_secret'),
config('spotify.redirect_uri')
);
});
}
public function __construct(private SpotifyWebApi $spotify) {}
Caching Responses:
return Cache::remember('user_top_tracks', now()->addHours(24), function () {
return $this->spotify->getMyTopTracks('short_term');
});
Token Expiry:
SpotifyWebApi\Exceptions\SpotifyWebApiException for expired tokens.try {
$spotify->getMyCurrentPlayingTrack();
} catch (\SpotifyWebApi\Exceptions\SpotifyWebApiException $e) {
if ($e->getCode() === 401) {
$token = $spotify->refreshAccessToken($refreshToken);
$spotify->setAccessToken($token);
retry();
}
}
Rate Limiting:
429 errors:
if ($e->getCode() === 429) {
sleep($e->getRetryAfter());
}
Scope Management:
user-top-read vs. user-library-read). Over-scoping can lead to auth failures.Redirect URI Mismatch:
SPOTIFY_REDIRECT_URI in .env matches Spotify’s registered URI. Mismatches cause redirect_uri_mismatch errors.$spotify->debug = true; // Logs HTTP requests/responses
401 Unauthorized: Token expired or invalid.403 Forbidden: Missing/invalid scope.404 Not Found: Invalid endpoint or ID.Environment Variables:
Store credentials in .env:
SPOTIFY_CLIENT_ID=your_id
SPOTIFY_CLIENT_SECRET=your_secret
SPOTIFY_REDIRECT_URI=http://your-app.com/callback
Testing:
$spotify->setAccessToken('test_token');
$spotify->setBasePath('https://api.spotify.com/test');
Extensions:
$spotify->get('/private-endpoint', ['query' => 'params']);
spotify-web-api-php to verify webhook signatures:
$spotify->verifyWebhook($request->header('X-Spotify-Signature'));
Performance:
How can I help you explore Laravel packages today?