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

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

#  Read the metadata saved by Get a sandbox access token.
$timing = New-Object Chilkat.JsonObject
$issued = New-Object Chilkat.CkDateTime
$loadedTiming = $timing.LoadFile("paypal-token-timing.json")
if ($loadedTiming -ne $true) {
    $("No timing metadata. Request a token.")
    exit
}

$validTimestamp = $issued.SetFromTimestamp($timing.StringOf("issued_at"))
if ($validTimestamp -ne $true) {
    $("Invalid issue time. Request a token.")
    exit
}

$now = New-Object Chilkat.CkDateTime
$now.SetFromCurrentSystemTime()
$age = $now.DiffSeconds($issued)
$lifetime = $timing.IntOf("expires_in")
if (($age -lt 0) -or ($lifetime -le 300) -or ($age -ge ($lifetime - 300))) {
    $("Request a new client-credentials token.")
    exit
}

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