Reputation: 21
I'm trying to get a connexion between a google Calendar account and the google calendar API to update a MySQL database based on the events contained by the google calendar. It seems that my client is set up, and now I have to get the CalendarList, but I'm having trouble here.
I took inspiration on what have been done in the quickstart.php and what is explained in the google documentation to try some tests.
The problem is that all my requests return an empty result when I use the method getItems();
function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP synchroniser');
$client->setScopes(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAuthConfig('Path/To/My/AccountService/File.json');
$client->setAccessType('online');
$client->setPrompt('MyCalendarWithMyData');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
/*
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
//I don't know what to put here.
}
}
*/
return $client;
}
$client = getClient(); // based on quickstart.php
$service = new Google_Service_Calendar($client);// from the sample on documentation
$calendarList = $service->calendarList->listCalendarList();
$calendars=$calendarList->getItems();
var_dump($calendars);
My goal is when I got the calendar list to get each events relative to each calendar in the calendar list to update my database. Thanks G.G
Upvotes: 2
Views: 1763
Reputation: 2345
I also had the same issue and followed the following steps to resolve it.
Go to your calender setting and share your calender with the service account. https://calendar.google.com/calendar/u/0/r/settings
Also, pls note down the calenderId from your account on the same page.
Once you are done doing this, it will start working. I am also pasting my python code snippet for the reference.
from google.oauth2 import service_account
from googleapiclient.discovery import build
from datetime import datetime, time, timedelta
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
SERVICE_ACCOUNT_FILE = 'personal-390418-9fb901964171.json'
creds = None
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('calendar', 'v3', credentials=creds)
start_date = datetime(2023, 6, 1).isoformat() + 'Z' # 'Z' indicates UTC time
end_date = datetime(2023, 6, 22).replace(hour=23, minute=59, second=59).isoformat() + 'Z'
events_result = service.events().list(calendarId='$CALENDER_ID', timeMin=start_date,
timeMax=end_date,
singleEvents=True,
orderBy='startTime').execute()
print(events_result)
events = events_result.get('items', [])
if not events:
print('No events found for this day.')
else:
print(f'Events for {start_date}:')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(f'{start} - {event["summary"]}')
Just replace $CALENDER_ID in above code snippet and replace the variable SERVICE_ACCOUNT_FILE value with your service account JSON.
Upvotes: 1
Reputation: 117281
What you need to remember is that a Service account is not you. A service account is a dummy user. This user has its own google calendar account, drive account and probably a few more.
If you do a
$calendar = $service->calendars->get('primary');
echo $calendar->getSummary();
You will see that in fact your service account does have a calendar. What it doesnt have is anything by default in its calendar list.
If you want it to have access to your personal Google calendar then you will need to go to the google calendar website and share the calendar with the service accounts email address. then it should be able to do the following make sure you note the calendar id for the calendar you shared with it while you are in the settings.
$calendar = $service->calendars->get('calendarid');
echo $calendar->getSummary();
If you really want it in calendar list you can add it.
$calendarListEntry = new Google_Service_Calendar_CalendarListEntry();
$calendarListEntry->setId("calendarId");
$createdCalendarListEntry = $service->calendarList->insert($calendarListEntry);
echo $createdCalendarListEntry->getSummary();
As i have mentioned service accounts need to be preauthorized. You need to go to the Google Calendar website and under settings for the calendar you want it to be able to access you need to share the calendar with it as shown
Upvotes: 3