Google Calendar API-创建/插入/添加事件-C#-错误403

时间:2019-03-13 08:31:12

标签: c# google-calendar-api

我正在尝试创建一个C#工具来操纵我的Google日历。 该工具正在成功从API接收事件,但是在尝试创建事件时出现错误:

Google.GoogleApiException: 'Google.Apis.Requests.RequestError
Insufficient Permission: Request had insufficient authentication scopes. [403]
Errors [
    Message[Insufficient Permission: Request had insufficient authentication scopes.] Location[ - ] Reason[insufficientPermissions] Domain[global]
]

我有2个按钮:一个用于创建事件,一个用于显示即将发生的事件。请注意,我尝试了3种不同的方法来添加事件,所有方法都具有相同的错误结果。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;

namespace GoogleCalendarsAssistant
{
    public partial class form_GoogleCalendarsAssistant : Form
    {
        public static class g
        {
            public static string[] Scopes = { CalendarService.Scope.Calendar };
            public static string ApplicationName = "GoogleCalendarsAssistant";

            public static UserCredential credential;
        }
        public string newline = "\r\n";
        public string tab     = "    ";


        public form_GoogleCalendarsAssistant()
        {
            InitializeComponent();
        }


        private void btn_addEvent_Click(object sender, EventArgs e)
        {
            using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created automatically when the authorization flow completes
                string credPath = "token.json";
                g.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    g.Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
                //tb_general.Text += newline + "Credential file saved to: " + credPath;
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = g.credential,
                ApplicationName = g.ApplicationName,
            });

            // Define parameters of request.
            Event addEvent_body = new Event();

            addEvent_body.Summary = "test summary";
            addEvent_body.Location = "test location";
            addEvent_body.Description = "test description";
            addEvent_body.Start = new EventDateTime()
            {
                DateTime = new DateTime(2019, 3, 7, 14, 0, 0),
                TimeZone = "Romania/Bucharest"
            };
            addEvent_body.End = new EventDateTime()
            {
                DateTime = new DateTime(2019, 3, 7, 15, 0, 0),
                TimeZone = "Romania/Bucharest"
            };
            addEvent_body.Attendees = new List<EventAttendee>()
            {
                new EventAttendee() {Email = "john@myjob.com"}
            };

            // Add event
            //method 1
            Event addEvent = service.Events.Insert(addEvent_body, "primary").Execute();

            //method 2
            //EventsResource.InsertRequest addEventResource = service.Events.Insert(addevent_body, "primary");
            //addEventResource.Execute();

            //method 3
            //EventsResource.InsertRequest request = service.Events.Insert(addevent_body, "primary");
            //request.Execute();
        }

        private void btn_upcoming_Click(object sender, EventArgs e)
        {
            using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created automatically when the authorization flow completes
                string credPath = "token.json";
                g.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    g.Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
                //tb_general.Text += newline + "Credential file saved to: " + credPath;
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = g.credential,
                ApplicationName = g.ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin = DateTime.Now;
            request.ShowDeleted = false;
            request.SingleEvents = true;
            request.MaxResults = 30;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = request.Execute();
            //Console.WriteLine("Upcoming events:");
            tb_general.Text = "Upcoming events:";
            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    string when = eventItem.Start.DateTime.ToString();
                    if (String.IsNullOrEmpty(when))
                    {
                        when = eventItem.Start.Date;
                    }
                    //Console.WriteLine("{0} ({1})", eventItem.Summary, when);
                    tb_general.Text += newline + tab + eventItem.Summary + when;
                }
            }
            else
            {
                //Console.WriteLine("No upcoming events found.");
                tb_general.Text = newline + "No upcoming events found.";
            }
            //Console.Read();
        }


    }
}

1 个答案:

答案 0 :(得分:0)

所以...我发现了问题:当应用程序首次启动时,Google API根据所需的作用域创建了token.json文件。就我而言,我首先使用“ CalendarReadOnly”,然后在“ Calendar”中进行了编辑,以便能够创建和删除事件。因此,我只是删除了token.json并再次启动了该应用程序,并且收到了带有“ Calendar”范围的新token.json。另外,由于错误400,我放弃了设置时区,但是无论如何都是可选的。