Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.0.0+

Constant Contact V3: Refresh a PKCE access token

See more Constant Contact Examples

Run desktop authorization first. Refresh near the saved expiry or after a 401. Reuse the original client ID and redirect URI and save any rotated refresh token with the new access token. Serialize refreshes for the same account so two processes cannot overwrite the newest grant. If the grant is invalid, authorize again.

Constant Contact developer guide

Chilkat Swift Downloads

Swift

func chilkatTest() {
    //  Assumes Chilkat is unlocked. See Global Unlock Sample.
    let vault = CkoSecrets()!
    vault.location = "local_manager"
    vault.autoSplit = true
    let entry = CkoJsonObject()!
    entry.updateString(jsonPath: "appName", value: "ConstantContactV3")
    entry.updateString(jsonPath: "service", value: "OAuth2")
    entry.updateString(jsonPath: "username", value: "my-account")
    let tokens = CkoJsonObject()!
    var loaded: Bool = vault.getSecretJson(jsonId: entry, jsonOut: tokens)
    if loaded != true {
        print("Run the desktop authorization example using this account and store.")
        return
    }

    if (tokens.jsonType(of: "refresh_token").intValue != 1) || (tokens.jsonType(of: "client_id").intValue != 1) || (tokens.jsonType(of: "redirect_uri").intValue != 1) {
        print("The saved PKCE grant is incomplete. Authorize again.")
        return
    }

    let http = CkoHttp()!
    http.requireSslCertVerify = true
    let form = CkoHttpRequest()!
    form.httpVerb = "POST"
    form.contentType = "application/x-www-form-urlencoded"
    form.addHeader(name: "Accept", value: "application/json")
    form.addParam(name: "grant_type", value: "refresh_token")
    form.addParam(name: "client_id", value: tokens.string(of: "client_id"))
    form.addParam(name: "redirect_uri", value: tokens.string(of: "redirect_uri"))
    form.addParam(name: "refresh_token", value: tokens.string(of: "refresh_token"))
    let resp = CkoHttpResponse()!
    var sent: Bool = http.httpReq(url: "https://authz.constantcontact.com/oauth2/default/v1/token", request: form, response: resp)
    let reply = CkoJsonObject()!
    var parsed: Bool = reply.load(json: resp.bodyStr)
    if (sent != true) || (resp.statusCode.intValue != 200) {
        print("Token refresh failed. HTTP status \(resp.statusCode.intValue)")
        if reply.string(ofEquals: "error", value: "invalid_grant", caseSensitive: true) == true {
            print("The refresh grant is no longer valid. Authorize again.")
        }

        return
    }

    if (reply.jsonType(of: "access_token").intValue != 1) || (reply.int(of: "expires_in").intValue <= 0) {
        print("Token response is missing an access token or lifetime.")
        return
    }

    if reply.string(ofEquals: "access_token", value: "", caseSensitive: true) == true {
        print("The returned access token is empty.")
        return
    }

    if reply.jsonType(of: "refresh_token").intValue == 1 {
        if reply.string(ofEquals: "refresh_token", value: "", caseSensitive: true) != true {
            tokens.updateString(jsonPath: "refresh_token", value: reply.string(of: "refresh_token"))
        }

    }

    let now = CkoDateTime()!
    now.setFromCurrentSystemTime()
    tokens.updateString(jsonPath: "obtained_at_utc", value: now.get(asTimestamp: false))
    tokens.updateString(jsonPath: "access_token", value: reply.string(of: "access_token"))
    tokens.updateInt(jsonPath: "expires_in", value: reply.int(of: "expires_in").intValue)
    var saved: Bool = vault.updateSecretJson(jsonId: entry, secret: tokens)
    if saved != true {
        print("Could not save the current token record. Check the credential store.")
        return
    }

    print("Authorization saved. Access-token lifetime in seconds: \(tokens.int(of: "expires_in").intValue)")

}