module TDAmeritrade::Authentication

Attributes

access_token[R]
access_token_expires_at[R]
authorization_code[R]
client_id[R]
redirect_uri[R]
refresh_token[R]
refresh_token_expires_at[R]

Public Instance Methods

get_access_tokens(authorization_grant_code) click to toggle source

This is the OAuth code retrieved from your browser window, first step in OAuth needed to retrieve the tokens

# File lib/tdameritrade/authentication.rb, line 13
def get_access_tokens(authorization_grant_code)
  # headers = { 'Content-Type': 'application/x-www-form-urlencoded' } # turns out didn't need this
  params = {
    'grant_type': 'authorization_code',
    'access_type': 'offline',
    'code': authorization_grant_code,
    'client_id': client_id,
    'redirect_uri': redirect_uri
  }
  response = HTTParty.post(
    'https://api.tdameritrade.com/v1/oauth2/token',
    body: params
  )

  unless response_success?(response)
    raise TDAmeritrade::Error::TDAmeritradeError.new(
      "Unable to retrieve access tokens from API - #{response.code} - #{response.body}"
    )
  end

  update_tokens(parse_json_response(response))
end
get_new_access_token() click to toggle source
# File lib/tdameritrade/authentication.rb, line 36
def get_new_access_token
  params = {
    grant_type: 'refresh_token',
    refresh_token: refresh_token,
    access_type: 'offline',
    client_id: client_id,
    redirect_uri: redirect_uri
  }

  response = HTTParty.post(
    'https://api.tdameritrade.com/v1/oauth2/token',
    body: params
  )

  update_tokens(parse_json_response(response))
end
Also aliased as: refresh_access_token
refresh_access_token()
update_tokens(args={}) click to toggle source
# File lib/tdameritrade/authentication.rb, line 54
def update_tokens(args={})
  gem_error(args[:error]) if args.has_key?(:error)

  @access_token = args[:access_token]
  @refresh_token = args[:refresh_token]
  @access_token_expires_at = Time.now + (args[:expires_in] || 0)
  @refresh_token_expires_at = Time.now + (args[:refresh_token_expires_in] || 0)

  args
end