I'm trying to enable and sync Google Calendar API in my project.
Summary:
In my current project i've multiple users and each user has a dashboard with fullcalendar.js. I've a table named events and it has these columns
Events
name
description
user_id
full_day
start
end
Users can create calendar events through a modal which i save in the database.
I want to enable the ability for the users to import their Google Calendar Events and/or 2-way sync events.
So far i've done the following:
1) Enabled calendar api, created OAuth Tokens for webapp (client id & secret), filled in redirect and created a google consent screen.
2) composer require google/apiclient in my project.
3) Setup Socialite Google drive
4) Created a controller named GoogleController and created routes for it.
- OAuthGoogle method (GoogleController) with the following code:
public function OAuthGoogle()
{
$scopes = [
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'openid',
'https://www.googleapis.com/auth/calendar'
];
return Socialite::driver('google')
->scopes($scopes)
->with(["access_type" => "offline", "prompt" => "consent select_account"])
->redirect();
}
After that on the redirect Method i've the following code where i store the tokens in user DB:
public function OAuthGoogleCallback()
{
$user = Socialite::with('google')->user();
$loggedUser = getAuthUser();
$loggedUser->google_access_token = Crypt::encryptString($user->token);
$loggedUser->google_refresh_token = Crypt::encryptString($user->refreshToken);
$loggedUser->save();
}
After that i'm trying to fetch calendar events and list them:
public function list()
{
$user = getAuthUser();
$token = Crypt::decryptString($user->google_access_token);
$client = new Google_Client();
$client->setAccessToken($token);
$service = new Calendar($client);
// $calendarId = 'primary';
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$events = $service->events->listEvents('primary');
while (true) {
foreach ($events->getItems() as $event) {
echo $event->getSummary();
}
$pageToken = $events->getNextPageToken();
if ($pageToken) {
$optParams = array('pageToken' => $pageToken);
$events = $service->events->listEvents('primary', $optParams);
} else {
break;
}
}
}
Unfortunately I get the following error when I try it:
Call to a member function listEvents() on null
thanks in advance for your help!