I have a Rails app in which I want users to be able to sign in / up with Google. I'm using the following gem:

```
#gemfile
gem 'omniauth-google-oauth2'

```

I've almost got it to work (I actually received the access token once, not sure why) - but before getting the access\_token I constantly get the following error:

```
"error"=>"invalid_grant", "error_description"=>"Invalid code."

```

I have checked so that the code is unique for each request and that it isn't nil. The relevant parts of the method where I try to get the `access_token` after I've received the one time authorisation code looks like this:

```
def google_authentication
  respond_to do |format|
    # authorisation code

    code = params[:code]
    unless code.blank?

      client_id = ENV["GOOGLE_CLIENT_ID"]
      client_secret = ENV["GOOGLE_CLIENT_SECRET"]
      redirect_uri = 'postmessage'
      grant_type = 'authorization_code'

      load = {client_id: client_id, client_secret: client_secret,  redirect_uri: redirect_uri, grant_type: grant_type, code: code}
      payload = load.to_json
      url = "https://www.googleapis.com/oauth2/v3/token"
      response = HTTParty.post(url, :query => load)

      json = JSON.parse(response.body)

      unless json.nil?
        unless json[:error].present?
          # TODO: Handle data      
          format.json { render :json => {:message => "Success"} }              
        else
          # ERROR "Invalid code" always happen
        end
      end
    end
  end
end

```

In Google's developer console I have the following credentials:

```
Client ID           [CLient ID]
Email address       [Email]
Client secret       [Secret]
Redirect URIs       http://127.0.0.1:3000/
JavaScript origins  http://127.0.0.1:3000

```

Would be thankful for any ideas or tips. 

**Update for completion**

This is how I set up omniauth-google-oauth2:

```
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"],  ENV["GOOGLE_CLIENT_SECRET"],
    {
      :scope => "email, profile",
      :prompt => "select_account",
      :provider_ignores_state => true
    }
end

```

**Update 2**

As mentioned above I once managed to get the access token once, I managed to reproduce it again. I did it by clicking my sign in button three times.The first time I got:

```
"error"=>"invalid_grant", "error_description"=>"Invalid code."

```

The second click resulted in:

```
"error"=>"invalid_grant", "error_description"=>"Code was already redeemed."

```

And the third time I successfully got the `access_token`. I find it really strange that I sometimes get the `access_token`, but most of the time get:

```
"error"=>"invalid_grant", "error_description"=>"Invalid code."

```

And the success / error "rate" isn't 100% consistent. Sometimes it takes more than three clicks. I find it quite strange that it sometimes works and that I sometimes get different error responses without changing anything in my code. 

Could it be related to time / expiration date of the code? 

**Update 3**

For additional completion. This is how my Javascript (or CoffeeScript) looks like when the user clicks the Google Sign in button: 

```
$(document).ready ->
  $.ajax
    url: 'https://apis.google.com/js/client:plus.js?onload=gpAsyncInit'
    dataType: 'script'
    cache: true

window.gpAsyncInit = ->
  $('.googleplus-login').click (e) ->
    e.preventDefault()
    gapi.auth.authorize {
      immediate: false
      response_type: 'code'
      cookie_policy: 'single_host_origin'
      client_id: '[id]'
      scope: 'email profile'
    }, (response) ->
      if response and !response.error

        jQuery.ajax
          type: 'POST'
          url: '/auth/google_oauth2/callback'
          dataType: 'json'
          data: response
          success: (json) ->
            # response from server
            console.log "JSON: " + json
            return
      else
        # google authentication failed

```