title: Google Oauth2: Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'
body: <p>I have the following code running on my localhost to try and authenticate with Google Oauth2. After authenticating, it appears to work for a while. Then after a certain amount of time I'm getting this classic error:</p>
  
  <pre><code>Error refreshing the OAuth2 token, message: '{
  "error" : "invalid_grant"
  }'
  </code></pre>
  
  <p>I've looked at the previous times this issue was posted to StackOverflow, but the suggested solutions didn't seem to work for me. </p>
  
  <p>I believe the access token is updated correctly (see code below). I also believe the server clock is synchronized correctly. What am I doing wrong?</p>
  
  <hr>
  
  <pre><code>    //$token retrieved from database
      $token = {"access_token":"xxx.xxx_xxxx-xxx","token_type":"Bearer","expires_in":3600,"refresh_token":"1\/xXxXxxxxxXXXxx","created":145490000}
  
      $google = new Google_Client();
      $google-&gt;setAccessType('offline');
      $google-&gt;setClientId($client_id);
      $google-&gt;setClientSecret($client_secret);
      $google-&gt;setRedirectUri($client_redirect_uri);
      $google-&gt;setAccessToken($token);
      if($google-&gt;isAccessTokenExpired()) {
        $google-&gt;refreshToken($token);
      }
      $token = $google-&gt;getAccessToken();
      $google-&gt;setAccessToken($token);
  
      //Some Database code to save the new $token
      ...
  
      $result = new \Google_Service_YouTube($google);
  </code></pre>