kerox / oauth2-spotify
PHP League OAuth2-Client 的 Spotify OAuth 2.0 客户端提供者
2.0.0
2022-11-04 08:30 UTC
Requires
- php: >=8.1
- league/oauth2-client: ^2.6
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpunit/phpunit: ^9.5
README
OAuth 2.0 客户端 Spotify 提供者
此包为 PHP League 的 OAuth 2.0 客户端 提供Spotify OAuth 2.0 支持。
安装
您可以使用 Composer 安装此包
composer require kerox/oauth2-spotify
然后您需要
- 运行
composer install
以将这些依赖项添加到您的 vendor 目录中 - 使用以下行将自动加载器添加到您的应用程序中:
require('vendor/autoload.php');
使用方法
使用方法与 The League 的 OAuth 客户端相同,使用 \Kerox\OAuth2\Client\Provider\Spotify
作为提供者。
授权码流程
$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\SpotifyScope::USER_READ_EMAIL->value, ] ]); $_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; } // Try to get an access token (using the authorization code grant) $token = $provider->getAccessToken('authorization_code', [ 'code' => $_GET['code'] ]); // Optional: Now you have a token you can look up a users profile data try { // We got an access token, let's now get the user's details /** @var \Kerox\OAuth2\Client\Provider\SpotifyResourceOwner $user */ $user = $provider->getResourceOwner($token); // Use these details to create a new profile printf('Hello %s!', $user->getDisplayName()); echo '<pre>'; var_dump($user); echo '</pre>'; } catch (Exception $e) { // Failed to get user details exit('Damned...'); } echo '<pre>'; // Use this to interact with an API on the users behalf var_dump($token->getRefreshToken()); # string(217) "CAADAppfn3msBAI7tZBLWg... // The time (in epoch time) when an access token will expire var_dump($token->getExpires()); # int(1436825866) echo '</pre>';
授权范围
所有范围均可在 官方文档 中找到,通过 \Kerox\OAuth2\Client\Provider\SpotifyScope
枚举获取。
- 图像
- UGC_IMAGE_UPLOAD
- Spotify Connect
- USER_READ_PLAYBACK_STATE
- USER_MODIFY_PLAYBACK_STATE
- USER_READ_CURRENTLY_PLAYING
- 播放
- APP_REMOTE_CONTROL
- STREAMING
- 播放列表
- PLAYLIST_READ_PRIVATE
- PLAYLIST_READ_COLLABORATIVE
- PLAYLIST_MODIFY_PRIVATE
- PLAYLIST_MODIFY_PUBLIC
- 关注
- USER_FOLLOW_MODIFY
- USER_FOLLOW_READ
- 收听历史
- USER_READ_PLAYBACK_POSITION
- USER_TOP_READ
- USER_READ_RECENTLY_PLAYED
- 音乐库
- USER_LIBRARY_MODIFY
- USER_LIBRARY_READ
- 用户
- USER_READ_PRIVATE
- USER_READ_EMAIL
贡献
请参阅 CONTRIBUTING 以获取详细信息。
鸣谢
许可
MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件。