langleyfoxall / xero-laravel

💸 Access the Xero accounting system using an Eloquent-like syntax
https://packagist.org/packages/langleyfoxall/xero-laravel
GNU Lesser General Public License v3.0
85 stars 40 forks source link

Is there a bug in the demo README code? #46

Open cam8001 opened 3 years ago

cam8001 commented 3 years ago

There's some example code in the readme (very helpful). When you initially save a token as a result of the callback, there's this:

public function handleCallbackFromXero(Request $request) {
        // Lots of stuff omitted
        $accessToken = $this->getOAuth2()->getAccessTokenFromXeroRequest($request);
        $user->xero_access_token = json_encode($accessToken);
}

And then later on, when you save the refresh token:


    public function refreshAccessTokenIfNecessary()
    {
        // Step 5 - Before using the access token, check if it has expired and refresh it if necessary.
        $user = auth()->user();
        $accessToken = new AccessToken(json_decode($user->xero_access_token));

        if ($accessToken->hasExpired()) {
            $accessToken = $this->getOAuth2()->refreshAccessToken($accessToken);
            // Should this line use a json_encode() ?
            $user->xero_access_token = $accessToken;
            $user->save();
        }
    }

In the refreshAccessTokenIfNecessary method, should the access token be saved JSON encoded, or as a raw string like that? It is JSON encode when it is first saved.

seanmccabe commented 3 years ago

That is up to the user, some people prefer to save things as json, others as seperate strings. Personally I save it as a json string, and then decode it out and use a getter to get the token into a string.

From memory though, I don't think you can use this code straight off the bat. Its not really a bug though, just a guide into using this and a little fill the gaps depending on your setup and use.

cam8001 commented 3 years ago

I confused myself by using the code as-is but then realising I was sending JSON strings to Xero instead of the actual auth token. Would you be cool if I did a small PR to the readme demo code to describe the data formats?

chrisloftus commented 3 years ago

@seanmccabe How is this right when refreshAccessToken doesn't return the token expiry time? So then the hasExpired method won't know when the new token has expired?

Whereas getAccessTokenFromXeroRequest returns the token and expiry..