Sample code for 30+ languages & platforms
Rust

ETrade Renew Access Token

See more ETrade Examples

Renews an ETrade OAuth access token.

Chilkat Rust Downloads

Rust

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

let http = chilkat::Http::new();

http.set_o_auth1(true);
http.set_o_auth_verifier("");
http.set_o_auth_consumer_key("ETRADE_CONSUMER_KEY");
http.set_o_auth_consumer_secret("ETRADE_CONSUMER_SECRET");

// Load the access token previously obtained via the OAuth1 Authorization
let json_token = chilkat::JsonObject::new();
if json_token.load_file("qa_data/tokens/etrade.json").is_err() {
    println!("Failed to load OAuth1 token");
    return;
}

http.set_o_auth_token(&json_token.string_of("oauth_token").unwrap_or_default());
http.set_o_auth_token_secret(&json_token.string_of("oauth_token_secret").unwrap_or_default());

let resp = chilkat::HttpResponse::new();
if http.http_no_body("GET", "https://api.etrade.com/oauth/renew_access_token", &resp).is_err() {
    println!("{}", http.last_error_text());
    return;
}

// Make sure a successful response was received.
if resp.status_code() != 200 {
    println!("{}", resp.status_line());
    println!("{}", resp.header());
    println!("{}", resp.body_str());
    return;
}

// If successful, the resp.BodyStr contains something like this:
// oauth_token=%3TiQRgQCRGPo7Xdk6G8QDSEzX0Jsy6sKNcULcDavAGgU%3D&oauth_token_secret=%7RrC9scEpzcwSEMy4vE7nodSzPLqfRINnTNY4voczyFM%3D
println!("{}", resp.body_str());

let sb_resp_body = chilkat::StringBuilder::new();
let _ = resp.get_body_sb(&sb_resp_body);
if sb_resp_body.contents_equal("Access Token has been renewed", false) {
    // 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"
    println!("Keeping the same access token, but it's renewed...");
    return;
}

let hash_tab = chilkat::Hashtable::new();
let _ = hash_tab.add_query_params(&resp.body_str());

let access_token = hash_tab.lookup_str("oauth_token").unwrap_or_default();
let access_token_secret = hash_tab.lookup_str("oauth_token_secret").unwrap_or_default();

// The access token + secret is what should be saved and used for
// subsequent REST API calls.
println!("Access Token = {}", access_token);
println!("Access Token Secret = {}", access_token_secret);

// Save this access token for future calls.
// Just in case we need user_id and screen_name, save those also..
let json = chilkat::JsonObject::new();
let _ = json.append_string("oauth_token", &access_token);
let _ = json.append_string("oauth_token_secret", &access_token_secret);

let fac = chilkat::FileAccess::new();
let _ = fac.write_entire_text_file("qa_data/tokens/etrade.json", &json.emit().unwrap_or_default(), "utf-8", false);

println!("Success.");