matt-bartlett / php-spotify-api

PHP Spotify Web API 包

0.3.0 2020-02-17 20:46 UTC

This package is auto-updated.

Last update: 2024-09-19 19:33:06 UTC


README

这是一个与框架无关的PHP库,用于与Spotify Web API交互。

安装

使用Composer安装

$ composer require matt-bartlett/php-spotify-api

前往 Spotify 创建一个应用程序。您需要以下信息供以后使用

  • Spotify 客户端ID
  • Spotify 客户端密钥
  • 重定向URL

基本用法

这个库围绕 资源 展开。资源封装了特定的Spotify功能。会话处理已被抽象化,虽然这个库自带会话处理器,但您也可以编写自己的处理器并将其绑定到实现中。我强烈建议使用某种依赖注入容器来配置这个库。我将通过一些示例进行说明。

通用示例

如果您在纯PHP环境中工作,那么 examples/vanilla_php_example.php 应该可以覆盖库的基本用法。

Laravel 示例

这个库附带一个 LaravelSessionHandler。这个类封装了Laravel中内置的会话处理器,允许您使用控制应用程序的相同会话驱动器。由于Laravel自带依赖注入容器,我们不需要提供太多的配置。但是,我们将需要解决具体的实现。我们可以通过服务提供者来完成。

App\Provider 中创建一个新的服务提供者,并粘贴以下内容

<?php

namespace App\Providers;

use Spotify\Http\Request;
use Illuminate\Session\Store;
use Spotify\Auth\Credentials;
use Spotify\Auth\Authenticator;
use Spotify\Contracts\Store\Session;
use Illuminate\Support\ServiceProvider;
use Spotify\Sessions\LaravelSessionHandler;
use Spotify\Contracts\Auth\Authenticator as AuthenticatorInterface;

class SpotifyServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // Bind Credentials.
        $this->app->singleton(Credentials::class, function ($app) {
            return new Credentials(
                getenv('SPOTIFY_CLIENT_ID'),
                getenv('SPOTIFY_CLIENT_SECRET'),
                getenv('SPOTIFY_REDIRECT_URL')
            );
        });

        // Bind Authenticator.
        $this->app->bind(AuthenticatorInterface::class, function ($app) {
            return new Authenticator(
                $app->make(Request::class),
                $app->make(Credentials::class)
            );
        });

        // Bind the Laravel Session handler.
        $this->app->bind(Session::class, function ($app) {
            return new LaravelSessionHandler(
                $app->make(Store::class)
            );
        });
    }
}

接下来,在您的 config/app.php 中,请确保将此服务提供者添加到 providers 数组中。

我们需要将我们的Spotify凭证添加到我们的 .env 文件中。替换值并粘贴。

SPOTIFY_CLIENT_ID=client-id
SPOTIFY_CLIENT_SECRET=client-secret
SPOTIFY_REDIRECT_URL=your-redirect-url

一切配置完成后,让我们通过一些示例来运行。

客户端凭证流

客户端凭证授权流不需要任何用户授权即可生成访问令牌。通常,此访问令牌仅允许执行查找/读取操作,例如查找播放列表及其所有歌曲。

<?php

namespace App\Http\Controllers;

use Spotify\Resources\Playlist;

class ExampleController extends Controller
{
    protected $service;

    public function __construct(Playlist $service)
    {
        $this->service = $service;
    }

    public function show(Request $request)
    {
        $playlist = $this->service->getPlaylist($request->get('playlist-id'));

        return $playlist;
    }
}

授权代码流

例如创建播放列表这样的操作需要用户授权。为了获取访问令牌,我们必须首先要求用户授权并同意我们希望执行的操作。确认后,他们将被重定向到 Spotify\Auth\Credentials 类中设置的 redirect_url,并附带一个我们可以用来交换访问令牌的代码。

为了演示,我将在我们的应用程序中添加2个路由。第一个路由将处理从Spotify的重定向。第二个路由将创建一个播放列表。

Route::get('/spotify/redirect', 'SpotifyController@redirect');
Route::post('/spotify/playlist/create', 'SpotifyController@playlist');
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Spotify\Constants\Scope;
use Spotify\Resources\Playlist;
use Spotify\Exceptions\UserRequiresAuthorizationException;

class SpotifyController extends Controller
{
    protected $service;

    public function __construct(Playlist $service)
    {
        $this->service = $service;
    }

    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return Illuminate\Http\RedirectResponse
     */
    public function redirect(Request $request)
    {
        $code  = $request->get('code');
        $error = $request->get('error');

        if ($error) {
            // Do something when an error is returned.
        }

        // Exchange code for access token.
        $this->service->getManager()->handleCallback($code);

        // Redirect the user back to the `playlist` route.
        $redirect = $request->session()->get('redirect', '/an/alternative/endpoint');

        // Let's clean up after ourselves, remove it from the session.
        $request->session()->forget('redirect');

        return redirect()-to($redirect);
    }

    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function playlist(Request $request)
    {
        try {
            // Get the Playlist name from the request.
            $name = $request->get('playlist-name');

            // Create a Playlist with the given name.
            $playlist $this->service->createPlaylist($name));

            return response()->json($playlist);
        } catch (UserRequiresAuthorizationException $e) {
            // Generate authorization URL. We'll need the `playlist-modify-public` scope to make a playlist.
            $url = $this->service->getManager()->getAuthorizationUrl([Scope::PLAYLIST_MODIFY_PUBLIC], true);

            $currentRoute = url()->full();

            // To make this a bit more seamless, we'll set the intended URL to the session.
            $request->session()->put(['redirect' => $currentRoute]);

            return redirect()->to($url);
        }
    }
}

您可能有一个专门处理重定向的控制器。这不一定与特定的资源相关联。在这种情况下,您可以使用 Manager

<?php

namespace App\Http\Controllers;

use Spotify\Manager;
use Spotify\Constants\Scope;
use Illuminate\Http\Request;
use Spotify\Exceptions\UserRequiresAuthorizationException;

class SpotifyRedirectController extends Controller
{
    protected $manager;

    public function __construct(Manager $manager)
    {
        $this->manager = $manager;
    }

    /**
     * @param \Illuminate\Http\Request $request
     *
     * @return Illuminate\Http\RedirectResponse
     */
    public function redirect(Request $request)
    {
        $code  = $request->get('code');
        $error = $request->get('error');

        if ($error) {
            // Do something when an error is returned.
        }

        // Exchange code for access token.
        $this->manager->handleCallback($code);

        return redirect('route.name');
    }
}