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

CkJava
import com.chilkatsoft.*;

public class ChilkatExample {

  static {
    try {
        System.loadLibrary("chilkat");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load.\n" + e);
      System.exit(1);
    }
  }

  public static void main(String argv[])
  {
    //  Read the metadata saved by Get a sandbox access token.
    CkJsonObject timing = new CkJsonObject();
    CkDateTime issued = new CkDateTime();
    boolean loadedTiming = timing.LoadFile("paypal-token-timing.json");
    if (loadedTiming != true) {
        System.out.println("No timing metadata. Request a token.");
        return;
        }

    boolean validTimestamp = issued.SetFromTimestamp(timing.stringOf("issued_at"));
    if (validTimestamp != true) {
        System.out.println("Invalid issue time. Request a token.");
        return;
        }

    CkDateTime now = new CkDateTime();
    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.");
  }
}