Skip to content
Romain Monteil edited this page Jan 2, 2019 · 6 revisions

Start

First, you have to request an OAuth token to be able to use the API

composer require kerox/oauth2-spotify

then run composer install to get this dependency added to your project.

$provider = new Kerox\OAuth2\Client\Provider\Spotify([
    'clientId'     => '{spotify-client-id}',
    'clientSecret' => '{spotify-client-secret}',
    'redirectUri'  => 'https://example.com/callback-url',
]);

if (!isset($_GET['code'])) {
    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl([
        'scope' => [
            Kerox\OAuth2\Client\Provider\Spotify::SCOPE_USER_READ_BIRTHDATE,
            Kerox\OAuth2\Client\Provider\Spotify::SCOPE_USER_READ_EMAIL,
        ]
    ]);
    
    $_SESSION['oauth2state'] = $provider->getState();
    
    header('Location: ' . $authUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {

    unset($_SESSION['oauth2state']);
    echo 'Invalid state.';
    exit;

}

$token = $provider->getAccessToken('authorization_code', [
    'code' => $_GET['code']
]);

$spotify = new \Kerox\Spotify\Spotify($token->getToken(), $client);
$response = $spotify->me()->get();
Clone this wiki locally