PHP code example of calliostro / spotify-web-api-bundle

1. Go to this page and download the library: Download calliostro/spotify-web-api-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

calliostro / spotify-web-api-bundle example snippets


// config/bundles.php

return [
    // ...
    Calliostro\SpotifyWebApiBundle\CalliostroSpotifyWebApiBundle::class => ['all' => true],
];

// src/Controller/SomeController.php

use SpotifyWebAPI\SpotifyWebAPI;
// ...

class SomeController
{
    public function index(SpotifyWebAPI $api)
    {
        $search = $api->search('Thriller', 'album');

        var_dump($search);

        // ...
    }
}

// src/Controller/SpotifyController.php

namespace App\Controller;

use SpotifyWebAPI\Session;
use SpotifyWebAPI\SpotifyWebAPI;
use SpotifyWebAPI\SpotifyWebAPIAuthException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class SpotifyController extends AbstractController
{
    public function __construct(
        private SpotifyWebAPI $api,
        private Session $session
    ) {}

    #[Route('/', name: 'home')]
    public function index(): Response
    {
        return new Response('
            <h1>Spotify Web API Demo</h1>
            <p>Welcome to the Spotify Web API Bundle demonstration!</p>
            <p><a href="/authorize">Click here to authorize with Spotify</a></p>
        ', 200, ['Content-Type' => 'text/html']);
    }

    #[Route('/callback')]
    public function callback(Request $request): Response
    {
        try {
            $this->session->requestAccessToken($request->query->getString('code'));
        } catch (SpotifyWebAPIAuthException) {
            return $this->redirectToRoute('authorize');
        }

        $this->api->setAccessToken($this->session->getAccessToken());
        $me = $this->api->me();

        return new Response('
            <h1>Spotify Authorization Successful!</h1>
            <p>Welcome, ' . htmlspecialchars($me->display_name ?? 'Spotify User') . '!</p>
            <pre>' . htmlspecialchars(var_export($me, true)) . '</pre>
            <p><a href="/">Back to Home</a></p>
        ', 200, ['Content-Type' => 'text/html']);
    }

    #[Route('/authorize', name: 'authorize')]
    public function authorize(): Response
    {
        $options = [
            'scope' => [
                'user-read-email',
            ],
        ];

        return $this->redirect($this->session->getAuthorizeUrl($options));
    }
}