Sample code for 30+ languages & platforms
JavaScript 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

Note
This example is intended for running within a Chilkat.Js embedded JavaScript engine. All Chilkat JavaScript examples require Chilkat v11.4.0 or greater.
JavaScript
var success = false;

//  See Unlock Chilkat before making requests.
var http = new CkHttp();
//  Load these values from the credential store on the merchant backoffice workstation.
//  Never embed the merchant secret in an app distributed to customers.
http.Login = "SANDBOX_CLIENT_ID";
http.Password = "SANDBOX_CLIENT_SECRET";
http.BasicAuth = true;
var issued = new CkDateTime();
issued.SetFromCurrentSystemTime();
var resp = new CkHttpResponse();
success = http.HttpStr("POST","https://api-m.sandbox.paypal.com/v1/oauth2/token","grant_type=client_credentials","utf-8","application/x-www-form-urlencoded",resp);
if (success !== true) {
    console.log("No HTTP response: " + http.LastErrorText);
    return;
}

if ((resp.StatusCode < 200) || (resp.StatusCode >= 300)) {
    var errorInfo = new CkJsonObject();
    errorInfo.Load(resp.BodyStr);
    console.log("HTTP " + resp.StatusCode + " " + errorInfo.StringOf("error") + " " + errorInfo.StringOf("error_description"));
    console.log("PayPal debug ID: " + errorInfo.StringOf("debug_id"));
    return;
}

var result = new CkJsonObject();
var parsed = result.Load(resp.BodyStr);
if (parsed !== true) {
    console.log("Expected a JSON response; HTTP " + resp.StatusCode);
    return;
}

var accessToken = result.StringOf("access_token");
var lifetime = result.IntOf("expires_in");
if ((result.HasMember("access_token") !== true) || (lifetime <= 0)) {
    console.log("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.
var timing = new CkJsonObject();
timing.UpdateString("issued_at",issued.GetAsTimestamp(false));
timing.UpdateInt("expires_in",lifetime);
var savedTiming = timing.WriteFile("paypal-token-timing.json");
if (savedTiming !== true) {
    console.log("Could not save token timing.");
    return;
}

console.log("Token received; lifetime in seconds: " + lifetime);