jwilsson / spotify-web-api-php

A PHP wrapper for Spotify's Web API.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How can I get the token without another ?code= forwarding?

salimcansatici opened this issue · comments

Hello there,

Localhost index.php gone to me http://localhost/?code=AQBhex-8CF0Xv15HTgob5WesCOmnBTkGQ6QHVMgCwpgx5oXwwHgVMAMjxrCLS0UkQhLzPvd53syHgaf1bQlVrKo-RDNAv10s6pTQNZywdahkDXARJxR_jCHAnQXZiWUKHcfTsCB-nyQRu5PDx_zc7jQouX0rL63LER06XHIdWPrTKQse0jUFBcWh51-4jMadu6Uholi3lxPy3_TcDXObDzs1vwWjx9WiB_cmzmyb as a URL redirect.

### How can I get the token without another forwarding?
I want to be shown what I listened to when visiting the site.
Thanks to you, I can get the information about which music I'm listening to. But when I visit the site, I want other users to see this from my own token.

Where can I store this token? I have read the document but could not understand it. Could you please give me some guidance?

My code is;

<?php 
ob_start();

$session = new SpotifyWebAPI\Session(
    'Hidden',
    'Hidden',
    'http://localhost:80'
);

$api = new SpotifyWebAPI\SpotifyWebAPI(['auto_refresh' => true, 'auto_retry' => true]);
if (isset($_GET['code'])) {
    $session->requestAccessToken($_GET['code']);
    $api->setAccessToken($session->getAccessToken());
    // $refresh_token = $session->getRefreshToken();
    //print_r($api->me());
} else {
    $options = [
        'scope' => [
            'user-read-currently-playing',
            'user-read-playback-state'
        ],
    ];

    header('Location: ' . $session->getAuthorizeUrl($options)); //The url here redirects. :(
    die();
}
$my_data = $api->getMyCurrentTrack();
$image = $my_data->item->album->images[0]->url;
echo '<img class="absolute h-full w-full object-cover" src="'. $image.'"/>';
?>

Thanks,

Hi!
After requesting the tokens, you'll need to save the access and refresh tokens somewhere persistent. This could be in a database, a file on disk, or somewhere else as long as it's secret and safely stored so no one else can access it. It's really up to you to decide what's the best approach to saving the tokens.

Then, whenever someone visits your site and you want to display the image you need to first retrieve the tokens and tell the API-wrapper about them. The Authorization Code Flow guide should provide some guidance on this and how to split things into multiple files.