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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Handle hoTiming
    Variant vIssued
    Handle hoIssued
    Boolean iLoadedTiming
    Boolean iValidTimestamp
    Handle hoNow
    Boolean iSuccess
    Integer iAge
    Integer iLifetime
    String sTemp1

    //  Read the metadata saved by Get a sandbox access token.
    Get Create (RefClass(cComChilkatJsonObject)) To hoTiming
    If (Not(IsComObjectCreated(hoTiming))) Begin
        Send CreateComObject of hoTiming
    End
    Get Create (RefClass(cComCkDateTime)) To hoIssued
    If (Not(IsComObjectCreated(hoIssued))) Begin
        Send CreateComObject of hoIssued
    End
    Get ComLoadFile Of hoTiming "paypal-token-timing.json" To iLoadedTiming
    If (iLoadedTiming <> True) Begin
        Showln "No timing metadata. Request a token."
        Procedure_Return
    End

    Get ComStringOf Of hoTiming "issued_at" To sTemp1
    Get ComSetFromTimestamp Of hoIssued sTemp1 To iValidTimestamp
    If (iValidTimestamp <> True) Begin
        Showln "Invalid issue time. Request a token."
        Procedure_Return
    End

    Get Create (RefClass(cComCkDateTime)) To hoNow
    If (Not(IsComObjectCreated(hoNow))) Begin
        Send CreateComObject of hoNow
    End
    Get ComSetFromCurrentSystemTime Of hoNow To iSuccess
    Get pvComObject of hoIssued to vIssued
    Get ComDiffSeconds Of hoNow vIssued To iAge
    Get ComIntOf Of hoTiming "expires_in" To iLifetime
    If ((iAge < 0) Or (iLifetime <= 300) Or (iAge >= (iLifetime - 300))) Begin
        Showln "Request a new client-credentials token."
        Procedure_Return
    End

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


End_Procedure