Sample code for 30+ languages & platforms
Rust Requires Chilkat v11.0.0+

PayPal: Get a sandbox access token

See more PayPal Examples

Exchange a sandbox REST app client ID and secret for a bearer token on a merchant-controlled backoffice workstation. PayPal supplies its lifetime in seconds. Store the token in a protected credential store; the companion expiry example reads only timing metadata.

PayPal documentation

Chilkat Rust Downloads

Rust

// See Unlock Chilkat before making requests.
let http = chilkat::Http::new();
// Load these values from the credential store on the merchant backoffice workstation.
// Never embed the merchant secret in an app distributed to customers.
http.set_login("SANDBOX_CLIENT_ID");
http.set_password("SANDBOX_CLIENT_SECRET");
http.set_basic_auth(true);
let issued = chilkat::DateTime::new();
let _ = issued.set_from_current_system_time();
let resp = chilkat::HttpResponse::new();
if http.http_str("POST", "https://api-m.sandbox.paypal.com/v1/oauth2/token", "grant_type=client_credentials", "utf-8", "application/x-www-form-urlencoded", &resp).is_err() {
    println!("No HTTP response: {}", http.last_error_text());
    return;
}

if (resp.status_code() < 200) || (resp.status_code() >= 300) {
    let error_info = chilkat::JsonObject::new();
    let _ = error_info.load(&resp.body_str());
    println!("HTTP {} {} {}", resp.status_code(), error_info.string_of("error").unwrap_or_default(), error_info.string_of("error_description").unwrap_or_default());
    println!("PayPal debug ID: {}", error_info.string_of("debug_id").unwrap_or_default());
    return;
}

let result = chilkat::JsonObject::new();
if result.load(&resp.body_str()).is_err() {
    println!("Expected a JSON response; HTTP {}", resp.status_code());
    return;
}

let access_token = result.string_of("access_token").unwrap_or_default();
let lifetime = result.int_of("expires_in");
if (!result.has_member("access_token")) || (lifetime <= 0) {
    println!("Missing token or lifetime.");
    return;
}

// Supply accessToken to Http.AuthToken. Never log the bearer token or client secret.
// Save only timing metadata here, relative to the start of the token request.
let timing = chilkat::JsonObject::new();
let _ = timing.update_string("issued_at", &issued.get_as_timestamp(false).unwrap_or_default());
let _ = timing.update_int("expires_in", lifetime);
if timing.write_file("paypal-token-timing.json").is_err() {
    println!("Could not save token timing.");
    return;
}

println!("Token received; lifetime in seconds: {}", lifetime);