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

PayPal: Decide when to renew an access token

See more PayPal Examples

Use the UTC request time and expires_in from the token example. Renew five minutes early. This is a cache decision; a revoked token can still receive HTTP 401 before its calculated expiry.

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
//  Read the metadata saved by Get a sandbox access token.
var timing = new CkJsonObject();
var issued = new CkDateTime();
var loadedTiming = timing.LoadFile("paypal-token-timing.json");
if (loadedTiming !== true) {
    console.log("No timing metadata. Request a token.");
    return;
}

var validTimestamp = issued.SetFromTimestamp(timing.StringOf("issued_at"));
if (validTimestamp !== true) {
    console.log("Invalid issue time. Request a token.");
    return;
}

var now = new CkDateTime();
now.SetFromCurrentSystemTime();
var age = now.DiffSeconds(issued);
var lifetime = timing.IntOf("expires_in");
if ((age < 0) || (lifetime <= 300) || (age >= (lifetime - 300))) {
    console.log("Request a new client-credentials token.");
    return;
}

console.log("Reuse the matching token from the credential store.");