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

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.DateTime;
import com.chilkatsoft.chilkat2.JsonObject;

public class ChilkatExample {

    public static void main(String[] args) {
        // Read the metadata saved by Get a sandbox access token.
        JsonObject timing = new JsonObject();
        DateTime issued = new DateTime();
        try {
            timing.loadFile("paypal-token-timing.json");
        } catch (ChilkatException e) {
            System.out.println("No timing metadata. Request a token.");
            return;
        }

        try {
            issued.setFromTimestamp(timing.stringOf("issued_at"));
        } catch (ChilkatException e) {
            System.out.println("Invalid issue time. Request a token.");
            return;
        }

        DateTime now = new DateTime();
        now.setFromCurrentSystemTime();
        int age = now.diffSeconds(issued);
        int lifetime = timing.intOf("expires_in");
        if ((age < 0) || ((lifetime <= 300) || (age >= (lifetime - 300)))) {
            System.out.println("Request a new client-credentials token.");
            return;
        }

        System.out.println("Reuse the matching token from the credential store.");
    }
}