Download the PHP package bjthecod3r/laravel-spotify-api-wrapper without Composer

On this page you can find all versions of the php package bjthecod3r/laravel-spotify-api-wrapper. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-spotify-api-wrapper

Laravel Spotify API Wrapper

A Laravel wrapper for the Spotify Web API. Search across tracks, albums, artists, playlists, shows, episodes, and audiobooks with a fluent facade and fully-typed responses.

Highlights

Requirements

Installation

Publish the config:

Add your Spotify app credentials to .env:

Search

Single-type search

The most common case — search one type, get a typed Paginated back:

Get a playlist

Search playlists hydrate as SimplifiedPlaylist summaries. Direct playlist lookups hydrate as Playlist so followers and paginated tracks.items are only present on the endpoint that returns them.

Get a single resource by ID

Direct lookups exist for every searchable resource, plus user profiles. They all return a fully-typed resource (the same classes the search endpoints hydrate), and accept ->market() where Spotify supports it.

Multi-type search

When you want several item types in one request:

Type strings work too if you'd rather skip the enum import:

Field filters

Spotify supports inline filters in the query string. Just pass them through:

Pagination

Typed resources

Every search response hydrates into objects under BjTheCod3r\Spotify\Resources\:

Resource Notable fields
Track name, durationMs, explicit, popularity, previewUrl, album, artists
Album name, albumType, totalTracks, releaseDate (Carbon), images, artists
Artist name, genres, popularity, images, followers (Followershref, total)
SimplifiedPlaylist name, description, public, owner (User), tracks (TracksLinkhref, total), items (PlaylistItemsLink), images
Playlist name, description, public, followers, owner (User), tracks (TracksLinkhref, total, items), images
Show name, description, publisher, totalEpisodes, images
Episode name, description, durationMs, releaseDate (Carbon), audioPreviewUrl
Audiobook name, description, authors (Author[]), narrators (Narrator[]), publisher, totalChapters
Image url, height, width
Paginated<T> items, total, limit, offset, next, previous, href

Date fields are real Illuminate\Support\Carbon instances. Spotify's date precision (year, month, day) is preserved on round-trip via releaseDatePrecision.

List fields (items, artists, images, genres, languages, authors, narrators, …) are Illuminate\Support\Collection instances, so you get the full Laravel Collection API:

Resources implement Arrayable + JsonSerializable, so this works:

Laravel will serialize the Paginated<Track> to JSON automatically.

Error handling

Status Exception
400 / 422 BjTheCod3r\Spotify\Exceptions\ValidationException
401 BjTheCod3r\Spotify\Exceptions\AuthenticationException (after a transparent token refresh + retry)
429 BjTheCod3r\Spotify\Exceptions\RateLimitException — exposes retryAfter in seconds
Other 4xx/5xx BjTheCod3r\Spotify\Exceptions\ApiException

All inherit from BjTheCod3r\Spotify\Exceptions\SpotifyException, so you can catch broadly:

Authentication

The package uses Spotify's Client Credentials grant — no user login required, suitable for any endpoint that doesn't need user context (Search, Browse, Albums, Artists, Tracks). Tokens are cached using Laravel's cache for the duration Spotify reports in expires_in, minus a small safety buffer, so you only hit the auth endpoint when a token actually needs refreshing.

User authentication

For endpoints that act on a listener's account — their playlists, library, top items, listening history — connect their Spotify account via the Authorization Code + PKCE flow.

About playback. The Spotify Web API does not return playable audio URLs even for authenticated users. Full playback is gated to Spotify's Web Playback SDK (browser, Premium) and the mobile SDKs. The user-auth surface here is for reading user data and (in a future release) controlling an active device, not for direct streaming.

Setup

Publish the migration that stores per-user tokens, then run it:

Tokens are encrypted at rest using Laravel's app key.

Set the OAuth redirect URI on your .env (and register the same value on the Spotify dashboard for your app):

The package registers three opt-in routes under the spotify prefix (configurable):

Method URI Name
GET /spotify/connect spotify.connect
GET /spotify/callback spotify.callback
POST /spotify/disconnect spotify.disconnect

Set spotify.oauth.routes.enabled to false (or env SPOTIFY_OAUTH_ROUTES_ENABLED=false) to disable them and wire your own controllers using the Spotify::redirect() / Spotify::handleCallback() helpers.

Connecting a user

Have the authenticated user hit the connect route — by default it requires the web + auth middleware:

Pass extra scopes via ?scopes=playlist-modify-public,user-modify-playback-state to merge with the configured defaults.

After consent, Spotify redirects to /spotify/callback. The controller exchanges the code, captures the listener's Spotify user id, persists encrypted tokens, dispatches SpotifyConnected, and redirects to oauth.after_connect.

If anything fails (state mismatch, user denied consent on Spotify, exchange error, …), the callback still redirects to oauth.after_connect but flashes a spotify.oauth.error payload onto the session so the destination can render error UX:

The reason is one of state_mismatch, user_denied, authorize_error, or exchange_failed; description carries the underlying Spotify error code or exception message.

Reading user data

All me() endpoints that return collections come back as the same Paginated resource the rest of the package uses. The me/tracks, me/albums, me/shows, me/episodes, and me/player/recently-played envelopes are unwrapped — the items collection contains the inner Track / Album / etc. directly. The added_at / played_at timestamps from those envelopes are not exposed in v0.3.

Token refresh & 401 handling

Access tokens are refreshed transparently when stale. A 401 from any API call forces an out-of-band refresh and retries the original request once, so a token revoked between issuance and use is recovered automatically.

If Spotify rejects the refresh token (invalid_grant) — typically because the user revoked access from their Spotify settings — the stored row is deleted and SpotifyDisconnected is fired with reason = invalid_grant, so your app can prompt the user to reconnect.

Concurrent refreshes are serialised per-user via Cache::lock, so a fan-out of queue workers doesn't double-spend a rotating refresh token.

Events

Listen for any of these to integrate with your app:

Event When
SpotifyConnected After a successful callback exchange.
SpotifyTokenRefreshed After any successful refresh-token grant.
SpotifyDisconnected On explicit disconnect() or invalid_grant from refresh.
SpotifyConnectFailed State mismatch, user denied consent, authorize error, exchange failure.

Disconnecting

Or POST to route('spotify.disconnect') from a form. The default route stack includes web middleware, so the form must carry a CSRF token:

Custom token storage

The default Eloquent-backed repository covers most apps. To swap implementations (Redis, encrypted file, another DB connection), implement BjTheCod3r\Spotify\Contracts\UserTokenRepository and point at it:

Testing

The package ships with Pest + Orchestra Testbench:

In your own application's tests, fake the HTTP layer with Laravel's standard helpers:

Roadmap

License

MIT.


All versions of laravel-spotify-api-wrapper with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
illuminate/contracts Version ^11.0|^12.0|^13.0
illuminate/http Version ^11.0|^12.0|^13.0
illuminate/support Version ^11.0|^12.0|^13.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package bjthecod3r/laravel-spotify-api-wrapper contains the following files

Loading the files please wait ...