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

SQL Server
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
    DECLARE @hr int
    DECLARE @sTmp0 nvarchar(4000)
    --  Read the metadata saved by Get a sandbox access token.
    DECLARE @timing int
    EXEC @hr = sp_OACreate 'Chilkat.JsonObject', @timing OUT
    IF @hr <> 0
    BEGIN
        PRINT 'Failed to create ActiveX component'
        RETURN
    END

    DECLARE @issued int
    EXEC @hr = sp_OACreate 'Chilkat.CkDateTime', @issued OUT

    DECLARE @loadedTiming int
    EXEC sp_OAMethod @timing, 'LoadFile', @loadedTiming OUT, 'paypal-token-timing.json'
    IF @loadedTiming <> 1
      BEGIN

        PRINT 'No timing metadata. Request a token.'
        EXEC @hr = sp_OADestroy @timing
        EXEC @hr = sp_OADestroy @issued
        RETURN
      END
    DECLARE @validTimestamp int
    EXEC sp_OAMethod @timing, 'StringOf', @sTmp0 OUT, 'issued_at'
    EXEC sp_OAMethod @issued, 'SetFromTimestamp', @validTimestamp OUT, @sTmp0
    IF @validTimestamp <> 1
      BEGIN

        PRINT 'Invalid issue time. Request a token.'
        EXEC @hr = sp_OADestroy @timing
        EXEC @hr = sp_OADestroy @issued
        RETURN
      END
    DECLARE @now int
    EXEC @hr = sp_OACreate 'Chilkat.CkDateTime', @now OUT

    DECLARE @success int
    EXEC sp_OAMethod @now, 'SetFromCurrentSystemTime', @success OUT
    DECLARE @age int
    EXEC sp_OAMethod @now, 'DiffSeconds', @age OUT, @issued
    DECLARE @lifetime int
    EXEC sp_OAMethod @timing, 'IntOf', @lifetime OUT, 'expires_in'
    IF (@age < 0) or (@lifetime <= 300) or (@age >= (@lifetime - 300))
      BEGIN

        PRINT 'Request a new client-credentials token.'
        EXEC @hr = sp_OADestroy @timing
        EXEC @hr = sp_OADestroy @issued
        EXEC @hr = sp_OADestroy @now
        RETURN
      END

    PRINT 'Reuse the matching token from the credential store.'

    EXEC @hr = sp_OADestroy @timing
    EXEC @hr = sp_OADestroy @issued
    EXEC @hr = sp_OADestroy @now


END
GO