Google Calendar API - create event PHP - php

I want to insert a new event into Google Calendar by using the Google Calendar API.
And the problem is that I want to set the event status to "free" or "busy" based on the input datetime data.
How to change the event status to "Free"? When I create a new event, it will automatically set to "Busy". I couldn't figure it out on how to set to "Free" or "Busy".
How I insert a new event by using Google Calendar API.
$googleClient = new GoogleClient();
$slotCalendarService = GoogleClientCalendar::getSlotCalendar($googleClient->getClient());
$googleEvent = new Event();
$googleEventStart = new EventDateTime();
$googleEventStart->setTimeZone($attrs['timezone']);
$googleEventStart->setDateTime("2021-12-02T10:00:00");
$googleEvent->setStart($googleEventStart);
$googleEventEnd = new EventDateTime();
$googleEventEnd->setTimeZone($attrs['timezone']);
$googleEventEnd->setDateTime("2021-12-02T10:50:00");
$googleEvent->setEnd($googleEventEnd);
$googleEventAttendee = new EventAttendee();
$googleEventAttendee->email = empty($attrs['attendee']) ? '' : $attrs['attendee'];
$googleEvent->description = $description;
$googleEvent->summary = $remark;
$googleEvent->setAttendees($googleEventAttendee);
$slotCalendarService->getCalendarService()->events->insert($slotCalendarService->getCurrentCalendarId(), $googleEvent);
Base on the the code above, there is no param to set the event status to "free" or "busy".
I also follow the document FreeBusy Google Calendar API and it does not have information on how to set event status to "free" or "busy".

When you want to set to "free", please modify as follows.
From:
$googleEvent->setAttendees($googleEventAttendee);
$slotCalendarService->getCalendarService()->events->insert($slotCalendarService->getCurrentCalendarId(), $googleEvent);
To:
$googleEvent->setAttendees($googleEventAttendee);
$googleEvent->transparency = "transparent"; // Added
$slotCalendarService->getCalendarService()->events->insert($slotCalendarService->getCurrentCalendarId(), $googleEvent);
When you don't use $googleEvent->transparency = "transparent"; or you use $googleEvent->transparency = "opaque";, it's "busy".
Reference:
Events: insert

Related

How to remove DataValidationRule via Google Sheets API

Currently I'm using the Google Sheets API via their PHP library to build a dynamic spreadsheet. I've set validation rules on a spreadsheet, specifically to create a dropdown list of states to select.
I have since updated the spreadsheet to have the state dropdown list in a different column. Upon doing this however, it seems the DataValidationRule that was set for the previous column, is still there.
I've attempted to create a method to REMOVE all validation from my sheet before re-applying any validation I want, but it does not seem to be working.
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/other#conditiontype
When setting a Condition Type, I'd like to revert the validation back to CONDITION_TYPE_UNSPECIFIED, however the API simply returns an error if I do so. I've attempted to use others such as ONE_OF_LIST, but then every cell errors saying:
Invalid: Input must be an item on specified list
Which makes sense, considering there is no list being generated (nor do I want one).
The rest of the columns can be any sort of combination of numbers/dates/text so I'd like to simply remove all validation before applying validation again.
Here's my current clearValidation code:
public function clearSpreadsheetValidations($spreadsheetId) {
$client = $this->getClient();
$service = new Google_Service_Sheets($client);
$conditions = new Google_Service_Sheets_BooleanCondition();
$conditions->setType('CONDITION_TYPE_UNSPECIFIED');
$conditions->setValues(null);
$setRule= new Google_Service_Sheets_DataValidationRule();
$setRule->setCondition($conditions);
$setRule->setInputMessage(null);
$setRule->setShowCustomUi(false);
$valReq = new Google_Service_Sheets_SetDataValidationRequest();
$valReq->setRule($setRule);
$sheetReq = new Google_Service_Sheets_Request();
$sheetReq->setSetDataValidation($valReq);
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$requestBody->setRequests($sheetReq);
$service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
}
How can I call the sheets API to remove all previously set DataValidationRules in a spreadsheet?
Thanks!
Okay, as noted here
https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/request
SetDataValidationRequest
Sets a data validation rule to every cell in the range. To clear
validation in a range, call this with no rule specified.
So all I had to do, was simply not declare a range, or set a rule, and ran this method on the existing spreadsheet to clear all existing validations
public function clearSpreadsheetValidations($spreadsheetId) {
$client = $this->getSheetsClient();
$service = new Google_Service_Sheets($client);
$valReq = new Google_Service_Sheets_SetDataValidationRequest();
$sheetReq = new Google_Service_Sheets_Request();
$sheetReq->setSetDataValidation($valReq);
$requestBody = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$requestBody->setRequests($sheetReq);
$service->spreadsheets->batchUpdate($spreadsheetId, $requestBody);
}
For java this code worked in my case.
public BatchUpdateSpreadsheetResponse removeAllDataValidation(String spreadsheetId, Sheets service)
throws IOException {
// [START sheets_conditional_formatting]
List<Request> requests = Arrays.asList(new Request().setSetDataValidation(
new SetDataValidationRequest()));
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse result = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
System.out.printf("%d cells updated.", result.getReplies().size());
// [END sheets_conditional_formatting]
return result;
}

google people api: assign/create contact group

I cannot figure out how to create a new contact group and assign it to the contact using google people api in php. An error
"person.memberships is a read only field."
occurs at $person->setMemberships():
$contactGroup=new Google_Service_PeopleService_ContactGroup();
//$contactGroup->setGroupType('USER_CONTACT_GROUP');
$contactGroup->setName('Some group');
$contactGroup->create();
$cgm=new Google_Service_PeopleService_ContactGroupMembership();
$cgm->setContactGroupId('groupID');
$membership=new Google_Service_PeopleService_Membership();
$membership->setContactGroupMembership($cgm);
$person=new Google_Service_PeopleService_Person();
$groupMemberships=array(($membership));
$person->setMemberships(array($groupMemberships));//error happens here
Anyone could help with a proper example of creating contact group and assigning it to the contact?
The following code assumes you have instantiated a Google_Client object, and have already created a person and know their ID.
Resource ID example,
$person_id = 'people/1234567890abcde';
Create a contact group,
$peopleService = new Google_Service_PeopleService($client);
$newContactGroup = new Google_Service_PeopleService_ContactGroup;
$newContactGroup->setName('New contact group');
$createContactGroupRequest = new Google_Service_PeopleService_CreateContactGroupRequest;
$createContactGroupRequest->setContactGroup($newContactGroup);
$contactGroup = $peopleService->contactGroups->create($createContactGroupRequest);
$contact_group_id = $contactGroup->getResourceName();
Add a person to contact group,
$peopleService = new Google_Service_PeopleService($googleClient);
$modifyContactGroupMembersRequest = new Google_Service_PeopleService_ModifyContactGroupMembersRequest;
$modifyContactGroupMembersRequest->setResourceNamesToAdd($person_id);
$peopleService->contactGroups_members->modify($contact_group_id, $modifyContactGroupMembersRequest);
You can't set members of the contact group in the creation call. You need to create the contact group in one call, then in a second call add it using members.modify api call.

API Google Calendar, Hangout is not created

We have a PHP application and when we create an event in Google Calendar using de API, this event is generated without Hangout Link, but if we create the event manually, the event is created with the Hangout Link. The option to create automatically hangouts when we create an event is checked.
The code is:
$event = new Google_Service_Calendar_Event();
$event->setSummary($summary);
$event->setLocation('hangout');
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($startDate->format(\DateTime::ISO8601));
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($endDate->format(\DateTime::ISO8601));
$event->setEnd($end);
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail($this->masterAccount);
$attendees= [];
$attendees[] = $attendee1;
foreach($company->getUsers()->toArray() as $user){
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setEmail($user->getEmail());
$attendees[] = $attendee1;
}
$event->attendees = $attendees;
$createdEvent = $this->google_calendar_service->events->insert($company->getCalendar()->getCalendarId(), $event);
If we use the form https://developers.google.com/google-apps/calendar/v3/reference/events/insert#try-it to create de Event, the hangout link is created without problems.
Any solutions?
Thanks :)
I know this topic is a bit old, but there are many people still struggling with making Calendar API work. After countless forums visited, hours of reading documentation and hitting my head against the wall I finally figured out, the key element is to set requestId.
In the time i've implemented this, this parameter wasn't mandatory and i skipped it.
Thats being said, my request looks like this:
$event = new Google_Service_Calendar_Event(); //creating empty event
$event->setSummary("Staff meeting"); //title
$event->setLocation("Room 101"); //location
$event->setDescription("We will talk about salary raise!"); //description
$event->setColorId(9); //make it shine by setting color
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($startDate->format(DateTime::ISO8601));
$start->setTimeZone('Europe/Warsaw');
$event->setStart($start); //set start
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($endDate->format(DateTime::ISO8601));
$end->setTimeZone('Europe/Warsaw');
$event->setEnd($end); //set end
$event->setGuestsCanSeeOtherGuests(false); //I dont want others to see who's invited
$event->setGuestsCanModify(false); //I dont want others to modify event
$event->setGuestsCanInviteOthers(false); //I dont want others to invite
$event->setAnyoneCanAddSelf(false); //I allow only people invited by me, not some strangers walking by
//this part should be executed in loop, for every guest
$attendee = new Google_Service_Calendar_EventAttendee();
$attendee->setEmail("staffmeber1#mywebsite.com");
$attendee->setResponseStatus('accepted');
$attendees[] = $attendee;
//When the list is completed, set guests in event
$event->setAttendees($attendees);
//The most important part about creating hangout
$conferenceData = new Google_Service_Calendar_ConferenceData(); //defining we have conference
$req = new Google_Service_Calendar_CreateConferenceRequest(); //requesting google to create video meeting
$req->setRequestId("req_".time()); //some random string/number changed every call. according to docs subsequent calls with the same request id are ignored
$conferenceData->setCreateRequest($req); //set request for videoconference in conference data
$event->setConferenceData($conferenceData); //set conference data in out event
$creator = new Google_Service_Calendar_EventCreator();
$creator->setDisplayName("Big boss");
$creator->setEmail('boss#mywebsite.com');
$event->setCreator($creator);
$event->setStatus('confirmed'); //lets say everyone is attending :D
$result = $this->calendarClient->events->insert($this->calendarObject->getId(), $event, ['conferenceDataVersion' => 1, 'sendUpdates' => "none"]); //dont forget about conferenceDataVersion or every conference data will be ignored
Working with Python here also faced issue, of events not being created with Hangouts. It seems settings can not be changed from program, but as SGC pointed out, I just changed google calendar settings from UI to add hangouts on every event created.

How to delete existing calender with same name from list and create and insert events as a fresh calender in google calender apiv3 with php

I am trying to integrate google calender APIv3 using php in my site.The idea is each user have a set of events as per his subscribed package on site on different dates.If the user select a new package later all events from previously subscribed package will overwrite with new one.
For me everything works fine except the following.
1)when a user reached gmail calender rendering page ,for the first time successfully created a calender (eg:My first work as name ) on left menu of My calender list and on that all events are inserted (for eg:events on march1,march5,march8 with different titles)
2)When the user click the link from site to render the same calender for the second time it will again created on left menu My calender list (eg:My first work and My first work two calenders with same name ).All events inserted on previous calender insertion will be there and the second time of insertion to same dates also will be there.(For eg: duplication of events on same dates march1,march5,march8 )
What i want is each time when a user click from site to render the calender page the calender should be created as a new one (this is working) and also the calender with same name on left menu "My calender list" should be deleted.So that there may not be duplicate data/event on same date.
any body please help me to find a solution?
following is my code snippet
$service = new Google_Service_Calendar($client);
$calendar = new Google_Service_Calendar_Calendar();
$calendar->setSummary('My first work');
$calendar->setTimeZone( 'Asia/Kolkata');
$createdCalendar = $service->calendars->insert($calendar);
$calendar = $service->calendars->get($createdCalendar->getId());
$calendarList = $service->calendarList->listCalendarList();
foreach($events_data_arr as $key=>$events_data_row)
{
$event = new Google_Service_Calendar_Event();
$event->setSummary($events_data_row['title']);
$event->setLocation('India');
$event->setDescription($events_data_row['description']);
$start = new Google_Service_Calendar_EventDateTime();
$start->setTimeZone('Asia/Kolkata');
$start->setDateTime($events_data_row['start_date'].'T10:00:00.000-07:00');
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setTimeZone( 'Asia/Kolkata');
$end->setDateTime($events_data_row['end_date'].'T10:00:00.000-07:01');
$event->setEnd($end);
$createdEvent = $service->events->insert($createdCalendar->getId(), $event);
}
Following code helped me.
$calendarList = $service->calendarList->listCalendarList();
foreach ($calendarList->getItems() as $calendarListEntry) {
$delid = $calendarListEntry->getId();
$calname = $calendarListEntry->getSummary();
if(strtolower(trim($calname)) == "mycalendername")
{
$service->calendarList->delete($delid);
$service->calendars->delete($delid);
//echo "ID= ".$delid ."<br/>";
}
}
The idea is to take all calenders from calenderlist using
$calendarList = $service->calendarList->listCalendarList();
Afetr that take calender id of those calender which have a name equal to our calender name and delete that calender.Only after this step start creating and inserting to our calender "mycalendername".This will prevent duplicate creation of same calender name to user's main calender list and each time taking our code will create a fresh calender with fresh data

Google Calendar API v3 quickAdd fail

First, I can add the event from Google API web page
https://developers.google.com/google-apps/calendar/v3/reference/events/quickAdd#try-it successfully by input "calendarId" and "text" parameters
But I am failed to use "quickAdd" API to add event in Google calendar by using PHP.
require_once "google-api-php-client/src/Google/Client.php";
require_once "google-api-php-client/src/Google/Service/Calendar.php";
// Service Account info
$calName = 'dcm2p5gkf3ge1r7k78f0ko28tc#group.calendar.google.com';
$client_id = '759399732845-j93sis8dktkdj00l3b8mn7gjs3ncf6b9.apps.googleusercontent.com';
$service_account_name = '759399732845-j93sis8dktkdj00l3b8mn7gjs3ncf6b9#developer.gserviceaccount.com';
$key_file_location = 'SMSProject-f14380ee82e4.p12';
$client = new Google_Client();
$client->setApplicationName("SMSProject");
$service = new Google_Service_Calendar($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/calendar'), $key);
$client->setAssertionCredentials($cred);
$createdEvent = $service->events->quickAdd('primary', 'Appointment at Somewhere on January 23rd 10am-10:25am');
echo $createdEvent->getId();
Event ID "g69tq9k7s38rfgit1mpnit9bpk" can be echo in the browser but no event is shown in the calendar
If I change
$createdEvent = $service->events->quickAdd('primary', 'Appointment at Somewhere on January 23rd 10am-10:25am');
to
$createdEvent = $service->events->quickAdd($calName, 'Appointment at Somewhere on January 23rd 10am-10:25am');
Event ID cannot be generated and show below error message
Error calling POST https://www.googleapis.com/calendar/v3/calendars/dcm2p5gkf3ge1r7k78f0ko28tc%40group.calendar.google.com/events/quickAdd: (404) Not Found
I need to use "quickAdd" instead of "insert" API. How to solve the problem? Thanks!
I was having the same issue, but then I discovered that it was, in fact, creating the events in the calendar for the Service Account xxxxxxx#developer.gserviceaccount.com instead of my personal calendar.
If you want it to create the events in your personal calendar that you use, go into the settings for your personal calendar and share it with your Service Account xxxxxxx#developer.gserviceaccount.com
then you should be able to use...
$createdEvent = $service->events->quickAdd($calName, 'Appointment at Somewhere on January 23rd 10am-10:25am');
...instead of 'primary'

Categories