首页 > 解决方案 > 带有 ASP.NET 的 Google 日历 API

问题描述

我对使用 Google 日历 API 在 ASP.NET 网络表单(C#)中添加/修改事件感到困惑。

我不确定我是否需要 oAuth 或什么。我的应用程序在我自己的服务器上访问我自己的域和我自己的日历。我不需要其他用户允许我访问他们的日历;我只需要通过我的应用程序访问我自己的。

在我的一个 aspx 页面上,我想将事件信息发送到我的 Google 日历以添加(或稍后修改)该事件。

我检查了各种代码示例和 Google 入门指南。我只是不清楚到底需要什么。我已经设置了一个 API 密钥和一个 oAuth2 客户端 ID。谷歌的指示让我转了一圈,这可能是因为我需要澄清需要什么。

有人可以消除我的困惑并指出我正确的方向吗?

标签: c#asp.netgoogle-calendar-api

解决方案


概括 :

  • 调用谷歌云 oauth2 保护资源

  • 从您的服务器到谷歌服务器

  • 无需用户交互

  • 访问您自己的数据

  • 使用 C#

代码 :

    var private_key = @"-----BEGIN PRIVATE KEY-ccc-END PRIVATE KEY-----\n";
    string calendarId = @"xxxxxxxxxxxxx@group.calendar.google.com";
    var client_email = @"my-google-calender@xxx.iam.gserviceaccount.com";

    var credential =
        new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(client_email)
        {
            Scopes = new string[] { CalendarService.Scope.Calendar }
        }.FromPrivateKey(private_key));
    var service = new CalendarService(new BaseClientService.Initializer()
    {
        HttpClientInitializer = credential,
    });
  • 使用服务方法获取数据

  • 可以从此链接生成私钥和 client_email

  • 日历 ID 可在 calendar.google.com 上找到

  • 您必须与 client_email 共享您的日历查看演示


  Google            You                             You
  Pay +             Pay +                           Pay +
  Google            Google                          You
  Manage            Manage                          Manage%
 +----------+    +----------+                     +----------+
 | Gmail    |    |          |                     |          |
 | Calendar |    |  G Suite |                     | Google   |
 | drive    |    |          |                     | Cloud    |
 |          |    |          |                     |          |
 +----^-----+    +----+-----+                     +------+---+
      |               ^                                  ^
      |               |                                  |
      |               |                                  |
      |               |                                  |
+-------------------------------------------------------------+
|     |               |                                  |    |
|     |               |                                  |    |
|     |               |       Google                     |    |
|     |               |       Oauth2                     |    |
|     |               |       Server                     |    |
|     |               |                                  |    |
|     |               |                                  |    |
+-------------------------------------------------------------+
      |               |                                  |
      |               |         +----------------+       |
      |               |         |                |       |
      |               |         |                |       | No
      |               |require  |                |       | Consent
      |               |admin    |                |       |
      |               |consent  |                |       |
      |require        |         |                +-------+
      |user           |         |                |
      |consent        +---------+   Your app     |
      |                         |                |
      |                         |                |
      |                         |                |
      |                         |                |
      +-------------------------+                |
                                |                |
                                |                |
                                |                |
                                +----------------+
                                     You
                                     Pay +
                                     You
                                     Manage

逐步演示


步骤 01:打开谷歌控制台

https://console.developers.google.com/projectselector/apis/library/calendar-json.googleapis.com

步骤02:点击选择

在此处输入图像描述

步骤 03:选择或创建一个新项目

在此处输入图像描述

步骤04:点击启用或管理

在此处输入图像描述 在此处输入图像描述

步骤 05:单击凭据

在此处输入图像描述

步骤 06:创建服务帐户密钥

在此处输入图像描述

步骤 07:输入服务帐户名称点击创建

在此处输入图像描述

步骤 08:点击 Create without role 然后将下载的 json 私钥保存在安全的地方

在此处输入图像描述

步骤 09:复制您的 client_email 从

在此处输入图像描述

第十步:打开谷歌日历

  • 日历.google.com

第 11 步:打开您的日历设置和共享

在此处输入图像描述

第 12 步:必须与特定的人共享,然后单击添加

在此处输入图像描述

第十三步:

  1. 添加您之前在步骤 09中复制的服务帐户的电子邮件
  2. 更改权限也进行更改并管理共享
  3. 点击发送

    在此处输入图像描述

第 14 步:在同一页面上复制并保存我们需要的日历 ID

在此处输入图像描述

第 15 步:创建新的控制台应用程序

在此处输入图像描述

第 16 步:将私钥 json 文件添加到您的项目中

在此处输入图像描述

第 17 步:右击私钥 json 并单击 Propertis

在此处输入图像描述

第 18 步:将“复制到输出目录”更改为“始终复制”

在此处输入图像描述

第 19 步:打开 PM 控制台并在默认项目 D 上选择您的项目

在此处输入图像描述

第 20 步:安装 Google.Apis 日历包

Install-Package Google.Apis.Calendar.v3

在此处输入图像描述

第 21 步:将 Program.cs 替换为代码

using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace CalendarQuickstart
{
    class Program
    {
        static void Main(string[] args)
        {
            string jsonFile = "xxxxxxx-xxxxxxxxxxxxx.json";
            string calendarId = @"xxxxxxxxxxxxx@group.calendar.google.com";

            string[] Scopes = { CalendarService.Scope.Calendar };

            ServiceAccountCredential credential;

            using (var stream =
                new FileStream(jsonFile, FileMode.Open, FileAccess.Read))
            {
                var confg = Google.Apis.Json.NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(stream);
                credential = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(confg.ClientEmail)
                   {
                       Scopes = Scopes
                   }.FromPrivateKey(confg.PrivateKey));
            }

            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Calendar API Sample",
            });

            var calendar = service.Calendars.Get(calendarId).Execute();
            Console.WriteLine("Calendar Name :");
            Console.WriteLine(calendar.Summary);

            Console.WriteLine("click for more .. ");
            Console.Read();


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

            // List events.
            Events events = listRequest.Execute();
            Console.WriteLine("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);
                }
            }
            else
            {
                Console.WriteLine("No upcoming events found.");
            }
            Console.WriteLine("click for more .. ");
            Console.Read();

            var myevent = DB.Find(x => x.Id == "eventid" + 1);

            var InsertRequest = service.Events.Insert(myevent, calendarId);

            try
            {
                InsertRequest.Execute();
            }
            catch (Exception)
            {
                try
                {
                    service.Events.Update(myevent, calendarId, myevent.Id).Execute();
                    Console.WriteLine("Insert/Update new Event ");
                    Console.Read();

                }
                catch (Exception)
                {
                    Console.WriteLine("can't Insert/Update new Event ");

                }
            }
        }


        static List<Event> DB =
             new List<Event>() {
                new Event(){
                    Id = "eventid" + 1,
                    Summary = "Google I/O 2015",
                    Location = "800 Howard St., San Francisco, CA 94103",
                    Description = "A chance to hear more about Google's developer products.",
                    Start = new EventDateTime()
                    {
                        DateTime = new DateTime(2019, 01, 13, 15, 30, 0),
                        TimeZone = "America/Los_Angeles",
                    },
                    End = new EventDateTime()
                    {
                        DateTime = new DateTime(2019, 01, 14, 15, 30, 0),
                        TimeZone = "America/Los_Angeles",
                    },
                     Recurrence = new List<string> { "RRULE:FREQ=DAILY;COUNT=2" },
                    Attendees = new List<EventAttendee>
                    {
                        new EventAttendee() { Email = "lpage@example.com"},
                        new EventAttendee() { Email = "sbrin@example.com"}
                    }
                }
             };
    }
}

第 22 步:将 json File Name 替换为您的 json 文件名

  string jsonFile = "xxxxxxx-xxxxxxxx.json";

第 23 步:将 calendarId 替换为第 14 步中的 calendarId

 string calendarId = @"xxxxxxxxxxxxx@group.calendar.google.com";

第 24 步:运行应用程序

在此处输入图像描述

第 25 步:访问您的日历,您应该会在其中看到该事件

 2019/01/13

在此处输入图像描述


推荐阅读