Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Spotify Web Api Php Laravel Package

jwilsson/spotify-web-api-php

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require jwilsson/spotify-web-api-php
    

    Add the package to your config/app.php under providers (if using Laravel services).

  2. 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');
    
  3. Key Files:

    • config/spotify.php (if publishing config via service provider).
    • routes/web.php (for OAuth redirect handling).

Implementation Patterns

Workflows

  1. OAuth Flow:

    • Redirect users to Spotify for auth:
      $authUrl = $spotify->getLoginUrl(['scope' => 'user-top-read']);
      return redirect($authUrl);
      
    • Handle callback in a route:
      $token = $spotify->getAccessToken('auth_code', $request->code);
      session(['spotify_token' => $token]);
      
  2. API Calls:

    • Batch Requests (for efficiency):
      $spotify->batch([
          ['method' => 'GET', 'path' => '/me'],
          ['method' => 'GET', 'path' => '/me/top/tracks'],
      ]);
      
    • Paginated Responses:
      $tracks = $spotify->getMyTopTracks('short_term', ['limit' => 20]);
      while ($tracks->next) {
          $tracks = $spotify->getNextPage($tracks);
      }
      
  3. Service Integration:

    • Laravel Service Provider:
      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')
              );
          });
      }
      
    • Dependency Injection:
      public function __construct(private SpotifyWebApi $spotify) {}
      
  4. Caching Responses:

    • Cache API responses (e.g., top tracks) for 24 hours:
      return Cache::remember('user_top_tracks', now()->addHours(24), function () {
          return $this->spotify->getMyTopTracks('short_term');
      });
      

Gotchas and Tips

Pitfalls

  1. Token Expiry:

    • Always handle SpotifyWebApi\Exceptions\SpotifyWebApiException for expired tokens.
    • Refresh tokens proactively:
      try {
          $spotify->getMyCurrentPlayingTrack();
      } catch (\SpotifyWebApi\Exceptions\SpotifyWebApiException $e) {
          if ($e->getCode() === 401) {
              $token = $spotify->refreshAccessToken($refreshToken);
              $spotify->setAccessToken($token);
              retry();
          }
      }
      
  2. Rate Limiting:

    • Spotify enforces rate limits. Implement exponential backoff for 429 errors:
      if ($e->getCode() === 429) {
          sleep($e->getRetryAfter());
      }
      
  3. Scope Management:

    • Ensure your app requests only necessary scopes (e.g., user-top-read vs. user-library-read). Over-scoping can lead to auth failures.
  4. Redirect URI Mismatch:

    • Double-check SPOTIFY_REDIRECT_URI in .env matches Spotify’s registered URI. Mismatches cause redirect_uri_mismatch errors.

Debugging

  • Enable Debugging:
    $spotify->debug = true; // Logs HTTP requests/responses
    
  • Common Errors:
    • 401 Unauthorized: Token expired or invalid.
    • 403 Forbidden: Missing/invalid scope.
    • 404 Not Found: Invalid endpoint or ID.

Tips

  1. Environment Variables: Store credentials in .env:

    SPOTIFY_CLIENT_ID=your_id
    SPOTIFY_CLIENT_SECRET=your_secret
    SPOTIFY_REDIRECT_URI=http://your-app.com/callback
    
  2. Testing:

    • Use Spotify’s test credentials for local testing.
    • Mock the API in PHPUnit:
      $spotify->setAccessToken('test_token');
      $spotify->setBasePath('https://api.spotify.com/test');
      
  3. Extensions:

    • Custom Endpoints: Extend the client for private endpoints:
      $spotify->get('/private-endpoint', ['query' => 'params']);
      
    • Webhooks: Use spotify-web-api-php to verify webhook signatures:
      $spotify->verifyWebhook($request->header('X-Spotify-Signature'));
      
  4. Performance:

    • Batch Requests: Reduce HTTP calls by batching (e.g., fetch multiple track details at once).
    • Async Processing: Use Laravel Queues for long-running tasks (e.g., playlist generation).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views