helpscout / helpscout-api-php

PHP Wrapper for the Help Scout API
MIT License
99 stars 62 forks source link

Clarify how to use refresh token to get updated access token #128

Closed leewillis77 closed 4 years ago

leewillis77 commented 5 years ago

The current docs explain how you can use a refresh token to make an API request, but not how to use one to retrieve updated access tokens.

After a bit of experimentation I've landed on the following code, but not sure if that's ideal?

$client->useRefreshToken(
    $appId,
    $appSecret,
    $refreshToken
);
// Refreshes the tokens but doesn't return them.
$client->getAuthenticator()->fetchAccessAndRefreshToken();
// Fetch the updated tokens.
$credentials = $client->getAuthenticator()->getTokens();
// Save access_token and updated refresh token here for future client usage
bkuhl commented 5 years ago

Yep, that's correct. Though having to call getAuthenticator() twice there seems a bit silly, so the attached PR now has fetchAccessAndRefreshToken() returning the authenticator.

leewillis77 commented 5 years ago

Perfect - thanks. 👍

nextend commented 5 years ago

@bkuhl Is there any exception thrown when the access token expired and needs to refresh? How can we identify if the token expired?

bkuhl commented 5 years ago

Here's a snippet from https://developer.helpscout.com/mailbox-api/overview/authentication/#response-2

This token is valid for 2 hours and you should create a new one only after the existing token expires. Expiration will be indicated by the API responding with HTTP 401.

In this case you're looking for a GuzzleHttp\Exception\ClientException though it would be easier to see a specific exception for this case so I've added that to our v3 milestone - https://github.com/helpscout/helpscout-api-php/issues/153.

nextend commented 5 years ago

@bkuhl: thanks! I just checked and it works without refreshing the access token, it is strange... The access token was requested 2 days ago and it is still working fine.

I use only the following endpoint:

    $client = \HelpScout\Api\ApiClientFactory::createClient();
    $client = $client->useClientCredentials(HS_APP_ID, HS_APP_SECRET);
    $client->setAccessToken($accessToken['access_token']);

    return $client->threads()
                  ->list($id);