Add event on user shared calendar - php

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.

Related

Zoom Api - I can't update a meeting

I am trying to update a meeting using Zoom API but I can't get it to work. I'm trying to do a PATCH request using eleague oauth2 client like this:
require '../vendor/autoload.php';
require_once '../config.php';
$id = $_POST['id'];
$topic = $_POST['topic'];
$type = $_POST['type'];
$start_time = $_POST['start_time'];
$duration = $_POST['duration'];
$agenda = $_POST['agenda'];
$params = array(
'topic' => $topic,
'type' => $type,
'start_time' => $start_time,
'duration' => $duration,
'agenda' => $agenda,
'password' => '123456'
);
$provider = new \League\OAuth2\Client\Provider\GenericProvider([
'clientId' => CONEXAO_API['clientId'],
'clientSecret' => CONEXAO_API['clientSecret'],
'redirectUri' => CONEXAO_API['redirect_url'],
'urlAuthorize' => 'https://zoom.us/oauth/authorize',
'urlAccessToken' => 'https://zoom.us/oauth/token',
'urlResourceOwnerDetails' => 'https://api.zoom.us/v2/users/me'
]);
$options['body'] = json_encode( $params );
$options['headers']['Content-Type'] = 'application/json';
$options['headers']['Accept'] = 'application/json';
$request = $provider->getAuthenticatedRequest( 'PATCH',
'https://api.zoom.us/v2/meetings/'.$id,
unserialize($_SESSION['token']),
$options
);
$retorno = $provider->getParsedResponse($request);
var_dump($retorno);
I'm getting an empty response, and I'm not sure what is missing. Can anyone help me?
basically the response given by the api is blank or just meeting updated which isn't in json format. So in case you want to check whether its working go to zoom meeting panel and open the meeting which you are updating using api and run the api and check the meeting is updated in zoom meeting panel.
The problem is that the method getParsedResponse for some reason is not returning any message. But the script is working, it's updating the meeting the way it supposed to.
If I get the response using the method getResponse I can see the statusCode 204, which means that everything went ok.

View meet link to each event created in a google calendar

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.

Google Calendar API - Forbidden - Error with Service Account

I try to use the Google Calendar API by php running server side.
I created a service account and use its credentials (via the json file). I am NOT using G Suite.
Now I am able to list events of my calendar but I get a Forbidden - Error, when I try to create a new event.
I shared my calendar with the service account's email address and gave it admin rights for the calendar. I don't know what I am doing wrong! I just can't get it working. I am also using the scope Google_Service_Calendar::CALENDAR.
The exception: 403 - Forbidden
I have no idea how to debug this problem and how to proceed further.
Can you help me?
Edit: here is my calling code:
putenv('GOOGLE_APPLICATION_CREDENTIALS=../google-service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes([Google_Service_Calendar::CALENDAR]);
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$service = new Google_Service_Calendar($client);
$event = new Google_Service_Calendar_Event([
'summary' => $name,
'location' => $location,
'description' => $desc,
'start' => [
'dateTime' => $start,
'timeZone' => $timezone,
],
'endTimeUnspecified' => true,
]);
$calendar = $service->calendars->get($calendarId);
$settings = $service->settings->listSettings();
$list = $service->acl->listAcl($calendarId);
$event = $service->events->insert($calendarId, $event);
The first three service calls ($calender = ..., $settings = ... and $list = ...) work fine and in the acl I can also see that the email address of my service account has all rights (role: owner). But the last line $event = ... gives the forbidden error...
'endTimeUnspecified' => true,
is causing your problem (its googles fault, but you cant tell them that)
if you change to
'end' => [
'dateTime' => $start2,
'timeZone' => $timezone,
],
it will work (i know it is not what you want and maybe you can figure out a way to adjust $start2 to give you what you want as an end time but the endTimeUnspecified is what is causing it to say 403 forbidden

Missing end time Google Calendar when insert event

I trying to insert an event in the Google Calendar. The authentication and to fetch events works without any problems. Unfortunately I got the following error message:
{
error: {
errors: [
{
domain: "global",
reason: "required",
message: "Missing end time."
}
],
code: 400,
message: "Missing end time."
}
}
I request the site with cURL in PHP. To count the Content-Length for the request I using the function countArrayChars(). The following is my code:
$start = date("c", strtotime($start));
$end = date("c", strtotime($end));
$data_array = array(
"end"=>array("dateTime"=>$end),
"start"=>array("dateTime"=>$start),
"summary"=>$name
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://www.googleapis.com/calendar/v3/calendars/primary/events',
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array("Content-length: ".countArrayChars($data_array),"Content-type: application/json","Authorization: Bearer $access_token\r\n"),
CURLOPT_POSTFIELDS => $data_array
));
$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
function countArrayChars(array $array){
$charNumber = 0;
array_walk_recursive($array, function($val, $key) use (&$charNumber)
{
$charNumber += strlen($val) + strlen($key);
});
return $charNumber;
}
What I also tried is to set the data as a http_build_query, as well as a json_encode result. Unfortunately this also didn't work.
Thanks for every response.
UPDATE:
$data_array = array(
"end"=>array("dateTime"=>$end,"timeZone"=>"Europe/Zurich"),
"start"=>array("dateTime"=>$start,"timeZone"=>"Europe/Zurich"),
"summary"=>$name
);
UPDATE 2:
This is the output of $end
string(25) "2017-03-10T00:00:00+01:00"
I don't know if this will help you, but this is the code I use to add events to google calendar through the API:
$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,
),
));
You usually need to add a timezone, like I have, which could be your problem. I would suggest trying that out first.
Update:
I can't find anything else that could be wrong with your code, it's probably something having to do with how Google accepts data. All I can offer you now is exactly how I do mine, which I know works:
First, follow the instructions here to setup service account, if not done already. Make sure to create a .p12 file, instead of JSON.
You can download the PHP Google Calendar File here as well, without needing to use composer.
Next, work with the code below to suit your needs, but this should work for you. (The dateTime was properly formatted before it was sent in POST, so you may need to change that)
header('Content-type: application/json');
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 = "clientemail"; //client email setup when you create the authorization in Google Developer Console.
$private_key = file_get_contents("privatekey.p12"); //location on your server where the .p12 file you created is stored
$scopes = array('https://www.googleapis.com/auth/calendar');
$user_to_impersonate = "primary"; //This can also be an email address associated with the current gmail login if you don't want to use the default one
$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
); //Keep everything in this array the same
$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 = $useremail;
$event = $service->events->insert($calendarId, $event);
echo json_encode($event);
Check that $start is less than $end.
the error of google is not correct.
you have to check al inputfield for strange symbols. I had Straße in locationfield...that gave the missing endtime error.
Hi the problem may be on special characters in the variable, must try to encode UTF-8.
please try this
'summary' => utf8_encode($summary),
'description' => utf8_encode($descripcion),
'location' => utf8_encode($location),
regards,
Luis

php autoload not loading correctly?

Using php-ews I try to create a calendar event by example (just to get the hang of it):
require $server_path.'scripts/ews/vendor/autoload.php';
use garethp\ews\API;
use garethp\ews\API\Enumeration;
use garethp\ews\API\Type;
$ews = API::withUsernameAndPassword($exchange_host, $_SESSION["user_data"]["u_email"], $_SESSION["user_data"]["u_pwd"]);
Seems to work without errors.
// Start building the request.
$calendar = $ews->getCalendar();
$start = new DateTime('8:00 AM');
$end = new DateTime('9:00 AM');
$request = array(
'Items' => array(
'CalendarItem' => array(
'Start' => $start->format('c'),
'End' => $end->format('c'),
'Body' => array(
'BodyType' => Enumeration\BodyTypeType::HTML,
'_value' => 'This is <b>the</b> body'
),
'ItemClass' => Enumeration\ItemClassType::APPOINTMENT,
'Sensitivity' => Enumeration\SensitivityChoicesType::NORMAL,
'Categories' => array('Testing', 'php-ews'),
'Importance' => Enumeration\ImportanceChoicesType::NORMAL
)
),
'SendMeetingInvitations' => Enumeration\CalendarItemCreateOrDeleteOperationType::SEND_TO_NONE
);
$request = Type::buildFromArray($request);
$response = $ews->CreateItem($request);
I get:
PHP Fatal error: Call to undefined method garethp\ews\API::CreateItem() in
in the execute part ($ews->CreateItem())
Please take a look at my examples/, they cover exactly this. The firs thing to note is that creating Calendar events is incredibly simplified, so your long request isn't entirely needed. That being said, if you want to access the functions directly, you can't do
$response = $ews->CreateItem($request);
you need to do
$response = $ews->getClient()->CreateItem($request);
More info on building requests manually can be found here.

Categories