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

PureBasic
IncludeFile "CkDateTime.pb"
IncludeFile "CkJsonObject.pb"

Procedure ChilkatExample()

    ;  Read the metadata saved by Get a sandbox access token.
    timing.i = CkJsonObject::ckCreate()
    If timing.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    issued.i = CkDateTime::ckCreate()
    If issued.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    loadedTiming.i = CkJsonObject::ckLoadFile(timing,"paypal-token-timing.json")
    If loadedTiming <> 1
        Debug "No timing metadata. Request a token."
        CkJsonObject::ckDispose(timing)
        CkDateTime::ckDispose(issued)
        ProcedureReturn
    EndIf

    validTimestamp.i = CkDateTime::ckSetFromTimestamp(issued,CkJsonObject::ckStringOf(timing,"issued_at"))
    If validTimestamp <> 1
        Debug "Invalid issue time. Request a token."
        CkJsonObject::ckDispose(timing)
        CkDateTime::ckDispose(issued)
        ProcedureReturn
    EndIf

    now.i = CkDateTime::ckCreate()
    If now.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkDateTime::ckSetFromCurrentSystemTime(now)
    age.i = CkDateTime::ckDiffSeconds(now,issued)
    lifetime.i = CkJsonObject::ckIntOf(timing,"expires_in")
    If (age < 0) OR (lifetime <= 300) OR (age >= (lifetime - 300))
        Debug "Request a new client-credentials token."
        CkJsonObject::ckDispose(timing)
        CkDateTime::ckDispose(issued)
        CkDateTime::ckDispose(now)
        ProcedureReturn
    EndIf

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


    CkJsonObject::ckDispose(timing)
    CkDateTime::ckDispose(issued)
    CkDateTime::ckDispose(now)


    ProcedureReturn
EndProcedure