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

Chilkat C# Downloads

C#
//  Read the metadata saved by Get a sandbox access token.
Chilkat.JsonObject timing = new Chilkat.JsonObject();
Chilkat.CkDateTime issued = new Chilkat.CkDateTime();
bool loadedTiming = timing.LoadFile("paypal-token-timing.json");
if (loadedTiming != true) {
    Debug.WriteLine("No timing metadata. Request a token.");
    return;
}

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

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

Debug.WriteLine("Reuse the matching token from the credential store.");