Get color_id from a Google Calendar using API [PHP]

For a project I needed to get the events from a Google Calendar, as well as the colors from it.

It’s been a pain, but after a couple of days I’ve been able to create a PHP page to do so. It will use the server-to-server auth mechanism.

I’ll try to provide the different steps (please note that my Google Console is in French so I tried to translate) :

  1. Go to https://console.developers.google.com/apis/api/calendar/overview and Activate the Calendar API (or create first a project if required)
  2. Once the API is activated you should be invited to go to the Identification part ; make sure you choose « Account Service Key » for the identification mode
  3. Then pick « New Service » and complete the fields (choose JSON for the file format)
  4. Download the JSON file and save it where your PHP file will stand on your web server
  5. Open the JSON file and search for the client_email
  6. Go to https://calendar.google.com/ and in the sharing parameters : make sure that you share your calendar in editing with the client_email address found in the previous step (the editing mode is required to get the Colors)
  7. Now you need to install the PHP library from Google … in my case I don’t have a console access on the server, so I transfered the files from Github to the web server, in the same directory as our PHP file will be (so I got a folder called google-api-php-client-1.1.7)
  8. Create your PHP file with the below content :
    <?php
    // make sure the include path got the Google API (please refer to https://developers.google.com/api-client-library/php/start/installation)
    set_include_path(get_include_path() . PATH_SEPARATOR . '/full/path/WordPress/wp-content/agenda/google-api-php-client-1.1.7/src/Google');
    require_once "autoload.php";
    
    // Connect to the Google Calendar Service
    $client = new Google_Client();
    $client->setApplicationName("Google Calendar");
    $data = json_decode(file_get_contents('YourKeyFile-xxxxx.json'));
    $client_id = $data->client_id;
    $client_email = $data->client_email;
    $cred = new Google_Auth_AssertionCredentials(
      $client_email,
      array(Google_Service_Calendar::CALENDAR),
      $data->private_key
    );
    
    // Remember to cache the access token locally if making multiple calls
    // and don't just use this function for each request!
    $client->getAuth()->refreshTokenWithAssertion($cred);
    $service = new Google_Service_Calendar($client);
    $optParams = array(
      "calendarId"   => "TheGoogleAccountForTheCalendar@gmail.com",
      "singleEvents" => true,
      "timeZone"     => "Europe/Paris",
      "maxResults"   => 250,
      "timeMin"      => date("c", strtotime("midnight")), /* to get events from today... */
      "timeMax"      => date("c",strtotime('+3 day')), /* ...to the 3 next days */
      "orderBy"      => "startTime"
    );
    $events = $service->events->listEvents('TheGoogleAccountForTheCalendar@gmail.com', $optParams);
    ?>
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <meta http-equiv="Content-Language" content="fr" />
        <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
      </head>
      <body>
    <?php
      while(true) {
        foreach ($events->getItems() as $event) {
          $endTime = new DateTime($event->getEnd()->getDateTime());
          echo $event->getSummary() ." [".$event->getColorId()."] (".$endTime->format('Y-m-d').")<br>";
        }
        $pageToken = $events->getNextPageToken();
        if ($pageToken) {
          $optParams['pageToken'] = $pageToken;
          $events = $service->events->listEvents('lgpmontpellier@gmail.com', $optParams);
        } else {
          break;
        }
      }
    ?>
      </body>
    </html>
    

    Finally you can refer to the Google Calendar API.

    FYI I retrieved the below colorId for the below available colors:

        // same order as the image above
        switch ($event->getColorId()) {
          case 9: $color="#5484ED"; break;
          case 1: $color="#A4BDFC"; break;
          case 7: $color="#46D6DB"; break;
          case 2: $color="#7AE7BF"; break;
          case 10: $color="#51B749"; break;
          case 5: $color="#FBD75B"; break;
          case 6: $color="#FFB878"; break;
          case 4: $color="#FF887C"; break;
          case 11: $color="#DC2127"; break;
          case 3: $color="#DBADFF"; break;
          case 8: $color="#E1E1E1"; break;
          default: $color="#AC725E"; // the first one in the picture, the one that is checked
        }
    

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*