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

Delphi DLL
var
timing: HCkJsonObject;
issued: HCkDateTime;
loadedTiming: Boolean;
validTimestamp: Boolean;
now: HCkDateTime;
age: Integer;
lifetime: Integer;

begin
//  Read the metadata saved by Get a sandbox access token.
timing := CkJsonObject_Create();
issued := CkDateTime_Create();
loadedTiming := CkJsonObject_LoadFile(timing,'paypal-token-timing.json');
if (loadedTiming <> True) then
  begin
    Memo1.Lines.Add('No timing metadata. Request a token.');
    Exit;
  end;
validTimestamp := CkDateTime_SetFromTimestamp(issued,CkJsonObject__stringOf(timing,'issued_at'));
if (validTimestamp <> True) then
  begin
    Memo1.Lines.Add('Invalid issue time. Request a token.');
    Exit;
  end;
now := CkDateTime_Create();
CkDateTime_SetFromCurrentSystemTime(now);
age := CkDateTime_DiffSeconds(now,issued);
lifetime := CkJsonObject_IntOf(timing,'expires_in');
if ((age < 0) or (lifetime <= 300) or (age >= (lifetime - 300))) then
  begin
    Memo1.Lines.Add('Request a new client-credentials token.');
    Exit;
  end;
Memo1.Lines.Add('Reuse the matching token from the credential store.');

CkJsonObject_Dispose(timing);
CkDateTime_Dispose(issued);
CkDateTime_Dispose(now);