Search code examples
delphigoogle-apigoogle-calendar-apigdatagdata-api

Create event in Google Calendar with Delphi - Error 401


My program has to connect to Google Calendar and create an event but I am receiving an error with text "Token invalid - AuthSub token has wrong scope"

The URL is http://www.google.com/calendar/feeds/default/owncalendars/full

This is my code:

Begin
  createXML := '<?xml version=''1.0'' encoding=''UTF-8''?>'#13#10 +
                  '<entry xmlns=''http://www.w3.org/2005/Atom'''#13#10 +
                  'xmlns:gd=''http://schemas.google.com/g/2005''>'#13#10 +
                  '<category scheme=''http://schemas.google.com/g/2005#kind'''#13#10 +
                  'term=''http://schemas.google.com/g/2005#event''></category>'#13#10 +
                  '<title type=''text''>' + title + '</title>'#13#10 +
                  '<content type=''text''>' + content + '</content>'#13#10 +
                  '<gd:transparency'#13#10 +
                  'value=''http://schemas.google.com/g/2005#event.opaque''>'#13#10 +
                  '</gd:transparency>'#13#10 +
                  '<gd:eventStatus'#13#10 +
                  'value=''http://schemas.google.com/g/2005#event.confirmed''>'#13#10 +
                  '</gd:eventStatus>'#13#10 +
                  '<gd:where valueString=''' + location + '''></gd:where>'#13#10 +
                  '<gd:when startTime=''' + EventStartTime + ''''#13#10 +
                  'endTime=''' + EventEndTime + '''></gd:when>'#13#10 +
                  '</entry>';

  HTTP:=THTTPSend.Create;
  url:=Edit3.Text;
  WriteStrToStream(HTTP.Document,EncodeURL(createXML));
  HTTP.Headers.Add('Authorization: OAuth '+OAuth.Access_token);
  HTTP.Headers.Add('GData-Version: 2');
  HTTP.MimeType:=('application/atom+xml');
  if HTTP.HTTPMethod('POST',url) then
  XML:=HTTP.Document;
  Memo2.Lines.LoadFromStream(XML);
End;

This is my code for OAuth Connection...

 Const
    client_id=%s&client_secret=%s&code=%s&redirect_uri=%s&grant_type=authorization_‌​‌​code'; 

.....

        procedure TForm2.Button4Click(Sender: TObject); var HTTP:THTTPSend; 
        begin HTTP:=THTTPSend.Create; 
        try 
        HTTP.Headers.Add('Authorization: OAuth '+OAuth.Access_token); 
        HTTP.Headers.Add('GData-Version: 2'); 
        if       HTTP.HTTPMethod('GET','google.com:443/calendar/feeds/default/allcalendars/full') then 
        XML:=HTTP.Document; 
        End;

Thank you very much for your time.

User: Google translate


Solution

  • Here you can read the protocol including what Authorization headers does it need. Even with the code you added it's still unclear how the OAuth object is built.

    However, I don't recommend you to continue using the GData API as it's being deprecated. Consider using the JSON-based v3 version along with the new authentication method. The API specification and usage is also new, so you will need to invest some time.