title: Google Plus Single Sign On Server Flow - Google_AuthException Error fetching OAuth2 access token, message: 'invalid_grant'
body: <p><em><strong>UPDATE 27th January 2013</em></strong></p>
  
  <p>I have now resolved this, Please check the accepted answer.</p>
  
  <hr>
  
  <p>I am having trouble to get my refresh token and my access token when using the server side flow between my Android Application and my PHP server.</p>
  
  <p>So I have managed to get my One Time Code by using the below:</p>
  
  <pre><code>AsyncTask&lt;Void, Void, String&gt; task = new AsyncTask&lt;Void, Void, String&gt;() {
      @Override
      protected String doInBackground(Void... params) {
  
          Bundle appActivities = new Bundle();
          appActivities.putString(GoogleAuthUtil.KEY_REQUEST_VISIBLE_ACTIVITIES,
                  "http://schemas.google.com/AddActivity");
          String scopes = "oauth2:server:client_id:" + SERVER_CLIENT_ID + 
                  ":api_scope:" + SCOPE_STRING;
  
          try {
              code = GoogleAuthUtil.getToken(
                      OneTimeCodeActivity.this,         // Context context
                      mPlusClient.getAccountName(),     // String accountName
                      scopes,                           // String scope
                      appActivities                     // Bundle bundle
              );
          } catch (IOException transientEx) {
              // network or server error, the call is expected to succeed if you try again later.
              // Don't attempt to call again immediately - the request is likely to
              // fail, you'll hit quotas or back-off.
              System.out.println(transientEx.printStactTrace());
              return "Error";
          } catch (UserRecoverableAuthException e) {
              // Recover
              code = null;
              System.out.println(e.printStackTrace());
              OneTimeCodeActivity.this.startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
          } catch (GoogleAuthException authEx) {
              // Failure. The call is not expected to ever succeed so it should not be
              // retried.
              System.out.println(authEx.printStackTrace());
              return "Error";
          } catch (Exception e) {
              System.out.println(authEx.printStackTrace());
          }
     }
  </code></pre>
  
  <p>Which will then store the token in the variable "code" and I call up the async task as</p>
  
  <pre><code>task.execute();
  </code></pre>
  
  <p>The code above will always bring up a popup message and throw UserRecoverableAuthException Need Permission that requires the user to grant offline access, which means the above will need to be called twice to retrieve the code and store it in "code"</p>
  
  <p>I am now trying to send this across to my server which is implemented in PHP.</p>
  
  <p>I have used the quick start <a href="https://developers.google.com/+/quickstart/php" rel="nofollow">https://developers.google.com/+/quickstart/php</a> and managed to get that working.</p>
  
  <p>In here, there is a sample signin.php</p>
  
  <p>In here and according to the documentation this already implements a One Time Authorisation Server Side Flow.</p>
  
  <p>So now my problem is sending this One Time Code to the server.</p>
  
  <p>I used the photohunt Android Auth example for this located here. </p>
  
  <p><a href="https://github.com/googleplus/gplus-photohunt-client-android/blob/master/src/com/google/plus/samples/photohunt/auth/AuthUtil.java" rel="nofollow">https://github.com/googleplus/gplus-photohunt-client-android/blob/master/src/com/google/plus/samples/photohunt/auth/AuthUtil.java</a></p>
  
  <p>I used the "authorization" method of the code and called up signin.php/connect through a post method shown below</p>
  
  <pre><code>$app-&gt;post('/connect', function (Request $request) use ($app, $client) {
      $token = $app['session']-&gt;get('token');
  
      if (empty($token)) {
          // Ensure that this is no request forgery going on, and that the user
          // sending us this connect request is the user that was supposed to.
          if ($request-&gt;get('state') != ($app['session']-&gt;get('state'))) {
              return new Response('Invalid state parameter', 401);
          }
  
          // Normally the state would be a one-time use token, however in our
          // simple case, we want a user to be able to connect and disconnect
          // without reloading the page.  Thus, for demonstration, we don't
          // implement this best practice.
          //$app['session']-&gt;set('state', '');
  
          $code = $request-&gt;getContent();
          // Exchange the OAuth 2.0 authorization code for user credentials.
          $client-&gt;authenticate($code);
          $token = json_decode($client-&gt;getAccessToken());
  
          // You can read the Google user ID in the ID token.
          // "sub" represents the ID token subscriber which in our case
          // is the user ID. This sample does not use the user ID.
          $attributes = $client-&gt;verifyIdToken($token-&gt;id_token, CLIENT_ID)
              -&gt;getAttributes();
          $gplus_id = $attributes["payload"]["sub"];
  
          // Store the token in the session for later use.
          $app['session']-&gt;set('token', json_encode($token));
          $response = 'Successfully connected with token: ' . print_r($token, true);
      }
  
      return new Response($response, 200);
  });
  </code></pre>
  
  <p>Now when I send the code using the above implementation, I get an 500 messages that says the below</p>
  
  <p>Google_AuthException Error fetching OAuth2 access token, message: 'invalid_grant'
  in ../vendor/google/google-api-php-client/src/auth/Google_OAuth2.php line 115</p>
  
  <p>at Google_OAuth2->authenticate(array('scope' => '<a href="https://www.googleapis.com/auth/plus.login" rel="nofollow">https://www.googleapis.com/auth/plus.login</a>'), '{ "token":"xxxxxxxx"}') in ../vendor/google/google-api-php-client/src/Google_Client.php line 131</p>
  
  <p>at Google_Client->authenticate('{ "token":"xxxxxxx"}') in ../signin.php line 99</p>
  
  <p>at {closure}(object(Request))</p>
  
  <p>at call_user_func_array(object(Closure), array(object(Request))) in ../vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php line 117</p>
  
  <p>at HttpKernel->handleRaw(object(Request), '1') in ../vendor/symfony/http-kernel/Symfony/Component/HttpKernel/HttpKernel.php line 61</p>
  
  <p>at HttpKernel->handle(object(Request), '1', true) in ../vendor/silex/silex/src/Silex/Application.php line 504</p>
  
  <p>at Application->handle(object(Request)) in ../vendor/silex/silex/src/Silex/Application.php line 481</p>
  
  <p>at Application->run() in ../signin.php line 139</p>
  
  <p>Funny enough I have had to worked once where I did receive a 200, but I cannot recreate it.</p>
  
  <p>So I know I have definitely got the implementation wrong, but I have no clue on how to send it and get my refresh token. I can't find anywhere on the web that explains this. Is someone able to help me please.</p>
  
  <p><strong>UPDATE 16 Jan 2014</strong></p>
  
  <p>Using <a href="https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" rel="nofollow">https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=</a> I can see that the token being produced from getToken is valid and is indeed valid for 1 hour.</p>
  
  <p>I can confirm the json formation is correct by changing the way I am inputting into the Post request and if I don't do it properly I get a total failure.</p>
  
  <p>Now I am going deeper into the php and look at this section Google_OAuth2.php line 115 where it is breaking it is throwing a Google_AuthException. The code is below and this is provided in the quick starter pack</p>
  
  <pre><code>/**
   * @param $service
   * @param string|null $code
   * @throws Google_AuthException
   * @return string
   */
  public function authenticate($service, $code = null) {
    if (!$code &amp;&amp; isset($_GET['code'])) {
      $code = $_GET['code'];
    }
  
    if ($code) {
      // We got here from the redirect from a successful authorization grant, fetch the access token
      $request = Google_Client::$io-&gt;makeRequest(new Google_HttpRequest(self::OAUTH2_TOKEN_URI, 'POST', array(), array(
        'code' =&gt; $code,
        'grant_type' =&gt; 'authorization_code',
        'redirect_uri' =&gt; $this-&gt;redirectUri,
        'client_id' =&gt; $this-&gt;clientId,
        'client_secret' =&gt; $this-&gt;clientSecret
      )));
  
      if ($request-&gt;getResponseHttpCode() == 200) {
        $this-&gt;setAccessToken($request-&gt;getResponseBody());
        $this-&gt;token['created'] = time();
        return $this-&gt;getAccessToken();
      } else {
        $response = $request-&gt;getResponseBody();
        $decodedResponse = json_decode($response, true);
        if ($decodedResponse != null &amp;&amp; $decodedResponse['error']) {
          $response = $decodedResponse['error'];
        }
        throw new Google_AuthException("Error fetching OAuth2 access token, message: '$response'", $request-&gt;getResponseHttpCode());
      }
    }
  
    $authUrl = $this-&gt;createAuthUrl($service['scope']);
    header('Location: ' . $authUrl);
    return true;
  }
  </code></pre>
  
  <p>I edit the code above to make sure the code, the client id and secret were correct and they were. So that is where I am now, I don't think it is scope issues as well as I hard coded it in the client setup and still does not work. Not too sure.</p>
  
  <p><em><strong>UPDATE 23rd January</em></strong></p>
  
  <p>OK, I think it is a time issue. I used <a href="https://developers.google.com/+/photohunt/android" rel="nofollow">https://developers.google.com/+/photohunt/android</a> and base my design on the BaseActivity in the Photohunt using the AuthUtil, and I get invalid grant on my server. How do I move the time back on my server in code. I read somewhere I can do time() - 10 somewhere but not sure where...</p>