Rectangle 27 2

It's creating the event in the calendar owned by the service account, if you want to manage it, you have to share the calendar with yourself (!):

$scope = new Google_AclRuleScope();
$scope->setType('user');
$scope->setValue('YOUR-EMAIL-HERE');

$rule = new Google_AclRule();
$rule->setRole('owner');
$rule->setScope($scope);

$result = $service->acl->insert('primary', $rule);

PS: there's a new version of the PHP client library.

Thank you very much! For some reason I was under the impression that the service account would be using the "accounts" primary calendar, but this puts everything into perspective knowing that the service account is essentially a virtual account with it's own calendars/calendar system and it needs to be treated as such. Pulled out a nice bit of hair fighting with this, can't thank you enough :) About the PHP client version, indeed I've switched back the latest now. Thank you.

php - Google Calendar API v3 - Not Creating Event (Server-to-Server Au...

php api google-api google-oauth google-api-php-client
Rectangle 27 2

It's creating the event in the calendar owned by the service account, if you want to manage it, you have to share the calendar with yourself (!):

$scope = new Google_AclRuleScope();
$scope->setType('user');
$scope->setValue('YOUR-EMAIL-HERE');

$rule = new Google_AclRule();
$rule->setRole('owner');
$rule->setScope($scope);

$result = $service->acl->insert('primary', $rule);

PS: there's a new version of the PHP client library.

Thank you very much! For some reason I was under the impression that the service account would be using the "accounts" primary calendar, but this puts everything into perspective knowing that the service account is essentially a virtual account with it's own calendars/calendar system and it needs to be treated as such. Pulled out a nice bit of hair fighting with this, can't thank you enough :) About the PHP client version, indeed I've switched back the latest now. Thank you.

php - Google Calendar API v3 - Not Creating Event (Server-to-Server Au...

php api google-api google-oauth google-api-php-client
Rectangle 27 1

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');

php - Google Calendar API v3 quickAdd fail - Stack Overflow

php google-api google-api-php-client
Rectangle 27 26

I have found a solution that I think that is "the official" for what you want to do.

First, you have to activate a Google API "Client ID for installed applications".

Go to the Google API console and create the project.

Go to the "API access" option, and use the "Create OAuth 2.0 client" button.

Give a name (and a logo, if you want) to the product. Click "next".

Choose the "Installed application" option and click "Create Client Id".

*The "Authentication Code". To get it, you need the following information:

SCOPE: https://www.google.com/calendar/feeds/ (if you want to access the calendar API. There are others you can find them at the OAuth 2.0 Playground)

Now, copy the following code into a file, put the values into the variables, execute the code (php -q script_name.php), and go to the URL printed.

<?php
$scope         =   '';
$client_id      =   '';
$redirect_uri   =   '';

$params = array(
                    'response_type' =>   'code',
                    'client_id'     =>   $client_id,
                    'redirect_uri'  =>   $redirect_uri,
                    'scope'         =>   $scope
                    );
$url = 'https://accounts.google.com/o/oauth2/auth?' . http_build_query($params);        
echo $url."\n";
?>

The web page will ask you to allow the access. Do it, and you will get a code, which is your Authentication Code.

The data you used before, plus the "client secret" code in the API Console, between the "client id" and the "redirect URI".

As you did before, copy the following code, and put the variables in place (the code field is the Authentication Code). Execute and the result is the "Refresh Token".

<?php
$url = 'https://accounts.google.com/o/oauth2/token';
$post_data = array(
                    'code'          =>   '',
                    'client_id'     =>   '',
                    'client_secret' =>   '',
                    'redirect_uri'  =>   '',
                    'grant_type'    =>   'authorization_code',
                    );
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
$token = json_decode($result);

echo $token->refresh_token . "\n";
?>

At this moment, you have all you need. Be careful if one day you change the Authentication Code. You will have to get new keys.

To access a calendar service, here you have the example: Change the variable values before using it. This example gets the primary calendar events, but you can change the address for any in the calendar API (http://code.google.com/intl/ca/apis/calendar/v3/getting_started.html#background_operations)

<?php
    $scope         =   'https://www.google.com/calendar/feeds/';
    $client_id      =   '';
    $client_secret  =   '';
    $redirect_uri   =   '';


    $refresh_token  =   '';

    $token_url = 'https://accounts.google.com/o/oauth2/token';
    $post_data = array(
                        'client_secret' =>   $client_secret,
                        'grant_type'    =>   'refresh_token',
                        'refresh_token' =>   $refresh_token,
                        'client_id'     =>   $client_id
                        );
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $token_url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);
    $token_object = json_decode($result);
    $access_token = $token_object->access_token;

    // Get the results
    $rest_url = 'https://www.googleapis.com/calendar/v3/calendars/primary/events';
    $header = "Authorization: OAuth " . $access_token;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
    curl_setopt($ch, CURLOPT_URL, $rest_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $rest_result = curl_exec($ch);

    print_r(json_decode($rest_result));
    ?>

First, the script asks for an "Access Token", which is valid for an hour. Then, the script gets the REST service (any in the calendar scope), sending the access token in the header. To give a best speed at the scrip, it would be good to store the access token in a cache until it's older than 3600 seconds. This way, the script would avoid one of the two calls.

Visit OAuth 2.0 Playground to understand all the information sent in the OAuth process. It helped me a lot

A post by Eric Nagel in his blog gave me the solution. All the merit is to him. I can't link it since I haven't got enough "reputation".

I used this method to upload videos to Youtube and it works like a charm. No need of asking users to authenticate!! Thanks a lot!

Now, to get refresh token, I need to send 'access_type:offline' while getting authentication code (developers.google.com/identity/protocols/). And Is refresh_token available forever or is it expired after sometime?

Forever is a verystrong word! But you just have to do it once, and I have scripts running with this since some years ago.

I created a Web Application OAuth Client Id because there was no Installed application option. I followed the steps and I am able to get the Authentication Code. But to get refresh token I get Notice: Trying to get property of non-object error at the echo $token->refresh_token . "\n"; line. And if anyone can look at my question it would be so nice. Because there is only one month left to finish my final graduate project. :(

php - Google Calendar API v3 hardcoded credentials - Stack Overflow

php authentication oauth google-api google-calendar
Rectangle 27 12

You will need to use both the Developer Key (API Key) and OAuth2. The developer key authenticates who wrote the software and is used for things like quota which is on a per developer basis not a per user basis. OAuth2 is for user authentication and will be need to access the non-public calendar.

OAuth2 has a renew token from which you can generate a session token and this means that you will not need to screen scrape the OAuth screens to get authenticated. To get this I would write a little command line application, or you use a one off PHP page.

  • Generate a new Client ID and choose Installed Application ( as you will be authenticating you server as you not as your user)
  • Either using a console app or a one off PHP page authenticate using OAuth and your google account (the one with the calendar you want access to)
  • In the return from the authentication there should be a renew token, (called renew or refresh or something similar). Save this string and make it available to your PHP site.
  • When you need to access the service your OAuth library should have a renew/refresh call. There is an example using .Net below.
private IAuthorizationState CreateAuthorization(NativeApplicationClient arg)
 {
   // Get the auth URL:
   IAuthorizationState state = new AuthorizationState(new[] { AdsenseService.Scopes.AdsenseReadonly.GetStringValue() });
   state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
   if (refreshToken.IsNotNullOrEmpty()) // refreshToken you stored in step 4
   {
     try
     {
       state.RefreshToken = refreshToken;
       if (arg.RefreshToken(state))     // This is calling out to the OAuth servers with the refresh token getting back a session token, returns true if successful.
       {
         if (state.RefreshToken != refreshToken) // if the refresh token has changed, save it.
         {
           PersistRefreshToken(authorization.RefreshToken);
         }
         return this.authorization = state; // Retain the authorization state, this is what will authenticate your calls.
       }
     }
     catch (ProtocolException ex) {...}

The AuthorisationState that has now been renewed can then be used to authenticate call you make to the API. this state can be used many time until it expires and then can be refreshed. As you are authenticating your application as yourself not as a user this AuthorisationState can be shared by all you sessions. Both the current AuthorisationState and the refresh token should be kept securely on your server and never sent to the client, if you ever sent these as part of a response your clients would have the same privileges as your code application

php - Google Calendar API v3 hardcoded credentials - Stack Overflow

php authentication oauth google-api google-calendar
Rectangle 27 1

Can also be used with the Google php library. The access token for the $client->setAccessToken() function has to be formatted in the following way:

$at= '{"access_token":"' . $access_token . '",' .
      '"token_type":"Bearer",' .
      '"expires_in":3600,' .
      '"refresh_token":"' . $refresh_token . '",',
      '"created":' . time() . '}';

Where $access_token is the access token found by you and $refresh_token is the refresh token. Tested with the useless simple.php google example.

$client->setAccessToken($at);

php - Google Calendar API v3 hardcoded credentials - Stack Overflow

php authentication oauth google-api google-calendar
Rectangle 27 1

I'm convinced this is a bug in the calendar API and I ended up writing a workaround for it.

I wrote code to calculate the expected instances of an event based on the start and recurrence data and then compare that against the instances in the when array on the recurrence. It creates canceled event objects when there is an expected instance but it's missing from the when array.

php - Google calendar API not returning all canceled events - Stack Ov...

php google-calendar zend-gdata
Rectangle 27 2

You should consider doing this with a service account. A service account will allow your application to access your Google Calendar data without prompting a user for access.

When you create the service account take the email address it gives you and add it like you would any other user to your Google Calendar. The script will then have access to it.

<?php
session_start();        
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';     
/************************************************   
 The following 3 values an befound in the setting   
 for the application you created on Google      
 Developers console.         Developers console.
 The Key file should be placed in a location     
 that is not accessable from the web. outside of 
 web root.   

 In order to access your GA account you must    
 Add the Email address as a user at the     
 ACCOUNT Level in the GA admin.         
 ************************************************/
$client_id = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp.apps.googleusercontent.com';
$Email_address = '1046123799103-nk421gjc2v8mlr2qnmmqaak04ntb1dbp@developer.gserviceaccount.com';     
$key_file_location = '629751513db09cd21a941399389f33e5abd633c9-privatekey.p12';     
$client = new Google_Client();      
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);    
// seproate additional scopes with a comma   
$scopes ="https://www.googleapis.com/auth/calendar.readonly";   
$cred = new Google_Auth_AssertionCredentials(    
    $Email_address,      
    array($scopes),     
    $key         
    );      
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {        
    $client->getAuth()->refreshTokenWithAssertion($cred);       
}       
$service = new Google_Service_Calendar($client);    

?>

<html><body>

<?php
$calendarList  = $service->calendarList->listCalendarList();
print_r($calendarList);
while(true) {
    foreach ($calendarList->getItems() as $calendarListEntry) {
        echo "<a href='Oauth2.php?type=event&id=".$calendarListEntry->id." '>".$calendarListEntry->getSummary()."</a><br>\n";
    }
    $pageToken = $calendarList->getNextPageToken();
    if ($pageToken) {
        $optParams = array('pageToken' => $pageToken);
        $calendarList = $service->calendarList->listCalendarList($optParams);
    } else {
        break;
    }
}    

?>
</html>

really helpful.. Thanks a lot .. after wasting almost 10 hours .. I found this and it works perfectly..!

Using above code, How can I add event in google calendar on particular date?

I just want to add event in google calendar using above code. Than where is I mention that date of event

php - Google Calendar API using refresh token - Stack Overflow

php google-calendar google-oauth google-api-php-client
Rectangle 27 1

I would convert the dates to unix timestamps and calculate the difference between the start and end dates. This is how I would accomplish the first part of your question:

$events = array(
    array(
        'start' => '2016-02-19T00:00:00-07:00',
        'end' => '2016-02-19T11:00:00-07:00'
    ),
    array(
        'start' => '2016-02-19T13:30:00-07:00',
        'end' => '2016-02-19T14:30:00-07:00'
    ),
    array(
        'start' => '2016-02-19T17:00:00-07:00',
        'end' => '2016-02-19T19:00:00-07:00'
    ),
    array(
        'start' => '2016-02-19T21:00:00-07:00',
        'end' => '2016-02-19T23:00:00-07:00'
    )
);

$free_time_slots = array();
$count = count($events)-1;
$i = 0;
foreach($events as $event) {
    if ($i < $count) {
        $free_time = strtotime($events[$i+1]['start']) - strtotime($event['end']);
        $free_time_slots[] = array(
            'start' => date("F j, Y, g:i a", strtotime($event['end'])),
            'end' => date("F j, Y, g:i a", strtotime($events[$i+1]['start'])),
            'minutes' => $free_time / 60
        );
        $i++;
    }
}  
echo '<pre>';
print_r($free_time_slots);
Array
(
    [0] => Array
        (
            [start] => February 19, 2016, 11:00 am
            [end] => February 19, 2016, 1:30 pm
            [minutes] => 150
        )

    [1] => Array
        (
            [start] => February 19, 2016, 2:30 pm
            [end] => February 19, 2016, 5:00 pm
            [minutes] => 150
        )

    [2] => Array
        (
            [start] => February 19, 2016, 7:00 pm
            [end] => February 19, 2016, 9:00 pm
            [minutes] => 120
        )

)

php - Google Calendar API algorithm to find open time slots for a give...

php algorithm date datetime google-calendar
Rectangle 27 1

From the Handling API Errors in the Google Calendar API, the error 404 that you get sometime means that the specified resource was not found. Other possible cause is when the requested resource (with the provided ID) has never existed or when accessing a calendar that the user can not access.

The suggested action here is use exponential backoff.

Based from this SO question, another caused of this issue is when accessing private calendar with a service account, you need to either perform an authority delegation if you own the domain containing those calendars or you will need to share the private calendar with the email address of the service account.

That's it, I forgot to share the calendar with the email of the service! Thank you so much!

Access another calendar using same settings - Google Calendar API PHP ...

php google-api google-calendar google-api-php-client
Rectangle 27 3

In nutshell, spread the large set of requests into smaller set of request. Most of the servers nowadays are multi core, it should capable to perform multitasking

  • fetch the event that start in 5 minutes
  • find all the users & details that need to be notified (assume is 200)
  • for every 10 notifcations, spawn a shell_exec process that calling Notification script, and make sure push the calling into background (refer php execute a background process )
  • receive the details of 10 users need to be notified (details input from master scripts)
200 x 1 = 200 seconds
1 seconds for master + (10 x 1 seconds) = 12 seconds

Server & bandwidth resources is not unlimited, there is an capped on how many processes your server can run concurrently, this up to you to perform testing and fine-tune

Hi! I made what you suggested to me. But it takes more second than before. I write the script like this. But the execution of the script wait all the exec(); so it doesn't made the php in background. foreach($tests as $test) { exec("php test.php ".$test["id"]); } what I'm doing wrong? thanks in advance!

exec

sorry but I continue to do not understand what exactly I've to do to push exec into background. Which of those answers in stackoverflow.com/questions/45953/ are correct?

in short, push into background mean PHP won't not wait for exec to return result

ok but I do not found the correct piece of code to do that. What is the correct piece of code?

How to add large number of event notification reminder via Google Cale...

php google-api google-calendar google-apps
Rectangle 27 1

The prn field works only with hosted domains, if the domain administrator enabled your application (based on client id) to impersonate users.

I am the domain administrator, and I have enabled the application following these steps; developers.google.com/accounts/docs/. Isnt that for OAuth applications? Not OAuth 2.0? The application and the Google Apps account are under the same domain.

Thank you for your answer. The penny finally dropped with the help of some other info as well. I was using the domain that the Google Apps account was on as the Client Id. Not the Client Id that was generated when I created the API Project. Doh!

Google OAuth 2.0 Service Account - Calendar API (PHP Client) - Stack O...

api google-calendar google-oauth
Rectangle 27 1

Just make sure the calendar is public, then try google calendar freebusy method. It will definitely work.

How to access any other's google calendar using google php api - Stack...

calendar google-calendar google-api-php-client
Rectangle 27 0

Thank you! Unfortunately, though, this does not answer my question. All of that documentation is for the REST API, I was looking for support documentation to the client library. Any idea where that may be?

Google Calendar API Library (PHP) - Where is the documentation? - Stac...

php google-api google-calendar google-api-php-client
Rectangle 27 0

CalendarList

If it is anything like the DRIVE documentation, then it likely does not show you very much. We would love to see google spend a bit of time creating actual documentation on their PHP library similar to how jQuery spends time working through ALL of the methods available in the library. Very little is said about how to use the client library. The library itself is a 64 file jumble with no real documentation about what to include and when.

Yup been spending hours trying to figure out how to use the client library. I got the calendar list to spit out but what do I do with that. Its not showing anything from my calendar after giving authorization... The documentation is worthless. I am just searching around for some actual examples. If I ever figure this out I will write a detailed documentation. All I want to do is show a user their calendar when they are logged into a website...

Google Calendar API Library (PHP) - Where is the documentation? - Stac...

php google-api google-calendar google-api-php-client
Rectangle 27 0

When you send that GET request, Calendar may return an HTTP 302 redirect; the redirect URL has a new query parameter, gsessionid, appended to it. (Note that some methods of sending the GET request may not show you the response headers by default; if you receive a blank response, check your HTTP utility's documentation to find out how to view response headers.) That gsessionid parameter is the way that Calendar keeps track of your session, to improve speed of response. (Some methods of sending the GET request may automatically follow redirects, and in some cases Calendar may not send a redirect at all; in such cases, you don't need to send the second request described below.) So after you've sent the GET request, you have to read the HTTP headers of the response to find the URL with the session ID appended; then you need to send another GET request with that new URL. (Note that if you're using the UNIX command line to send requests, you may have to precede the question mark in the new URL with a backslash to keep your shell from interpreting it.) In response to the second GET request, Calendar returns an HTTP 200 OK status code and a feed containing all the events in your calendar. If there's only one event in your calendar, then Calendar returns something similar to the following feed. We've edited the following example a little to make it a little more readable by humans; in particular, a real Calendar feed contains actual magic-cookie values and entry IDs.

So when I make a request to the API I check the response header. If the response code = 302 I catch the value of the gsessionid. Then i make exactly the same request like I did the first time but then with the gsessionid parameter key and value attached. Looks like this is working for me.

For the poeple who want to see my code, im using PHP with the cakephp 2.0 framework and some oauth class:

$consumer   = $this->createConsumer();
                    $response   = $consumer->get(
                        $settings['Setting']['access_token_key'], 
                        $settings['Setting']['access_token_secret'], 
                        $find['Calendar']['eventFeedLink'],
                        array(
                            'alt'       => 'jsonc',
                            'start-min' => $_sunday . 'T00:00:00',
                            'start-max' => $_saturday . 'T23:59:59',
                            //'singleevents'    => false
                        )
                    );

                    if($response->code == 302 && isset($response->headers['Location']) && !empty($response->headers['Location'])) {

                        $url    = $response->headers['Location']; 
                        $vars = explode('&',$url);
                        foreach($vars as $string){
                             list($is,$what) = explode('=',$string);

                             if($is == "gsessionid") {
                                 $gsessionid    = $what;
                                 break;
                             }
                        }

                        if(isset($gsessionid) && !empty($gsessionid)) {

                            $response   = $consumer->get(
                                $settings['Setting']['access_token_key'], 
                                $settings['Setting']['access_token_secret'], 
                                $find['Calendar']['eventFeedLink'],
                                array(
                                    'alt'           => 'jsonc',
                                    'start-min'     => $_sunday . 'T00:00:00',
                                    'start-max'     => $_saturday . 'T23:59:59',
                                    'gsessionid'    => $gsessionid
                                    //'singleevents'    => false
                                )
                            );

                        }

                    }

php - Google calendar API response: moved temporarily - Stack Overflow

php cakephp oauth google-calendar
Rectangle 27 0

Click on your project, then on the left side you will see APIs & Auth, click on Credentials. You will need to create your OAuth, and Public API Access keys.

Once you have done that you will then enter those into the appropriate client_id, secret, redirect etc.

The redirect uri is the same page your app is on, its the page the user gets sent back to after authorizing.

ok, thanks bowenac. I managed to include php client and i am now able to fetch "calendar id" from google calendar service. But my need is a bit different. The php example i tried ask me to authenticate (oauth2). My need is to have an appa (ios/android/webapp) that asks user his google calendar credentials (user/pwd) and then passes those to my php script that enters in HIS OWN calendar the event chosen in the app. I dont' know if i'm sufficiently clear. I read something about "offline" mode ? i'm doing mess ? :) Thanks !

That is what I was wanting to do as well. I thought I could use the API to actually show a calendar and be able to make edits just like you can on google. It's looking like that isn't really possible.

i can assure you that it worked flawlessly on api V1 and obj-c gdata client, back in the "old" 2012 :)

anyway, i don't want any "widget calendar". I have my interface/ui on my app. Then, via HTTP POST, i'd like to send user and pwd of the user of the app and insert the chosen event in his own calendar. Doesn't seem to difficult to me, even with OAUTH2 and API v3 :) But i can't :(

Problems working with Google Calendar Api V3 and PHP - Stack Overflow

api calendar google-calendar
Rectangle 27 0

$cred = new Google_Auth_AssertionCredentials(
  $service_account_name,,
  array('https://www.googleapis.com/auth/calendar'),
  $key,
  'notasecret',
  'http://oauth.net/grant_type/jwt/1.0/bearer',
  'some.email@our.domain.com'
);

Tell Google who is the person you want to impersonate, and then you will be able to operate everything of google calendar for this user.

Google Calendar API v3 domain wide delegated service account on PHP - ...

php api calendar google-calendar google-api-php-client
Rectangle 27 0

Granting domain-wide delegation to your service account in the Google Apps Admin Console doesn't give it access to everyone's calendar. Instead it allows the service account to impersonate any given user within your domain, and then make requests as that user.

In the PHP client library you can impersonate a user by setting the sub field on the Google_AssertionCredentials object you created.

$auth->sub = $userEmail;

We don't have a complete sample showing this for the Calendar API, but the Drive API documentation includes a sample, and the process is identical.

php - How do I Insert Google Calendar Event using Google Api 3 for any...

php google-api google-calendar google-api-v3
Rectangle 27 0

Simple API Access key

Normally OAuth 2.0 is used for authorization. But since you have your reason not to use it.

  • If you want to use OAuth1.0 for authorization. You need an API key in Simple API Access section on the API Access page.
  • If you want to use username & password login instead of OAuth, you can refer to ClientLogin, but this is not recommanded.

You say there is no such thing, but then say "get an api key in the simple api access section"?

Did you check if the API key is really necessary? I think the information in developers.google.com/google-apps/calendar/auth conflicts with developers.google.com/accounts/docs/OAuth, and I was able to query Calendar API v3 without the API key at all, with just the consumer key and secret (OAuth1)

How do you do this now with the Cloud Console?

How do I use Google's "Simple API Access key" to access Google Calenda...

php google-calendar