Sample code for 30+ languages & platforms
Lua

ETrade Renew Access Token

See more ETrade Examples

Renews an ETrade OAuth access token.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- This requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.

local http = chilkat.Http.new()

http.oauth1 = true
http.oauth_verifier = ""
http.oauth_consumer_key = "ETRADE_CONSUMER_KEY"
http.oauth_consumer_secret = "ETRADE_CONSUMER_SECRET"

-- Load the access token previously obtained via the OAuth1 Authorization
local jsonToken = chilkat.JsonObject.new()
local success = jsonToken:load_file("qa_data/tokens/etrade.json")
if not success then
    print("Failed to load OAuth1 token")
    return
end

http.oauth_token = jsonToken:string_of("oauth_token")
http.oauth_token_secret = jsonToken:string_of("oauth_token_secret")

local resp = chilkat.HttpResponse.new()
success = http:http_no_body("GET", "https://api.etrade.com/oauth/renew_access_token", resp)
if not success then
    print(http.last_error_text)
    return
end

-- Make sure a successful response was received.
if resp.status_code ~= 200 then
    print(resp.status_line)
    print(resp.header)
    print(resp.body_str)
    return
end

-- If successful, the resp.BodyStr contains something like this:
-- oauth_token=%3TiQRgQCRGPo7Xdk6G8QDSEzX0Jsy6sKNcULcDavAGgU%3D&oauth_token_secret=%7RrC9scEpzcwSEMy4vE7nodSzPLqfRINnTNY4voczyFM%3D
print(resp.body_str)

local sbRespBody = chilkat.StringBuilder.new()
resp:get_body_sb(sbRespBody)
if sbRespBody:contents_equal("Access Token has been renewed", false) then
    -- The documentation at https://apisb.etrade.com/docs/api/authorization/renew_access_token.html
    -- indicates that the response should be as described above.  However, the response received when
    -- trying to refresh a non-expired token was "Access Token has been renewed"
    print("Keeping the same access token, but it's renewed...")
    return
end

local hashTab = chilkat.Hashtable.new()
hashTab:add_query_params(resp.body_str)

local accessToken = hashTab:lookup_str("oauth_token")
local accessTokenSecret = hashTab:lookup_str("oauth_token_secret")

-- The access token + secret is what should be saved and used for
-- subsequent REST API calls.
print("Access Token = " .. accessToken)
print("Access Token Secret = " .. accessTokenSecret)

-- Save this access token for future calls.
-- Just in case we need user_id and screen_name, save those also..
local json = chilkat.JsonObject.new()
json:append_string("oauth_token", accessToken)
json:append_string("oauth_token_secret", accessTokenSecret)

local fac = chilkat.FileAccess.new()
fac:write_entire_text_file("qa_data/tokens/etrade.json", json:emit(), "utf-8", false)

print("Success.")