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

Xbase++
LOCAL oTiming
LOCAL oIssued
LOCAL nLoadedTiming
LOCAL nValidTimestamp
LOCAL oNow
LOCAL nAge
LOCAL nLifetime

//  Read the metadata saved by Get a sandbox access token.
oTiming := CreateObject("Chilkat.JsonObject")
oIssued := CreateObject("Chilkat.CkDateTime")
nLoadedTiming := oTiming:LoadFile("paypal-token-timing.json")
IF (nLoadedTiming != 1)
    ? "No timing metadata. Request a token."
    oTiming:destroy()
    oIssued:destroy()
    RETURN
ENDIF

nValidTimestamp := oIssued:SetFromTimestamp(oTiming:StringOf("issued_at"))
IF (nValidTimestamp != 1)
    ? "Invalid issue time. Request a token."
    oTiming:destroy()
    oIssued:destroy()
    RETURN
ENDIF

oNow := CreateObject("Chilkat.CkDateTime")
oNow:SetFromCurrentSystemTime()
nAge := oNow:DiffSeconds(oIssued)
nLifetime := oTiming:IntOf("expires_in")
IF ((nAge < 0) .OR. (nLifetime <= 300) .OR. (nAge >= (nLifetime - 300)))
    ? "Request a new client-credentials token."
    oTiming:destroy()
    oIssued:destroy()
    oNow:destroy()
    RETURN
ENDIF

? "Reuse the matching token from the credential store."

oTiming:destroy()
oIssued:destroy()
oNow:destroy()