rhysnhall / etsy-php-sdk

PHP SDK for Etsy API v3.
MIT License
47 stars 36 forks source link

Added autoRefreshSettings config option #23

Closed MikeWillis closed 3 months ago

MikeWillis commented 1 year ago

I wanted my app to automatically refresh the token if necessary, instead of triggering a fatal error. So I added a config option autoRefreshSettings where you can pass an array of settings for refreshing the token. If set, a 401/invalid_token response will trigger a token refresh followed by a recursive call, so the refresh is seamless.

If the refresh is successful, the new access token and refresh tokens are stored for use on future calls. I also pass in an onSuccess handler, which you can use to save the new tokens somewhere in your DB.

I suppose you could just start every script with a call to the refresh token.. But I wanted to only run the refresh when necessary.

Example usage:

$etsy = new \Etsy\Etsy(
    $api_key,
    $access_token,
    [
        "autoRefreshSettings"=>[
            "refreshToken"=>$refreshToken, // presumably you'll have saved this in your DB somewhere
            "onSuccess"=>function($response) {
                // you'll probably want to save these in your DB
                $accessToken = $response["access_token"];
                $refreshToken = $response["refresh_token"];
            },
            "onFail"=>function($response) {
                echo "booo";
            }
        ]
    ]
);
rhysnhall commented 1 year ago

Hey Mike, Thanks for the PR. I will review this as soon as I get a chance to do so.

rhysnhall commented 3 months ago

Apologies on the radio silence. This repo is now being maintained again and a new major version has been released that impacts this PR. I think this PR is a good idea - my only concern is how to pass the refreshed API key back out to be stored? If you want to revise this for the updated version I will be happy to merge.