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

Lazarus Pascal
program ChilkatDemo;

// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}

uses
  {$IFDEF UNIX}
  cthreads,
  {$ENDIF}
  SysUtils,
  CkDllLoader,
  Chilkat.CkDateTime,
  Chilkat.HttpResponse,
  Chilkat.HttpRequest,
  Chilkat.JsonObject,
  Chilkat.Secrets,
  Chilkat.Http;

// ---------------------------------------------------------------------------

procedure RunDemo;
var
  vault: TSecrets;
  entry: TJsonObject;
  tokens: TJsonObject;
  loaded: Boolean;
  http: THttp;
  form: THttpRequest;
  resp: THttpResponse;
  sent: Boolean;
  reply: TJsonObject;
  parsed: Boolean;
  now: TCkDateTime;
  saved: Boolean;

begin
  //  Assumes Chilkat is unlocked. See Global Unlock Sample.
  vault := TSecrets.Create;
  vault.Location := 'local_manager';
  vault.AutoSplit := True;
  entry := TJsonObject.Create;
  entry.UpdateString('appName','ConstantContactV3');
  entry.UpdateString('service','OAuth2');
  entry.UpdateString('username','my-account');
  tokens := TJsonObject.Create;
  loaded := vault.GetSecretJson(entry,tokens);
  if (loaded <> True) then
    begin
      WriteLn('Run the desktop authorization example using this account and store.');
      Exit;
    end;
  if ((tokens.JsonTypeOf('refresh_token') <> 1) or (tokens.JsonTypeOf('client_id') <> 1) or (tokens.JsonTypeOf('redirect_uri') <> 1)) then
    begin
      WriteLn('The saved PKCE grant is incomplete. Authorize again.');
      Exit;
    end;
  http := THttp.Create;
  http.RequireSslCertVerify := True;
  form := THttpRequest.Create;
  form.HttpVerb := 'POST';
  form.ContentType := 'application/x-www-form-urlencoded';
  form.AddHeader('Accept','application/json');
  form.AddParam('grant_type','refresh_token');
  form.AddParam('client_id',tokens.StringOf('client_id'));
  form.AddParam('redirect_uri',tokens.StringOf('redirect_uri'));
  form.AddParam('refresh_token',tokens.StringOf('refresh_token'));
  resp := THttpResponse.Create;
  sent := http.HttpReq('https://authz.constantcontact.com/oauth2/default/v1/token',form,resp);
  reply := TJsonObject.Create;
  parsed := reply.Load(resp.BodyStr);
  if ((sent <> True) or (resp.StatusCode <> 200)) then
    begin
      WriteLn('Token refresh failed. HTTP status ' + resp.StatusCode);
      if (reply.StringOfEquals('error','invalid_grant',True) = True) then
        begin
          WriteLn('The refresh grant is no longer valid. Authorize again.');
        end;
      Exit;
    end;
  if ((reply.JsonTypeOf('access_token') <> 1) or (reply.IntOf('expires_in') <= 0)) then
    begin
      WriteLn('Token response is missing an access token or lifetime.');
      Exit;
    end;
  if (reply.StringOfEquals('access_token','',True) = True) then
    begin
      WriteLn('The returned access token is empty.');
      Exit;
    end;
  if (reply.JsonTypeOf('refresh_token') = 1) then
    begin
      if (reply.StringOfEquals('refresh_token','',True) <> True) then
        begin
          tokens.UpdateString('refresh_token',reply.StringOf('refresh_token'));
        end;
    end;
  now := TCkDateTime.Create;
  now.SetFromCurrentSystemTime();
  tokens.UpdateString('obtained_at_utc',now.GetAsTimestamp(False));
  tokens.UpdateString('access_token',reply.StringOf('access_token'));
  tokens.UpdateInt('expires_in',reply.IntOf('expires_in'));
  saved := vault.UpdateSecretJson(entry,tokens);
  if (saved <> True) then
    begin
      WriteLn('Could not save the current token record. Check the credential store.');
      Exit;
    end;
  WriteLn('Authorization saved. Access-token lifetime in seconds: ' + tokens.IntOf('expires_in'));


  vault.Free;
  entry.Free;
  tokens.Free;
  http.Free;
  form.Free;
  resp.Free;
  reply.Free;
  now.Free;

end;

// ---------------------------------------------------------------------------

begin

  try
    RunDemo;
  except
    on E: Exception do
      WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
  end;

  WriteLn;
  {$IFDEF MSWINDOWS}
  WriteLn('Press Enter to exit...');
  ReadLn;
  {$ENDIF}
end.