google calendar api php
Go quickstart
Complete the steps described in the rest of this page to create a simple Go command-line application that makes requests to the Google Calendar API.
Prerequisites
To run this quickstart, you need the following prerequisites:
Step 1: Prepare the workspace
Step 2: Set up the sample
Create a file named quickstart.go in your working directory and copy in the following code:
Step 3: Run the sample
Build and run the sample using the following command from your working directory:
The first time you run the sample, it prompts you to authorize access:
Browse to the provided URL in your web browser.
If you’re not already signed in to your Google account, you’re prompted to sign in. If you’re signed in to multiple Google accounts, you are asked to select one account to use for authorization.
Notes
Troubleshooting
This section describes some common issues that you may encounter while attempting to run this quickstart and suggests possible solutions.
This app isn’t verified
If the OAuth consent screen displays the warning «This app isn’t verified,» your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to
Further reading
For further information on the APIs used in this quickstart, refer to the google-api-go-client section of GitHub.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
PHP Quickstart
Complete the steps described in the rest of this page to create a simple PHP command-line application that makes requests to the Google Calendar API.
Prerequisites
To run this quickstart, you need the following prerequisites:
Step 1: Install the Google Client Library
See the library’s installation page for the alternative installation options.
Step 2: Set up the sample
Create a file named quickstart.php in your working directory and copy in the following code:
Step 3: Run the sample
Run the sample using the following command:
The first time you run the sample, it prompts you to authorize access:
Browse to the provided URL in your web browser.
If you are not already signed in to your Google account, you are be prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for the authorization.
Notes
Troubleshooting
This section describes some common issues that you may encounter while attempting to run this quickstart and suggests possible solutions.
SSL certificate problem: unable to get local issuer certificate
This error indicates that the underlying HTTP libraries can’t find a certificate store, and are therefore unable to setup the SSL connection to Google’s servers. See the Guzzle library’s documentation for information on how to setup a certificate store on your machine.
Uncaught InvalidArgumentException: missing the required redirect URI
This error occurs when the credentials.json file used contains a client ID of the wrong type. This code requires an OAuth client ID of type Other, which will be created for you when using the button in Step 1. If creating your own client ID please ensure you select the correct type.
This app isn’t verified
If the OAuth consent screen displays the warning «This app isn’t verified,» your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to
Further reading
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Google Calendar API Overview
The Google Calendar API is a RESTful API that can be accessed through explicit HTTP calls or via the Google Client Libraries. The API exposes most of the features available in the Google Calendar Web interface.
Following is a list of common terms used in the Google Calendar API:
Event An event on a calendar containing information such as the title, start and end times, and attendees. Events can be either single events or recurring events. An event is represented by an Event resource. Calendar A collection of events. Each calendar has associated metadata, such as calendar description or default calendar time zone. The metadata for a single calendar is represented by a Calendar resource. Calendar List A list of all calendars on a user’s calendar list in the Calendar UI. The metadata for a single calendar that appears on the calendar list is represented by a CalendarListEntry resource. This metadata includes user-specific properties of the calendar, such as its color or notifications for new events. Setting A user preference from the Calendar UI, such as the user’s time zone. A single user preference is represented by a Setting Resource. ACL An access control rule granting a user (or a group of users) a specified level of access to a calendar. A single access control rule is represented by an ACL resource.
Next steps
To get started with Google Calendar API:
To learn about developing with Google Workspace APIs, including handling authentication and authorization, refer to Get started as a Workspace developer.
To learn how to configure and run a simple Google Calendar API app, read the Quickstarts overview.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
PHP Quickstart
Complete the steps described in the rest of this page to create a simple PHP command-line application that makes requests to the Google Calendar API.
Prerequisites
To run this quickstart, you need the following prerequisites:
Step 1: Install the Google Client Library
See the library’s installation page for the alternative installation options.
Step 2: Set up the sample
Create a file named quickstart.php in your working directory and copy in the following code:
Step 3: Run the sample
Run the sample using the following command:
The first time you run the sample, it prompts you to authorize access:
Browse to the provided URL in your web browser.
If you are not already signed in to your Google account, you are be prompted to sign in. If you are signed in to multiple Google accounts, you are asked to select one account to use for the authorization.
Notes
Troubleshooting
This section describes some common issues that you may encounter while attempting to run this quickstart and suggests possible solutions.
SSL certificate problem: unable to get local issuer certificate
This error indicates that the underlying HTTP libraries can’t find a certificate store, and are therefore unable to setup the SSL connection to Google’s servers. See the Guzzle library’s documentation for information on how to setup a certificate store on your machine.
Uncaught InvalidArgumentException: missing the required redirect URI
This error occurs when the credentials.json file used contains a client ID of the wrong type. This code requires an OAuth client ID of type Other, which will be created for you when using the button in Step 1. If creating your own client ID please ensure you select the correct type.
This app isn’t verified
If the OAuth consent screen displays the warning «This app isn’t verified,» your app is requesting scopes that provide access to sensitive user data. If your application uses sensitive scopes, your your app must go through the verification process to remove that warning and other limitations. During the development phase you can continue past this warning by clicking Advanced > Go to
Further reading
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Подключение node-приложения к Google Calendar API
Как-то неожиданно для меня подключение своего nodejs-приложения к Google Calendar API оказалось довольно нетривиальной задачей. Несмотря на подробное описание вариантов подключения на русском языке пришлось продираться через лес различных настроек и конфигураций. В статье подробно изложены шаги, которые приходится совершить, чтобы интеграция завершилась успехом.
Создание календаря
Для начала нужно создать календарь, в который будем публиковать события. Идём в Google Calendar и нажимаем на кнопку «+» рядом с «Другие календари«, затем выбираем пункт «Создать календарь«:
заполняем форму и опять жмём «Создать календарь«, но уже синюю кнопку:
Гугл довольно долго шуршит мозгами, после чего радостно сообщает, что новый календарь готов. Доступ к настройкам нового календаря:
В настройках нас прежде всего интересует пункт «Интеграция календаря«:
Этот значение наше nodejs-приложение будет использовать при подключении к API.
Регистрация приложения в Google
Управление приложениями находится в «Консоли API».
Теперь нужно дать доступ этому проекту к соответствующим API Google’а:
Так как интерфейсов Google наплодил свыше 3 сотен, используем фильтр для поиска нужных:
Фильтрация по ключу «calend» оставляет всего два вариант, один из которых нам и нужен:
Заходим в «Google Calendar API» и включаем его для использования в нашем проекте:
После чего проваливаемся в dashboard использования этого API в нашем проекте (https://console.developers.google.com/apis/api/calendar-json.googleapis.com/overview?project=habr-demo-293107&supportedpurview=project), где нам сообщают, что для использования API мы должны создать учётные данные:
Жмём «СОЗДАТЬ УЧЁТНЫЕ ДАННЫЕ» и заполняем анкету, определяющую, какой тип учётных данных нам нужен для доступа к API:
вся анкета не влезла в один скрин, вот остаток:
По результатам анкетирования Google предлагает создать закрытый ключ в формате JSON, при помощи которого наше приложение будет подключаться к Google Calendar API:
Самую большую трудность для меня создал пункт «Роль«. Похоже, что ролей у Google’а даже больше, чем API, к которым можно подключаться:
В общем, если выбрать «Проект / Владелец«, то обещают предоставить полный доступ ко всем ресурсам. Жмём на кнопку «Продолжить» и получаем JSON-файл в каталог «Downloads» на своём компрьютере:
Содержимое JSON-файла примерно такое (ключ я вырезал):
В консоли API у приложения «Habr Demo» появляется новый сервис с email’ом «nodejs-app@habr-demo-293107.iam.gserviceaccount.com«:
Для подключения к API из nodejs-приложения Google предлагает библиотеку googleapis и обзор её использования. В обзоре применяется OAuth2-аутентификация и получение из календаря списка событий, а нам нужна аутентификация по ключу в соответствующих scope’ах и добавление события в календарь. Поэтому код получается примерно такой:
Запускаем код на выполнение и получаем ответ от Calendar API:
Настройка доступа сервиса к календарю
Заходим в наш календарь, созданный ранее, и в настройках жмём «Доступ для отдельных пользователей«, затем «Добавить пользователей» и вводим email-адрес нашего сервиса, который будет создавать события в нашем календаре:
После предоставления сервису доступа к календарю нужно настроить права:
Выбираем «Внесение изменений и предоставление доступа«, иначе будем иметь ошибку «You need to have writer access to this calendar.» при обращении к API:
Запускаем наш скрипт на выполнение ещё раз и фиксируем результат в календаре:
В коде я задавал время старта события в 16:00:
a по факту событие запланировано на 17:00, что вполне соответствует духу IT:
В программировании существует лишь два характерных затруднения: инвалидация кеша, наименование сущностей и ошибка на единицу
Резюме
Вот и всё, квест пройден. Хэппи, как говорится, кодинг.