Spotify Web API - Client Credentials - Accessing a users playlists

3.4k views Asked by At

I'm trying to access users playlist tracks by using the client credentials flow.

Spotify getting playlist documentation: https://developer.spotify.com/web-api/get-playlists-tracks/

Spotify getting client credentials documentation: https://developer.spotify.com/web-api/authorization-guide/

First question, is it possible to get a users playlist tracks using client credentials flow? I'm using this flow since I'm unable to pop up a login box for the user to login.

Secondly, I've tried using https://github.com/jwilsson/spotify-web-api-php client credentials flow (Docs: http://jwilsson.github.io/spotify-web-api-php/authorization.html) by practically copying the code at the bottom of that page:

    <?php

include('vendor/autoload.php');

$session = new SpotifyWebAPI\Session('Tobys client id', 'Tobys secret', 'http://localhost/callback');
// Request a access token with optional scopes
$scopes = array(
    'playlist-read-private',
    'user-read-private'
);

$session->requestCredentialsToken($scopes);
$accessToken = $session->getAccessToken(); // We're good to go!

// Set the code on the API wrapper
$api->setAccessToken($accessToken);

$playlists = $api->getUserPlaylists('USER_ID', array(
    'limit' => 5
));

foreach ($playlists->items as $playlist) {
    echo '<a href="' . $playlist->external_urls->spotify . '">' . $playlist->name . '</a> <br>';
}

This gives me Notice: Undefined variable: api in /var/www/html/dev/testing.php on line 16

I've also tried creating the API variable using $api = new SpotifyWebAPI\SpotifyWebAPI(); but this says I need user information/ tokens.

Thanks.

1

There are 1 answers

2
Michael Thelin On BEST ANSWER

First question, is it possible to get a users playlist tracks using client credentials flow?

Yes, retrieving tracks for a playlist doesn't require user authentication as part of the access token.

I've also tried creating the API variable using $api = new SpotifyWebAPI\SpotifyWebAPI(); but this says I need user information/ tokens.

Looking at the code (Session class, SpotifyWebapi class), it does look like you should set this up by doing

$api = new SpotifyWebAPI\SpotifyWebAPI();
$session = new SpotifyWebAPI\Session($clientId, $clientSecret, $redirectUri);
$api->setAccessToken($session->getAccessToken());

When that's set up you should be good to use the getUserPlaylists method like you're doing in your example code.