John Davidson

php - Unable to create events for different user in Google calendar

0 comments
Message:


Hi everyone.
I hope you all are doing well.


I know this question has been asked many times but non of the solutions provided there worked for me.


I am implementing google calendar API in custom PHP. I have followed the official documentation provided by Google. I have been able to create and get events for a specific user.


My original goal was to allow every user to get, create, update and delete Events on their own calendar.


Here's what I have been doing in the code.


This is calendarSetting.php file.


<?php
require __DIR__ . '/vendor/autoload.php';

function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Calendar API PHP Quickstart');
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('client_secret.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');


$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 {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));

// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);

// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
?>

This is createCalendar.php file


<?php

require __DIR__ . '/vendor/autoload.php';
include('calendarSetting.php');
session_start();
$appointment_id = $_SESSION['appointment_id'];
$patient_fname = $_SESSION['patient_fname'];
$patient_lname = $_SESSION['patient_lname'];
$patient_phone = $_SESSION['patient_phone'];
$schedule = $_SESSION['appointment_date'];
$start_date = $_SESSION['start'];
$end_date = $_SESSION['end'];

$client = getClient();
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event(array(
'summary' => $patient_fname . ' ' . $patient_lname,
'description' => $patient_fname . ' ' . ' ' . $patient_lname . ' ' . $patient_phone ,

'start' => array(
'dateTime' => $start_date.':00+05:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $end_date.':00+05:00',
'timeZone' => 'America/Los_Angeles',
),
'recurrence' => array(
'RRULE:FREQ=DAILY;COUNT=1'
),
'attendees' => array(
array('email' => '[email protected]')
)


));

$calendarId = '[email protected]';
$event = $service->events->insert($calendarId, $event);
printf('Event created');
header('location: Doctor');


?>

This is perfectly working for the user where $calendarId = '[email protected]';. but if I change the user it gives me an error.



Fatal error: Uncaught Google\Service\Exception: { "error": { "errors":
[ { "domain": "global", "reason": "notFound", "message": "Not Found" }
], "code": 404, "message": "Not Found" } } in
F:\xampp\htdocs\bupa1\vendor\google\apiclient\src\Http\REST.php:128
Stack trace: #0
F:\xampp\htdocs\bupa1\vendor\google\apiclient\src\Http\REST.php(103):
Google\Http\REST::decodeHttpResponse(Object(GuzzleHttp\Psr7\Response),
Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #1 [internal
function]: Google\Http\REST::doExecute(Object(GuzzleHttp\Client),
Object(GuzzleHttp\Psr7\Request), 'Google_Service_...') #2
F:\xampp\htdocs\bupa1\vendor\google\apiclient\src\Task\Runner.php(182):
call_user_func_array(Array, Array) #3
F:\xampp\htdocs\bupa1\vendor\google\apiclient\src\Http\REST.php(66):
Google\Task\Runner->run() #4
F:\xampp\htdocs\bupa1\vendor\google\apiclient\src\Client.php(898):
Google\Http\REST::execute(Object(GuzzleHttp\Client),
Object(GuzzleHttp\Psr7\Request), 'Google_Service_...', Array, NULL) #5
F:\x in
F:\xampp\htdocs\bupa1\vendor\google\apiclient\src\Http\REST.php on
line 128



I have been trying to figure out why is this happening. so far what I found is that each time when i send a request to google to create the event my access token in the calendarSetting.php file isn't refreshing.


Now I got stuck on how can I get the refresh token so that a new user could also create events.


If anybody could help to figure this out I'll be very grateful.


Thank you



My Answer:
php

require_once 'vendor/autoload.php';

$client = new Google_Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google_Service_Calendar::CALENDAR);

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_Calendar($client);

$event = new Google_Service_Calendar_Event(array(
'summary' => 'Test Event',
'description' => 'This is a test event',
'start' => array(
'dateTime' => '2022-01-01T10:00:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2022-01-01T12:00:00',
'timeZone' => 'America/Los_Angeles',
),
));

$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);

echo 'Event created: ' . $event->htmlLink;
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}


This code snippet is creating an event in the primary calendar of the authenticated user. If you want to create events for different users, you will need to modify the `$calendarId` variable to use the calendar ID of the specific user you want to create events for.

You can get the calendar ID of a user by listing all the calendars for the authenticated user and selecting the desired calendar ID.

Here's how you can list all calendars for the authenticated user:

php
$calendarList = $service->calendarList->listCalendarList();

foreach ($calendarList->getItems() as $calendarListEntry) {
echo $calendarListEntry->getId() . ' - ' . $calendarListEntry->getSummary() . '
';
}


Once you have the calendar ID of the user you want to create events for, you can use that ID in the `$calendarId` variable in the event creation code.

I hope this helps! Let me know if you have any further questions.

Rate this post

5 of 5 based on 4304 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us