如何将Google Meet Link附加到日历事件(使用服务帐户创建)?

发布于 2025-02-11 00:37:57 字数 2622 浏览 0 评论 0原文

我正在尝试创建一个简单的API调用,以创建一个使用 Google Meet link 创建Google日历事件,但似乎我无法做到。

我查找了日历API文档,并看到了各种示例,但它仍然对我不起作用。我在nodejs上使用服务帐户和一个React前端。以下是我项目的源代码。

const { google } = require('googleapis');
const { GoogleAuth } = require('google-auth-library');
var express = require('express');
var router = express.Router();

const SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.addons.execute', 'https://www.googleapis.com/auth/calendar.settings.readonly', 'https://www.googleapis.com/auth/calendar.events'];
const GOOGLE_PRIVATE_KEY = "MY_PRIVATE_KEY"
const GOOGLE_CLIENT_EMAIL = "MY_SERVICE_ACCOUNT"
const GOOGLE_PROJECT_NUMBER = "MY_PROJECT_NUMBER"
const GOOGLE_CALENDAR_ID = "MY_CALENDAR_ID"

const jwtClient = new google.auth.JWT(
    GOOGLE_CLIENT_EMAIL,
    null,
    GOOGLE_PRIVATE_KEY,
    SCOPES,
    "MY_PERSONAL_EMAIL"
);

const calendar = google.calendar({
    version: 'v3',
    project: GOOGLE_PROJECT_NUMBER,
    auth: jwtClient
});

const auth = new GoogleAuth({
    keyFile: 'credentials.json',
    scopes: 'https://www.googleapis.com/auth/calendar', //full access to edit calendar
});

auth.getClient();

router.get("/demo", (req, res) => {
    var event = {
        'summary': 'My first event!',
        'location': 'Hyderabad,India',
        'description': 'First event with nodeJS!',
        'start': {
            'dateTime': '2022-06-28T09:00:00-07:00',
            'timeZone': 'Asia/Dhaka',
        },
        'end': {
            'dateTime': '2022-06-29T17:00:00-07:00',
            'timeZone': 'Asia/Dhaka',
        },
        'attendees': [],
        'reminders': {
            'useDefault': false,
            'overrides': [
                { 'method': 'email', 'minutes': 24 * 60 },
                { 'method': 'popup', 'minutes': 10 },
            ],
        },
        "conferenceData": {
            'createRequest': {
                "requestId": getRandomString(),
                "conferenceSolution": {
                    "key": {
                        "type": "hangoutsMeet",
                    }
                },
            }
        }
    };


    calendar.events.insert({
        auth: auth,
        calendarId: GOOGLE_CALENDAR_ID,
        requestBody: event,
        conferenceDataVersion: 1,
    }, function (err, event) {
        if (err) {
            console.log('There was an error contacting the Calendar service: ' + err);
            return;
        }
        console.log('Event created: %s', event.data);
        res.jsonp("Event successfully created!");
    });
})

I am trying to create a simple API call to create a Google Calendar Event with a Google Meet link in it but it seems I am unable to do so.

I looked up the Calendar API Documentation and have seen various examples but it still doesn't work for me. I am using a Service Account on NodeJS and a React frontend. Here below is the source code of my project.

const { google } = require('googleapis');
const { GoogleAuth } = require('google-auth-library');
var express = require('express');
var router = express.Router();

const SCOPES = ['https://www.googleapis.com/auth/calendar', 'https://www.googleapis.com/auth/calendar.addons.execute', 'https://www.googleapis.com/auth/calendar.settings.readonly', 'https://www.googleapis.com/auth/calendar.events'];
const GOOGLE_PRIVATE_KEY = "MY_PRIVATE_KEY"
const GOOGLE_CLIENT_EMAIL = "MY_SERVICE_ACCOUNT"
const GOOGLE_PROJECT_NUMBER = "MY_PROJECT_NUMBER"
const GOOGLE_CALENDAR_ID = "MY_CALENDAR_ID"

const jwtClient = new google.auth.JWT(
    GOOGLE_CLIENT_EMAIL,
    null,
    GOOGLE_PRIVATE_KEY,
    SCOPES,
    "MY_PERSONAL_EMAIL"
);

const calendar = google.calendar({
    version: 'v3',
    project: GOOGLE_PROJECT_NUMBER,
    auth: jwtClient
});

const auth = new GoogleAuth({
    keyFile: 'credentials.json',
    scopes: 'https://www.googleapis.com/auth/calendar', //full access to edit calendar
});

auth.getClient();

router.get("/demo", (req, res) => {
    var event = {
        'summary': 'My first event!',
        'location': 'Hyderabad,India',
        'description': 'First event with nodeJS!',
        'start': {
            'dateTime': '2022-06-28T09:00:00-07:00',
            'timeZone': 'Asia/Dhaka',
        },
        'end': {
            'dateTime': '2022-06-29T17:00:00-07:00',
            'timeZone': 'Asia/Dhaka',
        },
        'attendees': [],
        'reminders': {
            'useDefault': false,
            'overrides': [
                { 'method': 'email', 'minutes': 24 * 60 },
                { 'method': 'popup', 'minutes': 10 },
            ],
        },
        "conferenceData": {
            'createRequest': {
                "requestId": getRandomString(),
                "conferenceSolution": {
                    "key": {
                        "type": "hangoutsMeet",
                    }
                },
            }
        }
    };


    calendar.events.insert({
        auth: auth,
        calendarId: GOOGLE_CALENDAR_ID,
        requestBody: event,
        conferenceDataVersion: 1,
    }, function (err, event) {
        if (err) {
            console.log('There was an error contacting the Calendar service: ' + err);
            return;
        }
        console.log('Event created: %s', event.data);
        res.jsonp("Event successfully created!");
    });
})

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

彩扇题诗 2025-02-18 00:37:57

您解决了问题吗?

我还因为附带项目而研究了这一部分,我将分享我成功的代码。

我不确定当我看时哪一部分有所不同。

我希望此代码有帮助。

/* index.js */
const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const { v4: uuidv4 } = require('uuid');
const express = require('express');
const app = express()

// OAuth scope
const SCOPES = ['https://www.googleapis.com/auth/calendar.events'];
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/* Reads previously authorized credentials from the save file. */
async function loadSavedCredentialsIfExist() {
  try {
    const content = await fs.readFile(TOKEN_PATH);
    const credentials = JSON.parse(content);
    return google.auth.fromJSON(credentials);
  } catch (err) {
    return null;
  }
}

/* Serializes credentials to a file compatible with GoogleAUth.fromJSON. */
async function saveCredentials(client) {
  const content = await fs.readFile(CREDENTIALS_PATH);
  const keys = JSON.parse(content);
  const key = keys.installed || keys.web;
  const payload = JSON.stringify({
    type: 'authorized_user',
    client_id: key.client_id,
    client_secret: key.client_secret,
    refresh_token: client.credentials.refresh_token,
  });
  await fs.writeFile(TOKEN_PATH, payload);
}

/* Load or request or authorization to call APIs. */
async function authorize() {
  let client = await loadSavedCredentialsIfExist();
  if (client) {
    return client;
  }
  client = await authenticate({
    scopes: SCOPES,
    keyfilePath: CREDENTIALS_PATH,
  });
  if (client.credentials) {
    await saveCredentials(client);
  }
  return client;
}

/**
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
async function inserEvent(auth) {
  const calendar = google.calendar({version: 'v3', auth});
  
  const event = {
    summary: 'Demo',
    description: 'Demo for Google Meet',
    start: {
      dateTime: '2022-11-20T09:00:00+09:00',
      timeZone: 'Asia/Seoul',
    },
    end: {
      dateTime: '2022-11-20T09:30:00+09:00',
      timeZone: 'Asia/Seoul',
    },
    conferenceData: {
      createRequest: {
        conferenceSolutionKey: {type: 'hangoutsMeet'},
        requestId: uuidv4(),
      },
    },
    attendees: [
      {email: '${email1}'}, /* insert email */
      {email: '${email2}'}, /* insert email */
    ],
    reminders: {
      useDefault: false,
      overrides: [
        {method: 'email', minutes: 60},
        {method: 'popup', minutes: 10},
      ],
    },
  };

  calendar.events.insert({
    auth: auth,
    calendarId: 'primary',
    resource: event,
    conferenceDataVersion: 1,
  }, function(err, event) {
    if (err) {
      console.log('There was an error contacting the Calendar service: ' + err);
      return;
    }
    console.log('Event created, google meet link :  %s', event.data.hangoutLink);
  });
}

app.get("/demo", (rqe, res) => {
  authorize().then(inserEvent).catch(console.error);
  res.send('Good');
})

app.listen(3000, () => {
  console.log('listening on port 3000');
})


Did you solve the Issue?

I also looked into this part because of a side project, and I'll share the code I've had success with.

I'm not sure which part is different when I look at it.

I hope this code helps.

/* index.js */
const fs = require('fs').promises;
const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const { v4: uuidv4 } = require('uuid');
const express = require('express');
const app = express()

// OAuth scope
const SCOPES = ['https://www.googleapis.com/auth/calendar.events'];
const TOKEN_PATH = path.join(process.cwd(), 'token.json');
const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');

/* Reads previously authorized credentials from the save file. */
async function loadSavedCredentialsIfExist() {
  try {
    const content = await fs.readFile(TOKEN_PATH);
    const credentials = JSON.parse(content);
    return google.auth.fromJSON(credentials);
  } catch (err) {
    return null;
  }
}

/* Serializes credentials to a file compatible with GoogleAUth.fromJSON. */
async function saveCredentials(client) {
  const content = await fs.readFile(CREDENTIALS_PATH);
  const keys = JSON.parse(content);
  const key = keys.installed || keys.web;
  const payload = JSON.stringify({
    type: 'authorized_user',
    client_id: key.client_id,
    client_secret: key.client_secret,
    refresh_token: client.credentials.refresh_token,
  });
  await fs.writeFile(TOKEN_PATH, payload);
}

/* Load or request or authorization to call APIs. */
async function authorize() {
  let client = await loadSavedCredentialsIfExist();
  if (client) {
    return client;
  }
  client = await authenticate({
    scopes: SCOPES,
    keyfilePath: CREDENTIALS_PATH,
  });
  if (client.credentials) {
    await saveCredentials(client);
  }
  return client;
}

/**
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
async function inserEvent(auth) {
  const calendar = google.calendar({version: 'v3', auth});
  
  const event = {
    summary: 'Demo',
    description: 'Demo for Google Meet',
    start: {
      dateTime: '2022-11-20T09:00:00+09:00',
      timeZone: 'Asia/Seoul',
    },
    end: {
      dateTime: '2022-11-20T09:30:00+09:00',
      timeZone: 'Asia/Seoul',
    },
    conferenceData: {
      createRequest: {
        conferenceSolutionKey: {type: 'hangoutsMeet'},
        requestId: uuidv4(),
      },
    },
    attendees: [
      {email: '${email1}'}, /* insert email */
      {email: '${email2}'}, /* insert email */
    ],
    reminders: {
      useDefault: false,
      overrides: [
        {method: 'email', minutes: 60},
        {method: 'popup', minutes: 10},
      ],
    },
  };

  calendar.events.insert({
    auth: auth,
    calendarId: 'primary',
    resource: event,
    conferenceDataVersion: 1,
  }, function(err, event) {
    if (err) {
      console.log('There was an error contacting the Calendar service: ' + err);
      return;
    }
    console.log('Event created, google meet link :  %s', event.data.hangoutLink);
  });
}

app.get("/demo", (rqe, res) => {
  authorize().then(inserEvent).catch(console.error);
  res.send('Good');
})

app.listen(3000, () => {
  console.log('listening on port 3000');
})


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文