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

C
#include <C_CkJsonObject.h>
#include <C_CkDateTime.h>

void ChilkatSample(void)
    {
    HCkJsonObject timing;
    HCkDateTime issued;
    BOOL loadedTiming;
    BOOL validTimestamp;
    HCkDateTime now;
    int age;
    int lifetime;

    //  Read the metadata saved by Get a sandbox access token.
    timing = CkJsonObject_Create();
    issued = CkDateTime_Create();
    loadedTiming = CkJsonObject_LoadFile(timing,"paypal-token-timing.json");
    if (loadedTiming != TRUE) {
        printf("No timing metadata. Request a token.\n");
        CkJsonObject_Dispose(timing);
        CkDateTime_Dispose(issued);
        return;
    }

    validTimestamp = CkDateTime_SetFromTimestamp(issued,CkJsonObject_stringOf(timing,"issued_at"));
    if (validTimestamp != TRUE) {
        printf("Invalid issue time. Request a token.\n");
        CkJsonObject_Dispose(timing);
        CkDateTime_Dispose(issued);
        return;
    }

    now = CkDateTime_Create();
    CkDateTime_SetFromCurrentSystemTime(now);
    age = CkDateTime_DiffSeconds(now,issued);
    lifetime = CkJsonObject_IntOf(timing,"expires_in");
    if ((age < 0) || (lifetime <= 300) || (age >= (lifetime - 300))) {
        printf("Request a new client-credentials token.\n");
        CkJsonObject_Dispose(timing);
        CkDateTime_Dispose(issued);
        CkDateTime_Dispose(now);
        return;
    }

    printf("Reuse the matching token from the credential store.\n");


    CkJsonObject_Dispose(timing);
    CkDateTime_Dispose(issued);
    CkDateTime_Dispose(now);

    }