簡體   English   中英

Google Calendar API - 創建/插入/添加事件 - C# - 錯誤 403

[英]Google Calendar API - Create/Insert/Add event - C# - error 403

我正在嘗試創建一個 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();
        }


    }
}

所以...我發現了問題:當應用程序第一次啟動時,Google API 根據所需的范圍創建了一個 token.json 文件。 就我而言,我首先使用“CalendarReadOnly”,然后在“Calendar”中編輯它,以便能夠創建和刪除事件。 所以我只是刪除了 token.json 並再次啟動了應用程序,並收到了一個具有“日歷”范圍的新 token.json。 另外,由於錯誤 400,我放棄了設置時區,但無論如何它都是可選的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM