jwilsson / spotify-web-api-php

A PHP wrapper for Spotify's Web API.
MIT License
868 stars 156 forks source link

Refreshing page causes Invalid authorization code #243

Closed dgtyPedro closed 2 years ago

dgtyPedro commented 2 years ago

I use the auth example given here to do my homepage but everytimes I refresh the page the token code gets invalidated, this happens because on refresh the $_GET['code'] stays the same as previous.

$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {

    $session->requestAccessToken($_GET['code']);
    $refreshToken = $session->getRefreshToken();
    $api->setAccessToken($session->getAccessToken());
    include ('html/home.php');

} else {

    header('Location: ' . $session->getAuthorizeUrl($options));
    die();
}

I wonder if I can do something with the Refresh Token but I don't want to mess with the other page that uses this token (this one does not have the token in the URL).

I already tried to do something like this:

if (isset($_GET['code']) && $api->setAccessToken($session->getAccessToken())) {

    $session->requestAccessToken($_GET['code']);
    $refreshToken = $session->getRefreshToken(); 
    include ('html/home.php');

} else {

    header('Location: ' . $session->getAuthorizeUrl($options));
    die();
}

but it give me too many redirects, causing the page to crash.

dgtyPedro commented 2 years ago

I fixed inserting a try catch method. The code ended like this:

$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
    try{
        $session->requestAccessToken($_GET['code']);
        $refreshToken = $session->getRefreshToken();
        $api->setAccessToken($session->getAccessToken());
        include ('html/home.php');
    }catch (exception $e){
        header('Location: ' . $session->getAuthorizeUrl($options));
        die();
    }

} else {
    header('Location: ' . $session->getAuthorizeUrl($options));
    die();
}
dgtyPedro commented 2 years ago

New fix.

This fix that I posted would cause too many redirects on some devices, because of this situations now I use:

$api = new SpotifyWebAPI\SpotifyWebAPI();
if (isset($_GET['code'])) {
    try{
        $session->requestAccessToken($_GET['code']);
        $refreshToken = $session->getRefreshToken();
        $api->setAccessToken($session->getAccessToken());
        include ('html/home.php');
    }catch (exception $e){
        header('Location: ' . $YOUR_BASE_URL_HERE);
        die();
    }

} else {
    header('Location: ' . $session->getAuthorizeUrl($options));
    die();
}