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

Lua
local chilkat = require("chilkat")

-- Read the metadata saved by Get a sandbox access token.
local timing = chilkat.JsonObject.new()
local issued = chilkat.DateTime.new()
local loadedTiming = timing:load_file("paypal-token-timing.json")
if not loadedTiming then
    print("No timing metadata. Request a token.")
    return
end

local validTimestamp = issued:set_from_timestamp(timing:string_of("issued_at"))
if not validTimestamp then
    print("Invalid issue time. Request a token.")
    return
end

local now = chilkat.DateTime.new()
now:set_from_current_system_time()
local age = now:diff_seconds(issued)
local lifetime = timing:int_of("expires_in")
if (age < 0) or ((lifetime <= 300) or (age >= (lifetime - 300))) then
    print("Request a new client-credentials token.")
    return
end

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