Google Calendar | RefreshToken

The Google Calendar API uses OAuth2 to authenticate against Google servers. sgcWebSockets has a component that handles the entire authentication process, but if your application closes and you attempt to connect again, you have two options:

 

1. Authenticate again using your Google APIs

2. Use the Refresh Token (if still valid), so you avoid the authentication process.

 

Using RefreshToken

The first time you authenticate, use the OnAuthToken event to save the RefreshToken if it exists. You can save it in an INI file, for example:

 


procedure OnGoogleCalendarAuthToken(Sender: TObject; const TokenType, Token, Data: string);
var
  oINI: TINIFile;
  oJSON: TsgcJSON;
begin
  oJSON := TsgcJSON.Create(nil);
  Try
    oJSON.Read(Data);
    if oJSON.Node['refresh_token']  nil then
    begin
      oINI := TINIFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
      Try
        oINI.WriteString('OAUTH2', 'Token', oJSON.Node['refresh_token'].Value);
      Finally
        oINI.Free;
      End;
    end;
  Finally
    oJSON.Free;
  End;
end;

Then, when you start your application again, if there is a RefreshToken, call the RefreshToken method and pass the token as an argument (you must first set the Google Calendar API keys). If successful, you will log in to Google servers without having to re-authenticate.

 


GoogleCalendar.RefreshToken('your refresh token here');