iamstuartwilson / strava

PHP Class for the Strava API (v3)
MIT License
120 stars 26 forks source link

Strava Refresh Token #40

Open Geovanek opened 5 years ago

Geovanek commented 5 years ago

I am unable to implement the token update, can you help me.

Fatal error: Uncaught RuntimeException: Strava access token needs to be refreshed in /

mjaschen commented 5 years ago

Hi,

did you take a look at the example script? Do you get that script working?

Geovanek commented 5 years ago

Yes,

This is exactly the example script.

I set the session values with the token that was generated 2 days ago, and this error appears. The token_refresh option does not appear.

https://racepace.com.br/funcoes/oauth-flow.php

bebablub commented 5 years ago

Hi there!

i'm also having issues with your example. I modifiied it the way:

require_once 'StravaApi.php';

// Replace with the actual URL of this file:
define('CALLBACK_URL', '<callback_url>/oauth-flow.php?action=callback');
// Insert your Strava App ID + Secret:
define('STRAVA_API_ID', '<my_client_id>');
define('STRAVA_API_SECRET', '<my_client_secret>');

After opening:

/oauth-flow.php?action=callback

in my browser i am getting:

Token Exchange Response Data
(after swapping the code from callback against tokens)

stdClass Object
(
    [message] => Bad Request
    [errors] => Array
        (
            [0] => stdClass Object
                (
                    [resource] => RequestToken
                    [field] => code
                    [code] => invalid
                )

        )

)

Do you have any idea on whats going wrong?

Thank you!

@Geovanek: have a look at the Readme.md Don't replace the $_SESSION['strava_access_token'], $_SESSION['strava_refresh_token'], $_SESSION['strava_access_token_expires_at'] with hardcoded values. This won't work anymore. Strava requires a new (in my opinion too complex) auth flow which bases on a callback with some kind of code...

Geovanek commented 5 years ago

Hi there!

i'm also having issues with your example. I modifiied it the way:

require_once 'StravaApi.php';

// Replace with the actual URL of this file:
define('CALLBACK_URL', '<callback_url>/oauth-flow.php?action=callback');
// Insert your Strava App ID + Secret:
define('STRAVA_API_ID', '<my_client_id>');
define('STRAVA_API_SECRET', '<my_client_secret>');

After opening:

/oauth-flow.php?action=callback

in my browser i am getting:

Token Exchange Response Data
(after swapping the code from callback against tokens)

stdClass Object
(
    [message] => Bad Request
    [errors] => Array
        (
            [0] => stdClass Object
                (
                    [resource] => RequestToken
                    [field] => code
                    [code] => invalid
                )

        )

)

Do you have any idea on whats going wrong?

Thank you!

@Geovanek: have a look at the Readme.md Don't replace the $_SESSION['strava_access_token'], $_SESSION['strava_refresh_token'], $_SESSION['strava_access_token_expires_at'] with hardcoded values. This won't work anymore. Strava requires a new (in my opinion too complex) auth flow which bases on a callback with some kind of code...

I went back to the original code at the link above

bebablub commented 5 years ago

Ok perfect when i just call <callback_url>/oauth-flow.php the example seems to work. Thank you! But now i have new problems. So far i used the API in some scripts (not in a web app). Therefore it's not possible for me to start the whole process (the authorization with callback) every time. How long are the authorization/refreshtoken code valid?

Geovanek commented 5 years ago

Ok, perfeito quando eu apenas chamo <callback_url>/oauth-flow.phpo exemplo parece funcionar. Obrigado! Mas agora eu tenho novos problemas. Até agora, usei a API em alguns scripts (não em um aplicativo da web). Portanto, não é possível iniciar todo o processo (a autorização com retorno de chamada) sempre. Por quanto tempo o código de autorização / atualização do token é válido?

Is valid for 6hs.

Geovanek commented 5 years ago

I believe I was able to make my app automated by placing the code as follows.

It returns the user data from the DB, connects to the strava API, if the token has expired, returns a new token and retries the connection. I will monitor the operation today, but it seems to be working.

try{
    $api->setAccessToken($user->strava_token, $user->strava_refresh_token, $user->strava_access_token_expires_at);
} catch (Exception $e) {
    if ($e->getMessage() === 'Strava access token needs to be refreshed') {
        $response = $api->tokenExchangeRefresh();
        $api->setAccessToken($response->access_token, $response->refresh_token, $response->expires_at);
    }
}
bebablub commented 5 years ago

@Geovanek Thank you very much! The code seems to work for me too :)

StravaFan commented 4 years ago

This thread was a lifesaver.

I added the following code to auth.php above the line "// Setup the API instance with authentication tokens, if possible:", and it kickstarted my otherwise frozen script.

I guess we'll see when I wake up in the morning if this is enough to keep things ticking.

// try to get new token -- if refresh is needed
try{
    $api->setAccessToken($_SESSION['strava_access_token'], $_SESSION['strava_refresh_token'], $_SESSION['strava_access_token_expires_at']);
} catch (Exception $e) {
    if ($e->getMessage() === 'Strava access token needs to be refreshed') {

        $response = $api->tokenExchangeRefresh();

        $_SESSION['strava_access_token'] = isset($response->access_token) ? $response->access_token : null;
        $_SESSION['strava_refresh_token'] = isset($response->refresh_token) ? $response->refresh_token : null;
        $_SESSION['strava_access_token_expires_at'] = isset($response->expires_at) ? $response->expires_at : null;

    }
}
phamhphuc commented 1 year ago

I believe I was able to make my app automated by placing the code as follows.

It returns the user data from the DB, connects to the strava API, if the token has expired, returns a new token and retries the connection. I will monitor the operation today, but it seems to be working.

try{
    $api->setAccessToken($user->strava_token, $user->strava_refresh_token, $user->strava_access_token_expires_at);
} catch (Exception $e) {
    if ($e->getMessage() === 'Strava access token needs to be refreshed') {
        $response = $api->tokenExchangeRefresh();
        $api->setAccessToken($response->access_token, $response->refresh_token, $response->expires_at);
    }
}

Work perfectly. Thanks friends. I think the source need to implement auto refresh for easier to use. Or we can extend and implement auto refresh feature