Node.js Requires Chilkat v11.0.0+
Node.js
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.
Chilkat Node.js Downloads
NODEJS_PRELUDE
function chilkatExample() {
var success = false;
// See Unlock Chilkat before making requests.
var http = new chilkat.Http();
// 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 chilkat.CkDateTime();
issued.SetFromCurrentSystemTime();
var resp = new chilkat.HttpResponse();
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 chilkat.JsonObject();
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 chilkat.JsonObject();
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 chilkat.JsonObject();
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);
}
chilkatExample();