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

Swift

func chilkatTest() {
    //  Read the metadata saved by Get a sandbox access token.
    let timing = CkoJsonObject()!
    let issued = CkoDateTime()!
    var loadedTiming: Bool = timing.loadFile(path: "paypal-token-timing.json")
    if loadedTiming != true {
        print("No timing metadata. Request a token.")
        return
    }

    var validTimestamp: Bool = issued.set(fromTimestamp: timing.string(of: "issued_at"))
    if validTimestamp != true {
        print("Invalid issue time. Request a token.")
        return
    }

    let now = CkoDateTime()!
    now.setFromCurrentSystemTime()
    var age: Int = now.diffSeconds(dateTimeArg: issued).intValue
    var lifetime: Int = timing.int(of: "expires_in").intValue
    if (age < 0) || (lifetime <= 300) || (age >= (lifetime - 300)) {
        print("Request a new client-credentials token.")
        return
    }

    print("Reuse the matching token from the credential store.")

}