View meet link to each event created in a google calendar - php

In a laravel 5.8 project user can create new events using my app and then save those events to his google calendar via OAUTH 2 so that he can view, edit or even delete them. new conference data will be added automatically with each created event.
I want to view google meet link with each event created so that guests can click this link to attend the conference
I started by adding event data and creating new conference data and adding its entry point and using Google_Service_Calendar_ConferenceSolutionKey class to determine its type which is "hangoutsMeet" and finally I added conference data to the event
Here is the function I am using to create new events:
public function doCreateEvent(Event $evt, Request $request)
{
$this->validate($request, [
'title' => 'required',
'calendar_id' => 'required',
'datetime_start' => 'required|date',
'datetime_end' => 'required|date'
]);
$title = $request->input('title');
$calendar_id = $request->input('calendar_id');
$start = $request->input('datetime_start');
$end = $request->input('datetime_end');
$start_datetime = Carbon::createFromFormat('Y/m/d H:i', $start);
$end_datetime = Carbon::createFromFormat('Y/m/d H:i', $end);
$cal = new \Google_Service_Calendar($this->client);
$event = new \Google_Service_Calendar_Event();
$event->setSummary($title);
$start = new \Google_Service_Calendar_EventDateTime();
$start->setDateTime($start_datetime->toAtomString());
$event->setStart($start);
$end = new \Google_Service_Calendar_EventDateTime();
$end->setDateTime($end_datetime->toAtomString());
$event->setEnd($end);
// Create new conference
$conference = new \Google_Service_Calendar_ConferenceData();
$entryPoint = new \Google_Service_Calendar_EntryPoint();
$entryPoint->setAccessCode('wx12z3s');
$entryPoint->setEntryPointType('video');
$entryPoint->setLabel('meet.google.com/wx12z3s');
$entryPoint->setMeetingCode('wx12z3s');
$entryPoint->setPasscode('wx12z3s');
$entryPoint->setPassword('wx12z3s');
$entryPoint->setPin('wx12z3s');
$entryPoint->setUri('https://meet.google.com/wx12z3s');
$conference->setEntryPoints($entryPoint);
$conferenceSolution = new \Google_Service_Calendar_ConferenceSolution();
$conferenceSolution->setIconUri(null);
$conferenceSolution->setKey(new \Google_Service_Calendar_ConferenceSolutionKey());
$conference->setConferenceSolution($conferenceSolution);
$conferenceRequest = new \Google_Service_Calendar_CreateConferenceRequest();
$conferenceRequest->setRequestId($request->_token);
$conferenceSolutionKey = new \Google_Service_Calendar_ConferenceSolutionKey();
$conferenceSolutionKey->setType("hangoutsMeet");
$conferenceRequest->setConferenceSolutionKey($conferenceSolutionKey);
$conferenceRequest->setStatus(new \Google_Service_Calendar_ConferenceRequestStatus());
$conference->setCreateRequest($conferenceRequest);
$event->setConferenceData($conference);
//attendee
if ($request->has('attendee_name')) {
$attendees = [];
$attendee_names = $request->input('attendee_name');
$attendee_emails = $request->input('attendee_email');
foreach ($attendee_names as $index => $attendee_name) {
$attendee_email = $attendee_emails[$index];
if (!empty($attendee_name) && !empty($attendee_email)) {
$attendee = new \Google_Service_Calendar_EventAttendee();
$attendee->setEmail($attendee_email);
$attendee->setDisplayName($attendee_name);
$attendees[] = $attendee;
}
}
$event->attendees = $attendees;
}
$created_event = $cal->events->insert($calendar_id, $event);
$evt->title = $title;
$evt->calendar_id = $calendar_id;
$evt->event_id = $created_event->id;
$evt->datetime_start = $start_datetime->toDateTimeString();
$evt->datetime_end = $end_datetime->toDateTimeString();
$evt->save();
return redirect('/event/create')
->with('message', [
'type' => 'success',
'text' => 'Event was created!'
]);
}
Event created successfully but no conference data showed on user's google calendar event card so he can not access the new created conference meet link
The question is how can I know if conference data is added to the event successfully although hangout meet link did not show on the event card?

This combination of the answers above worked for me:
$event = new \Google_Service_Calendar_Event(array(
'summary' => 'Appointment',
'location' => 'Earth',
'description' => 'Hello world',
'start' => array(
'dateTime' => Carbon::now()->format('c'),
'timeZone' => 'Europe/Zurich',
),
'end' => array(
'dateTime' => Carbon::now()->addMinutes(15)->format('c'),
'timeZone' => 'Europe/Zurich',
)
));
$calendarId = 'primary';
$event = $service->events->insert($calendarId, $event);
printf('Event created: %s', $event->htmlLink);
$conference = new \Google_Service_Calendar_ConferenceData();
$conferenceRequest = new \Google_Service_Calendar_CreateConferenceRequest();
$conferenceRequest->setRequestId('randomString123');
$conference->setCreateRequest($conferenceRequest);
$event->setConferenceData($conference);
$event = $service->events->patch($calendarId, $event->id, $event, ['conferenceDataVersion' => 1]);
printf('<br>Conference created: %s', $event->hangoutLink);

There's no information regarding how to show the meet link in calendar event card from the documentation. You will need to manually insert/input from the comment section the url of Hangout meeting.
I would like to suggest to use the Events formats from Hangouts Chat API.

$created_event = $cal->events->insert(
$calendar_id,
$event,
['conferenceDataVersion' => 1]
);
Need to set the conferenceDataVersion => 1 as one in the optional parameter set.

Related

Add event on user shared calendar

I'm using Garethp/php-ews package to manage Exchange data.
I'm able to read Calendar that other user shared with me, but unless they gave me write access on their Calendar (Under web client, I can add event), I'm not able to add events trough php.
I think I have to use
$calendar = $api->getCalendar();
$userCalendar = $calendar->pickCalendar($displayName);
If I'm right, how to get his $displayName ?
Thanks
I think I found a solution:
$this->api = API::withUsernameAndPassword($server, $your_username, $your_password
$this->api->setPrimarySmtpEmailAddress('user_shared_calendar#test.com');
$folder = $this->api->getFolderByDistinguishedId('calendar');
$calendar = $this->api->getCalendar();
$calendar->setFolderId($folder->getFolderId());
$start = new \DateTime('now');
$start->setTimezone(new \DateTimeZone('Europe/Paris'));
$end = new \DateTime('now');
$end->add(new \DateInterval('PT1H'));
$calendar->createCalendarItems([
'Subject' => 'This is made by PHP',
'Body' => [
'BodyType' => API\Enumeration\BodyTypeType::HTML,
'_value' => 'This is <b>the</b> HTML body',
],
'Start' => $start->format('c'),
'End' => $end->format('c'),
]);
This script add event on a shared calendar.

What is the proper format of request for querying a report?

Good afternoon everyone! I need to get the estimatedMinutesWatched parameter from YouTube's Analytics API. I found some examples on the internet, for example this one, and they all used the method:
$api = $analytics->reports->query($id, $start_date, $end_date, $metric, $optparams);
but now you need to pass a single array to the method, which is why I get errors.
I can't figure out which array should be passed to query(). This is my code:
$client = new Google_Client();
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
// authenticate code from Google OAuth Flow
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token);
$start_date = '2000-01-01';
$end_date = '2021-01-01';
$metrics = 'estimatedMinutesWatched';
$channel_url='https://www.youtube.com/channel/UCqRTXU9O7v3KeJcQuxmEhaA';
$ids = 'channel==' . $channel_url . '';
$analytics = new Google_Service_YouTubeAnalytics($client);
$optparams = array(
'dimensions' => '7DayTotals',
'sort' => 'day',
'ids' => $ids,
'start_date' => $start_date,
'end_date' => $end_date,
'metric'=>$metrics
);
$api = $analytics->reports->query($optparams);
var_dump($api);
die();
The exeption I've got is:
(query) unknown parameter: 'start_date'
I understand that I need to rewrite the query, but really don't know how to do that.
According to the official doc of YouTube Analytics' Reports Query, the name of the date parameters are: startDate and endDate (notice the camel case).
Thus your API call should look like:
$analytics = new Google_Service_YouTubeAnalytics($client);
$optparams = array(
'dimensions' => '7DayTotals',
'sort' => 'day',
'ids' => $ids,
'startDate' => $start_date,
'endDate' => $end_date,
'metrics' => $metrics
);
$api = $analytics->reports->query($optparams);
I also corrected the metric parameter to metrics.
Do note also that the ids parameter should contain a specification of form channel == CHANNEL_ID, but yours is channel == CHANNEL_URL. Just replace that with:
channel == UCqRTXU9O7v3KeJcQuxmEhaA or channel == MINE.
As per the official doc, it is presumed that UCqRTXU9O7v3KeJcQuxmEhaA is the ID of the channel corresponding to the user that authorized your app during the OAuth 2.0 authentication/authorization flow.

Google calendar using php does not show shared calendar list

I am using JSON key file authorization for getting calendars list so i can enter new calendar event.
The problem is that at specific google account i am getting calendar list and when following same instruction on different google account the list is empty.
This is the code:
require_once 'vendor//autoload.php';
$client = new Google_Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $credenential);
$client->useApplicationDefaultCredentials();
$client->setApplicationName("Quickstart");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');
$service = new Google_Service_Calendar($client);
$calendarList = $service->calendarList->listCalendarList();
$startDateTime = DateTime::createFromFormat("Y-m-d H:i:s", $start);
$endDateTime = DateTime::createFromFormat("Y-m-d H:i:s", $end);
$event = new Google_Service_Calendar_Event(array(
'summary' => $title_event,
'location' => $where_event,
'description' => $content_event,
'start' => array(
'dateTime' => rawurldecode($start)
),
'end' => array(
'dateTime' => rawurldecode($end)
)
));
foreach($calendarList as $item) {
if ( strcasecmp( $item['summary'], $google_email ) == 0 ){
$calendarId = $item['id'];
}
}
$event = $service->events->insert($calendarId, $event);

How to retrieve Google Calendar event ID after creating event in PHP

I have a PHP file that will create an event in my Google Calendar successfully from data Posted from my CRM, however, I can't find any documentation on how it can retreive the id of the event it just created and return a JSON data string.
Here is my current PHP file.
<?php
require_once __DIR__ . '/google-api-php-client/src/Google/autoload.php';
$summary = $_POST["summary"];
$location = $_POST["location"];
$description = $_POST["description"];
$startdatetime = $_POST["startdatetime"];
$enddatetime = $_POST["enddatetime"];
$client_email = 'xxxxxxxx#xxxxxxxx.iam.gserviceaccount.com';
$private_key = file_get_contents('xxxxxx.p12');
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = 'xxxxxxx#xxxxxxxxxxx.com';
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
);
$client = new Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$event = new Google_Service_Calendar_Event(array(
'summary' => $summary,
'location' => $location,
'description' => $description,
'start' => array(
'dateTime' => $startdatetime,
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => $enddatetime,
'timeZone' => 'America/Los_Angeles',
),
'reminders' => array(
'useDefault' => FALSE,
),
));
$service = new Google_Service_Calendar($client);
$calendarId = 'southbay#unlikelylegendsmedia.com';
$event = $service->events->insert($calendarId, $event);
If you know the corresponding calendarID, you may use Events: list.
By sending HTTP request with the calendarId parameter, you can retrieve eventId. Request like:
GET https://www.googleapis.com/calendar/v3/calendars/calendarId/events
If request is successful, this method may return a response body with either single one-off events and instances of recurring events.
Sample PHP code for this:
$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;
}
}

Google spreadsheet API v4 with PHP - how to insert empty row to beginning

I am confused about the new Google Sheets API v4.
My question is: how can I insert a row to the beginning of the spreadsheet?
I can't find any useful tutorial for the new Google Sheet API v4 or find viable documentation from Google specific to PHP.
I got this,
$requests = new Google_Service_Sheets_Request(array(
'insertDimension' => array(
'range' => array(
'sheetId' => 0,
'dimension' => "ROWS",
'startIndex' => 1,
'endIndex' => 2
)
)
));
$batchUpdateRequest = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest(array(
'requests' => $requests
));
$this->service->spreadsheets->batchUpdate($this->sheetID, $batchUpdateRequest);
where $this->service is instance of Google_Service_Sheets and $this->sheetID is your SheetID from google docs url
Here is how I did it:
//Insert blank new row between R1 and R2 (there is no R0)
$dr = new Google_Service_Sheets_DimensionRange();
$dr->setSheetId(0);//first sheet/tab of spreadsheet file
$dr->setDimension('ROWS');
$dr->setStartIndex(1);
$dr->setEndIndex(2);
$ins = new Google_Service_Sheets_InsertDimensionRequest();
$ins->setRange($dr);
$ins->setInheritFromBefore(false);
$ssr = new Google_Service_Sheets_Request();
$ssr->setInsertDimension($ins);
$busr = new Google_Service_Sheets_BatchUpdateSpreadsheetRequest();
$busr->setRequests([$ssr]);
$response = $sheetsService->spreadsheets->batchUpdate($spreadsheetId, $busr, []);

Categories