PHPackages                             dnklbgn/oauth2-spotify - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. dnklbgn/oauth2-spotify

ActiveLibrary[Authentication &amp; Authorization](/categories/authentication)

dnklbgn/oauth2-spotify
======================

Spotify OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1.0.0(2y ago)010MITPHPPHP &gt;=8.3

Since Jan 4Pushed 2y ago1 watchersCompare

[ Source](https://github.com/dnklbgn/oauth2-spotify)[ Packagist](https://packagist.org/packages/dnklbgn/oauth2-spotify)[ RSS](/packages/dnklbgn-oauth2-spotify/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

Spotify Provider for OAuth 2.0 Client
=====================================

[](#spotify-provider-for-oauth-20-client)

[![Latest Stable Version](https://camo.githubusercontent.com/4b815ba6b04adb410f0bcb93d1704d0e8aa395bf4d0c3bf2187c38c8de96e1c4/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f646e6b6c62676e2f6f61757468322d73706f74696679)](https://github.com/dnklbgn/oauth2-spotify/releases)[![License](https://camo.githubusercontent.com/844cbdcac8670dd9e247d7fbb3db3691a2f396a3110f2c9af75faeb514c3e8fb/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f646e6b6c62676e2f6f61757468322d73706f74696679)](LICENSE)[![Build Status](https://github.com/dnklbgn/oauth2-spotify/actions/workflows/ci.yml/badge.svg)](https://github.com/dnklbgn/oauth2-spotify/actions/workflows/ci.yml)[![Code Coverage](https://camo.githubusercontent.com/da8269a0a6962110fd2c1c98a8a1625eda6ff17bbf5d11093dae7cf6e7089808/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f67682f646e6b6c62676e2f6f61757468322d73706f74696679)](https://app.codecov.io/gh/dnklbgn/oauth2-spotify)[![Downloads](https://camo.githubusercontent.com/30e9604ac0d9d8fc0ab2132da9f8bf39323ee4df3af06d06fed873f845f7398f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f646e6b6c62676e2f6f61757468322d73706f74696679)](https://packagist.org/packages/dnklbgn/oauth2-spotify)

This package provides Spotify OAuth 2.0 support for the PHP League's [OAuth 2.0 Client](https://github.com/thephpleague/oauth2-client).

Requirements
------------

[](#requirements)

The following versions of PHP are supported:

- PHP 8.3

Please follow the [Spotify instructions](https://developer.spotify.com/documentation/web-api/concepts/apps) to create the app and obtain the required credentials.

Installation
------------

[](#installation)

You can install this package using Composer:

```
composer require dnklbgn/oauth2-spotify

```

Or you can add the following to your `composer.json` file:

```
{
    "require": {
        "dnklbgn/oauth2-spotify": "^1.0"
    }
}
```

Usage
-----

[](#usage)

### Authorization Code Flow

[](#authorization-code-flow)

```
$provider = new \Dnklbgn\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();
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authUrl);
    exit;
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
    // State is invalid, possible CSRF attack in progress
    unset($_SESSION['oauth2state']);
    exit('Invalid state');
} else {
    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken('authorization_code', [
        'code' => $_GET['code'],
    ]);

    try {
        // Optional: Now you have a token you can look up a users profile data
        // We got an access token, let's now get the user's details
        /** @var \Dnklbgn\OAuth2\Client\Provider\SpotifyResourceOwner $user */
        $resourceOwnerDetails = $provider->getResourceOwner($token);

        // Use these details to create a new profile
        printf('Hello %s!', $resourceOwnerDetails->getDisplayName());
    } catch (\Exception $e) {
        // Failed to get user details
        exit('Something went wrong: ' . $e->getMessage());
    }

    // Use this to interact with an API on the users behalf
    var_dump($token->getToken());
    # string(217) "CAADAppfn3msBAI7tZBLWg..."

    // Use this to get a new access token if the old one expires
    var_dump($token->getRefreshToken());
    # string(217) "CAADAppfn3msBAI7tZBLWg..."

    // Unix timestamp at which the access token expires
    var_dump($token->getExpires());
    # int(1436825866)
}
```

### Managing Scopes

[](#managing-scopes)

When creating your Spotify authorization URL, you can specify the state and scopes your application may authorize.

```
$options = [
    'scope' => [
        \Dnklbgn\OAuth2\Client\Provider\SpotifyScope::USER_READ_PRIVATE->value,
        \Dnklbgn\OAuth2\Client\Provider\SpotifyScope::USER_READ_EMAIL->value,
    ],
];

$authUrl = $provider->getAuthorizationUrl($options);
```

If neither are defined, the provider will utilize internal defaults. At the time of authoring this documentation, the [following scopes are available](https://developer.spotify.com/documentation/web-api/concepts/scopes).

- **Images**
    - ugc-image-upload (`SpotifyScope::UGS_IMAGE_UPLOAD`)
- **Spotify Connect**
    - user-read-playback-state (`SpotifyScope::USER_READ_PLAYBACK_STATE`)
    - user-modify-playback-state (`SpotifyScope::USER_MODIFY_PLAYBACK_STATE`)
    - user-read-currently-playing (`SpotifyScope::USER_READ_CURRENTLY_PLAYING`)
- **Playback**
    - app-remote-control (`SpotifyScope::APP_REMOTE_CONTROL`)
    - streaming (`SpotifyScope::STREAMING`)
- **Playlists**
    - playlist-read-private (`SpotifyScope::PLAYLIST_READ_PRIVATE`)
    - playlist-read-collaborative (`SpotifyScope::PLAYLIST_READ_COLLABORATIVE`)
    - playlist-modify-private (`SpotifyScope::PLAYLIST_MODIFY_PRIVATE`)
    - playlist-modify-public (`SpotifyScope::PLAYLIST_MODIFY_PUBLIC`)
- **Follow**
    - user-follow-modify (`SpotifyScope::USER_FOLLOW_MODIFY`)
    - user-follow-read (`SpotifyScope::USER_FOLLOW_READ`)
- **Listening History**
    - user-read-playback-position (`SpotifyScope::USER_READ_PLAYBACK_POSITION`)
    - user-top-read (`SpotifyScope::USER_TOP_READ`)
    - user-read-recently-played (`SpotifyScope::USER_READ_RECENTLY_PLAYED`)
- **Library**
    - user-library-modify (`SpotifyScope::USER_LIBRARY_MODIFY`)
    - user-library-read (`SpotifyScope::USER_LIBRARY_READ`)
- **Users**
    - user-read-email (`SpotifyScope::USER_READ_EMAIL`)
    - user-read-private (`SpotifyScope::USER_READ_PRIVATE`)
- **Open Access**
    - user-soa-link (`SpotifyScope::USER_SOA_LINK`)
    - user-soa-unlink (`SpotifyScope::USER_SOA_UNLINK`)
    - user-manage-entitlements (`SpotifyScope::USER_MANAGE_ENTITLEMENTS`)
    - user-manage-partner (`SpotifyScope::USER_MANAGE_PARTNER`)
    - user-create-partner (`SpotifyScope::USER_CREATE_PARTNER`)

### Retrieving Spotify user information

[](#retrieving-spotify-user-information)

The `getResourceOwner()` method will return an instance of `\Dnklbgn\OAuth2\Client\Provider\SpotifyResourceOwner`, which has some helpful getter methods to access basic authorized user details.

```
$resourceOwnerDetails = $provider->getResourceOwner($token);

// The country of the user, as set in the user's account profile
$country = $resourceOwnerDetails->getCountry();
var_dump($country);
// string(2) "ID"

// The name displayed on the user's profile
$displayName = $resourceOwnerDetails->getDisplayName();
var_dump($displayName);
// string(6) "dnkbgn"

// The user's email address, as entered by the user when creating their account
$email = $resourceOwnerDetails->getEmail();
var_dump($email);
// string(19) "dnklbgn@example.com"

// The user's explicit content settings
$explicitContent = $resourceOwnerDetails->getExplicitContent();
var_dump($explicitContent);
// array(2) {
//   ["filter_enabled"]=>
//   bool(false)
//   ["filter_locked"]=>
//   bool(false)
//}

// Known external URLs for this user
$externalUrls = $resourceOwnerDetails->getExternalUrls();
var_dump($externalUrls);
// array(1) {
//   ["spotify"]=>
//   string(44) "https://open.spotify.com/user/abcd0123456789"
// }

// Information about the followers of the user
$followers = $resourceOwnerDetails->getFollowers();
var_dump($followers);
// array(2) {
//   ["href"]=>
//   NULL
//   ["total"]=>
//   int(3)
// }

// A link to the Web API endpoint for this user
$href = $resourceOwnerDetails->getHref();
var_dump($href);
// string(47) "https://api.spotify.com/v1/users/abcd0123456789"

// The Spotify user ID for the user
$id = $resourceOwnerDetails->getId();
var_dump($id);
// string(14) "abcd0123456789"

// The user's profile image
$images = $resourceOwnerDetails->getImages();
var_dump($images);
// array(1) {
//   [0]=>
//   array(3) {
//     ["url"]=>
//     string(64) "https://i.scdn.co/image/ab67616d00001e02ff9ca10b55ce82ae553c8228"
//     ["height"]=>
//     int(300)
//     ["width"]=>
//     int(300)
//   }
// }

// The user's Spotify subscription level: "premium", "free", etc.
$product = $resourceOwnerDetails->getProduct();
var_dump($product);
// string(7) "premium"

// The object type: "user"
$type = $resourceOwnerDetails->getType();
var_dump($type);
// string(4) "user"

// The Spotify URI for the user
$uri = $resourceOwnerDetails->getUri();
var_dump($uri);
// string(27) "spotify:user:abcd0123456789"
```

### Refreshing a Token

[](#refreshing-a-token)

If your access token expires you can refresh them with the refresh token.

```
if ($accessToken->hasExpired()) {
    $refreshedAccessToken = $provider->getAccessToken(
        new \League\OAuth2\Client\Grant\RefreshToken(),
        ['refresh_token' => $accessToken->getRefreshToken()],
    );
}
```

Contributing
------------

[](#contributing)

Contributions are welcome and will be fully credited. Please see [CONTRIBUTING](https://github.com/dnklbgn/oauth2-spotify/blob/master/CONTRIBUTING.md) for details.

Credits
-------

[](#credits)

- [Nikolay Kuzmin](https://github.com/dnklbgn)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/dnklbgn/oauth2-spotify/blob/master/LICENSE) for more information.

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity5

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

856d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6e5ba0eb7e366e101a3fe6d834c3f1da8a84f29e7142b42daf923c7a02c9b7d6?d=identicon)[dnklbgn](/maintainers/dnklbgn)

---

Tags

oauth2oauth2-providerphpspotifyphpclientoauthoauth2authorizationauthorisationspotify

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/dnklbgn-oauth2-spotify/health.svg)

```
[![Health](https://phpackages.com/badges/dnklbgn-oauth2-spotify/health.svg)](https://phpackages.com/packages/dnklbgn-oauth2-spotify)
```

###  Alternatives

[stevenmaguire/oauth2-keycloak

Keycloak OAuth 2.0 Client Provider for The PHP League OAuth2-Client

2275.9M27](/packages/stevenmaguire-oauth2-keycloak)[patrickbussmann/oauth2-apple

Sign in with Apple OAuth 2.0 Client Provider for The PHP League OAuth2-Client

1132.5M6](/packages/patrickbussmann-oauth2-apple)[league/oauth2-instagram

Instagram OAuth 2.0 Client Provider for The PHP League OAuth2-Client

761.0M31](/packages/league-oauth2-instagram)[stevenmaguire/oauth2-salesforce

Salesforce OAuth 2.0 Client Provider for The PHP League OAuth2-Client

311.6M3](/packages/stevenmaguire-oauth2-salesforce)[mollie/oauth2-mollie-php

Mollie Provider for OAuth 2.0 Client

251.7M1](/packages/mollie-oauth2-mollie-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
