I'm working on a google Calendar sync with my application.
I'm using the latest google-api-php-client
Now I want to update all my event, so i want to use the batch operation.
The example code of the php client api is:
$client = new Google_Client();
$plus = new Google_PlusService($client);
$client->setUseBatch(true);
$batch = new Google_BatchRequest();
$batch->add($plus->people->get(''), 'key1');
$batch->add($plus->people->get('me'), 'key2');
$result = $batch->execute();
So when I "translate" it to the calendar API, I become the following code:
$client = new Google_Client();
$this->service = new Google_CalendarService($client);
$client->setUseBatch(true);
// Make new batch and fill it with 2 events
$batch = new Google_BatchRequest();
$gEvent1 = new Google_event();
$gEvent1->setSummary("Event 1");
$gEvent2 = new Google_event();
$gEvent2->setSummary("Event 2");
$batch->add( $this->service->events->insert('primary', $gEvent1));
$batch->add( $this->service->events->insert('primary', $gEvent2));
$result = $batch->execute();
But when I run this code, I get this error:
Catchable fatal error: Argument 1 passed to Google_BatchRequest::add()
must be an instance of Google_HttpRequest, instance of Google_Event given
And I do not think that "$plus->people->get('')" is a HttpRequest.
Does anybody know what I do wrong, or what method / object I should use to add in the batch?
Or what the correct use of the batch operation for the calendar is?
Thanks in advance!
I had the same problem while working with inserts to the MirrorService api, specifically with timeline items. What is happening is that the the Google_ServiceRequest object is seeing that you've set the useBatch flag on the client and is actually returning returning Google_HttpRequest object before executing the call to Google but the insert statement in the calendar service doesn't properly handle it as such and ends up returning the calendar event object instead.
It also looks like your params to batch->add are backwards. Should be:
$batch->add( $this->service->events->insert($gEvent1, 'primary'));
Here is my modification to the insert method (you'll need to do this in the calendar service with the proper object input to the method). Just a few lines to make it check what class is coming back from the ServiceRequest class:
public function insert(google_TimelineItem $postBody, $optParams = array()) {
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
$data = $this->__call('insert', array($params));
if ($this->useObjects()) {
if(get_class($data) == 'Google_HttpRequest'){
return $data;
}else{
return new google_TimelineItem($data);
}
} else {
return $data;
}
}
you can use this code to insert events in batch:
public function addEventInBatch($accessToken, $calendarId, array $events)
{
$client = new Google_Client();
$client->setAccessToken($accessToken);
$client->setUseBatch(true);
$service = new Google_Service_Calendar($client);
$batch = $service->createBatch();
collect($events)->each(fn ($event) => $batch->add($service->events->insert($calendarId, $event)));
return $batch->execute();
}
Related
I am trying to insert a new task into TaskList.
here is my code:
$client = getClient();
$service = new Google_Service_Tasks($client);
$optParams = array('maxResults' => 10);
$serviceTasklist = $service->tasklists->listTasklists($optParams);
$serviceTask = $service->tasks->listTasks("#default", $optParams);
try {
$task = new Google_Service_Tasks_Task();
$task->setTitle("here is new task");
$task->setNotes("this is note of new task");
$result = $service->tasks->insert("#default", $task);
return $result->getId();
} catch (Google_Exception $ggex) {
echo "\n Error: " . $ggex->getMessage();
}
I had tried to change scope from Google_Service_Task::TASK_READONLY to Google_Service_Task::TASK, included google task document also do a samething, but I tried then it not work . Can someone give my suggest or tell me know where am I wrong? Thank You !.
For documentation purpose:
The problem was in the token file itself. When you change the scopes you need to make sure to get a new updated token. If you still use the previous token is like haven't changed your code at all.
I'm following Google indexing API
And I want to send batch request with Google_Service_Indexing.
In PHP, please help me. How to do it.
In Google document, this is Google_Service_Books.
I tried with PHP like :
//set google client
$client = new Google_Client();
$client->setAuthConfig('my_key.json');
$client->addScope('https://www.googleapis.com/auth/indexing');
$client->setUseBatch(true);
//set batch
$batch = new Google_Http_Batch($client);
//set service
$service = new Google_Service_Indexing($client);
$postBody = new Google_Service_Indexing_UrlNotification();
$postBody->setType('URL_UPDATED');
$postBody->setUrl('https://my_job_detail');
$service->urlNotifications->publish($postBody);
$batch ->add($service);
$results = $batch->execute();
And I stuck in error :
Argument 1 passed to Google_Http_Batch::add() must implement interface Psr\Http\Message\RequestInterface, instance of Google_Service_Indexing_UrlNotification given, called in /Applications/MAMP/htdocs/Jukukoushi/src/Controller/ToppagesController.php on line 340
Request URL: /
I tried with PHP and completed.
//init google client
$client = new Google_Client();
$client->setAuthConfig('your_path_to_key.json');
$client->addScope('https://www.googleapis.com/auth/indexing');
$client->setUseBatch(true);
//init google batch and set root URL
$batch = new Google_Http_Batch($client,false,'https://indexing.googleapis.com');
//init service Notification to sent request
$postBody = new Google_Service_Indexing_UrlNotification();
$postBody->setType('URL_UPDATED');
$postBody->setUrl('https://your_job_detail');
//init service Indexing ( like updateJobPosting )
$service = new Google_Service_Indexing($client);
//create request
//$service->urlNotifications->createRequestUri('https://indexing.googleapis.com/batch');
$request_kame = $service->urlNotifications->publish($postBody);
//add request to batch
$batch ->add($request_kame);
I am using the Google API Client Libraries PHP (Beta) and I have been successful at getting authorization for both the Calendar and Task api.
I have also created calendars, inserted events and updated events.
The next step was to create Tasks lists. However, I keep getting error:
Fatal error: Class 'Task' not found for $task = new Task(); when I run the sample code:
require_once 'vendor/autoload.php'; //this worked for all the calendar functions
$client = new Google_Client();
$client_id="xxxxOmitted";
$client_secret="xxxxxxxOmitted";
$redirect_uri='xxxxOmitted';
$client->setApplicationName("XXXXOmitted");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Tasks($client);
$task = new Task();
$task->setTitle('New Task');
$task->setNotes('Please complete me');
$task->setDue(new TaskDateTime('2010-10-15T12:00:00.000Z'));
$result = $service->insertTasks('#default', $task);
echo $result->getId();
Found work around for tasks but not for inserting tasklist
$service = new Google_Service_Tasks($client);
$task= new Google_Service_Tasks_Task();
$task->setTitle('New Task');
$task->setNotes('Please complete me');
$result = $service->tasks->insert('#default', $task);
echo $result->getId();
Can someone help with insert tasklists? Thanks in advance!
Similar question:Only list method is working in Google task api PHP
Similarly to what done for Tasks, see the following code for Tasklists.
$service = new Google_Service_Tasks($client);
$tasklist= new Google_Service_Tasks_TaskList();
$tasklist->setTitle('New TaskList');
$service->tasklists->insert($tasklist);
A new service for Google_Tasks is instantiated. A new tasklist is created, with title set and then inserted.
I am trying to access to a calendar created by my application via cron, and I get a calendar with the same name that the calendar the application creates, but the id is absolutely different... This is my code:
public function cronTest()
{
$this->g_client = new Google_Client();
$this->g_client->setApplicationName($this->config->item("APPLICATION_NAME"));
$service = $this->getCronService("CalendarTest-46bde015a16.p12");
$calendar = $this->getCalendar($service);
}
private function getCronService($file)
{
$key = file_get_contents(CREDENTIALS_PATH.$file);
$cred = new Google_Auth_AssertionCredentials($this->config->item("google_service_id"), SCOPES, $key);
$this->g_client->setAssertionCredentials($cred);
if($this->g_client->getAuth()->isAccessTokenExpired())
$this->g_client->getAuth()->refreshTokenWithAssertion($cred);
return new Google_Service_Calendar($this->g_client);
}
private function getCalendar($service)
{
$calendarList = $service->calendarList->listCalendarList();
echo "getCalendar<br>";
foreach ($calendarList->getItems() as $calendarListEntry)
{
echo $calendarListEntry->getSummary()." with id:".$calendarListEntry->getId()."<br>";
echo "<br>";
if($calendarListEntry->getSummary()=="Auto-Citas")
echo "found";
//return $calendarListEntry->getId();
}
die;
}
When I execute it from the command line (simulating the cron):
wget www.domain.com/prototipo/alien/cronTest
I get this:
Calendar
Auto-Citas with id:h0gefmo7vjqlr4lp0r2n93vk9c#group.calendar.google.com
found
But, the id of calendar created with this application doesn´t match with this id...
Before this attempt with ron, I had to learn how to use the API, in this way I needed to remove sometimes the same calendar. So what I do, was remove one more time the Auto-Citas on my calendar, and call the function on my app to create a new calendar with a different name, then I made again the request of the "simulated cron" (wget www.domain.com/prototipo/alien/cronTest) and the result is the same than before: only one calendar called Auto-Citas, but nothing about the new calendar.
The functionality is to create a module anti-absenteeism, sending an email or sms to the user two hours before the appointment(cita=appointment)
For this tasks I have to function more... but they aren´t important for the case:
$events = $this->getDates($service,$calendar,$min,$max);
$this->transformDates($events, $service, ",phone");
Ok... I find solution just here (the google official docs). I need to use the option of user_to_impersonate.
$client_email = '1234567890-a1b2c3d4e5f6g7h8i#developer.gserviceaccount.com';
$private_key = file_get_contents('MyProject.p12');
$scopes = implode(' ', array(Google_Service_Calendar::CALENDAR));
$user_to_impersonate = 'user#example.org';
$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,
);
What is the best way I could add possibly 10,000 to 20,000 events at once to a Google Calendar with PHP?
If I try adding them separately I get a "limit exceeded" error far before the daily max.
I've also been looking at importing ICAL/ICS files but I also can't seem to find a function for this besides the calendar subscriptions. Calendar Subscriptions are great but I need to have almost "real-time" updates in my calendars when an event gets changed and it's unclear when calendar subscriptions get updated this could take as much as a day from the initial change in the ICS file.
Need to use Batch Requests. A batch request consists of multiple API calls combined into one HTTP request. Batch processing is a known feature request and is actively worked on. Read the following article about it: https://developers.google.com/google-apps/calendar/batch
See my multipleInsert function for example:
class My_google_calendar
{
...
/** Add single Event for Student */
function addEvent($lesson, $instructor, $return_request = false, $enable_attendees = false)
{
$calendar = $this->getGoogleCalendar(); // get calendar service variable
$lesson_from = date(DATE_RFC3339, $lesson->from);
$lesson_to = date(DATE_RFC3339, $lesson->from + $lesson->duration);
$event = new Google_Service_Calendar_Event();
$event->setSummary('Lesson with student: '$lesson->student_full_name);
$start = new Google_Service_Calendar_EventDateTime();
$start->setDateTime($lesson_from);
$start->setTimeZone($this->getGoogleCalendarTimeZone());
$event->setStart($start);
$end = new Google_Service_Calendar_EventDateTime();
$end->setDateTime($lesson_to);
$end->setTimeZone($this->getGoogleCalendarTimeZone());
$event->setEnd($end);
$event->setColorId(4);
$description = "...";
$event->setDescription($description);
if (isset($student->email) && $enable_attendees) {
$attendee1 = new Google_Service_Calendar_EventAttendee();
$attendee1->setResponseStatus('needsAction');
$attendee1->setEmail($student->email);
$attendees = array($attendee1);
$event->setAttendees($attendees);
}
$createdEvent = $this->calendar->events->insert($this->calendar_id, $event, array('fields' => 'id'));
return $return_request ? $createdEvent : $createdEvent->getId();
}
/** Push group of events to the Calendar */
function multipleInsert ($lessons, $instructor)
{
$this->use_batch = true;
$this->client->setUseBatch($this->use_batch);
$batch = new Google_Http_Batch($this->client);
foreach($lessons as $time => $lesson) {
$lesson = array_shift($group['lessons']);
$req = $this->addEvent($lesson, $instructor, true);
$batch->add($req, $time);
}
}
$results = $batch->execute();
return $results;
}
}