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

Constant Contact V3: Authorize a desktop app with PKCE

See more Constant Contact Examples

Register a V3 app for the public-client PKCE flow and register http://localhost:3017/ exactly, including the trailing slash. Chilkat opens the system browser, receives the redirect on the same computer, and exchanges the code using the PKCE verifier. Request contact_data for contacts and lists, campaign_data for email campaigns and reporting, and offline_access for refresh. If the app already has a contacts-only grant, repeat this browser authorization to grant campaign access. Refreshing the old token cannot add a scope. Use a client ID from the PKCE app registration.

The examples share a Chilkat Secrets record. Windows Credential Manager and Apple Keychain persist the local record. On systems where the local manager uses process memory, configure a persistent Secrets backend for all examples. Give each authorized account its own record name. If migrating from the old token-file example, authorize once to populate the store.

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.OAuth2,
  Chilkat.JsonObject,
  Chilkat.Secrets;

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

procedure RunDemo;
var
  oauth: TOAuth2;
  url: string;
  opened: Boolean;
  waited: Integer;
  reply: TJsonObject;
  parsed: Boolean;
  vault: TSecrets;
  entry: TJsonObject;
  tokens: TJsonObject;
  now: TCkDateTime;
  saved: Boolean;

begin
  //  Assumes Chilkat is unlocked. See Global Unlock Sample.
  oauth := TOAuth2.Create;
  oauth.AuthorizationEndpoint := 'https://authz.constantcontact.com/oauth2/default/v1/authorize';
  oauth.TokenEndpoint := 'https://authz.constantcontact.com/oauth2/default/v1/token';
  oauth.ClientId := 'PKCE_CLIENT_ID';
  oauth.LocalHost := 'localhost';
  oauth.ListenPort := 3017;
  //  Run authorization again if the account previously granted only contact access.
  oauth.Scope := 'contact_data campaign_data offline_access';
  oauth.CodeChallenge := True;
  oauth.CodeChallengeMethod := 'S256';
  oauth.UseBasicAuth := False;
  url := oauth.StartAuth();
  if (oauth.LastMethodSuccess <> True) then
    begin
      WriteLn('Could not start the local listener. Check the registered port.');
      Exit;
    end;
  opened := oauth.LaunchBrowser(url);
  if (opened <> True) then
    begin
      oauth.Cancel();
      WriteLn('Could not open the system browser.');
      Exit;
    end;
  waited := 0;
  while ((waited < 300000) and (oauth.AuthFlowState < 3)) do
    begin
      oauth.SleepMs(100);
      waited := waited + 100;
    end;

  if (oauth.AuthFlowState < 3) then
    begin
      oauth.Cancel();
      WriteLn('Authorization timed out.');
      Exit;
    end;
  if (oauth.AuthFlowState = 4) then
    begin
      WriteLn('Authorization was declined.');
      Exit;
    end;
  if (oauth.AuthFlowState <> 3) then
    begin
      WriteLn('Authorization failed. Check the PKCE app registration and exact redirect URI.');
      Exit;
    end;
  reply := TJsonObject.Create;
  parsed := reply.Load(oauth.AccessTokenResponse);
  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) or (reply.StringOfEquals('refresh_token','',True) = True)) then
    begin
      WriteLn('Missing refresh token. Check the offline_access scope and authorize again.');
      Exit;
    end;
  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;
  tokens.UpdateString('client_id',oauth.ClientId);
  tokens.UpdateString('redirect_uri','http://localhost:3017/');
  tokens.UpdateString('refresh_token',reply.StringOf('refresh_token'));
  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'));


  oauth.Free;
  reply.Free;
  vault.Free;
  entry.Free;
  tokens.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.