Ce tutoriel explique comment ajouter des événements dans un agenda Google à partir d’un script PHP sur Raspberry Pi. Le script demande l’autorisation de se connecter à l’agenda puis, une fois l’autorisation accordée, crée des événements sur l’agenda lorsqu’on le souhaite.
Nous avons créé un agenda « Pi Nautilus » dans l’article Raspberry Pi : envoyer des SMS sans 3G et gratuitement. Cet article explique également comment installer PHP sur un Pi si c’est nécessaire.
Nous allons maintenant écrire un programme, en PHP, qui créera automatiquement un événement dans l’agenda Google.
Télécharger le client PHP de l’API Google
Dans ce dépôt GitHub, suivre les instructions « Download the release » :
- cliquer sur le lien ‘the releases’
- dans le chapitre « Downloads », sélectionner un fichier qui a un nom du genre google-api-php-client-[RELEASE_NAME].zip (pour moi google-api-php-client-2.0.3_PHP54.zip)
- extraire le fichier zip
- Copier les fichiers extraits dans un répertoire php-google-api-client (placé dans notre répertoire de travail, pour moi /home/jf/exec).
Paramétrer un projet dans la console Google Api
La principale source d’informations que j’ai utilisé est PHP Quickstart, par Google.
Se connecter à la console Google API.
Créer un projet
Créer un projet, par exemple « Api Google Calendar » (noter le nom choisi)
Activer l’API Google Calendar
Obtenir des identifiants
Au sein du projet, aller dans le menu « identifiants ». Ne pas cliquer sur la fenêtre « API identifiants » mais aller dans l’onglet « Ecran d’autorisation OAuth ».
Maintenant, on peut cliquer sur le bouton « créer des identifiants », on choisit « ID client OAuth » puis « autre ». On lui donne un nom « client Pi calendar » et on crée l’ID :
Une fois le client créé, une fenêtre s’affiche avec notre ID client et son code secret. Les copier et les coller dans un document. On voit maintenant une liste des clients créés. Télécharger le fichier JSON en cliquant sur le bouton à droite de la ligne :
La clé doit être placée dans un répertoire /home/jf/exec/certificates et renommée client_secret.json .
On en profite pour créer un répertoire /home/jf/exec/credentials , qui doit être vide.
Vérifier l’organisation du répertoire de travail
Mon répertoire de travail est /home/jf/exec.
A l’intérieur, j’y trouve trois répertoires :
- certificates, qui contient client_secret.json ;
- credentials, qui est vide pour l’instant ;
- php-google-api-client, qui contient la bibliothèque PHP de client de l’API Google, comme dans cette copie d’écran :
Maintenant, on peut créer notre premier script pour intéragir avec notre agenda Google.
Créer un script PHP pour modifier l’agenda
Obtenir l’identifiant de l’agenda à modifier
L’id du calendrier est montrée lorsque je clique sur paramètres (onglet détails) :
A ce stade on a noté les informations suivantes (AAAA est composé de 44 caractères [a-z][0-9], BBBB de 24 caractères [A-Z][a-z][0-9], CCCC 26 caractères [a-z][0-9]) :
Nom du projet | Api Google Calendar |
Nom du produit | Pi calendars by ALD |
ID client | AAAA.apps.googleusercontent.com |
code secret client | BBBB |
ID agenda | parcours-performance.com_CCCC@group.calendar.google.com |
Ecrire un premier script
J’ai utilisé principalement le script PHP proposé par PHP Quickstart, de Google, ainsi qu’un bout de code trouvé sur la page consacrée à Events: quickAdd.
Si on veut pouvoir accéder en lecture ET écriture, il faut modifier la ligne contenant « define( ‘SCOPES’,… », et remplacer CALENDAR_READONLY par CALENDAR.
Et si on avait déjà obtenu une autorisation quand SCOPES était réglé sur CALENDAR_READONLY, il faut supprimer le fichier JSON dans le répertoire credentials avant de l’éxécuter de nouveau. Sinon, on a une autorisation en lecture seule et on demande l’écriture, ce qui provoque une erreur.
Créer un fichier al-pi-create-google-calendar-event.php dans notre répertoire de travail /home/jf/exec.
Dans ce fichier – en mode encodage UTF8, retours de ligne LINUX – placer le code suivant (remplacer l’id du calendrier par votre id) :
#!/usr/bin/php <?php require_once __DIR__ . '/php-google-api-client/vendor/autoload.php'; define('APPLICATION_NAME', 'Pi calendars by ALD'); define('CREDENTIALS_PATH', __DIR__ . '/credentials/calendar-php-quickstart.json'); define('CLIENT_SECRET_PATH', __DIR__ . '/credentials/client_secret.json'); // If modifying these scopes, delete your previously saved credentials // at __DIR__ . '/credentials/calendar-php-quickstart.json define('SCOPES', implode(' ', array( Google_Service_Calendar::CALENDAR) // CALENDAR_READONLY )); if (php_sapi_name() != 'cli') { throw new Exception('This application must be run on the command line.'); } // data for the function $title = "19.8°C chez Pi Nautilus"; $cal_id = "parcours-performance.com_CCCC@group.calendar.google.com" ; $create_event = al_pi_create_quick_event( $title, $cal_id ) ; echo "event ID : " . $create_event . "\r\n" ; function al_pi_create_quick_event( $title, $cal_id ) { // Get the API client and construct the service object. $client = getClient(); $service = new Google_Service_Calendar($client); // https://developers.google.com/google-apps/calendar/v3/reference/events/quickAdd $optParams = Array( 'sendNotifications' => true, ); $createdEvent = $service->events->quickAdd( $cal_id, $title, $optParams ); return $createdEvent->getId(); } /** * Returns an authorized API client. * @return Google_Client the authorized client object */ function getClient() { $client = new Google_Client(); $client->setApplicationName(APPLICATION_NAME); $client->setScopes(SCOPES); $client->setAuthConfig(CLIENT_SECRET_PATH); $client->setAccessType('offline'); // Load previously authorized credentials from a file. $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH); if (file_exists($credentialsPath)) { $accessToken = json_decode(file_get_contents($credentialsPath), true); } else { // Request authorization from the user. $authUrl = $client->createAuthUrl(); printf("Open the following link in your browser:\n%s\n", $authUrl); print 'Enter verification code: '; $authCode = trim(fgets(STDIN)); // Exchange authorization code for an access token. $accessToken = $client->fetchAccessTokenWithAuthCode($authCode); // Store the credentials to disk. if(!file_exists(dirname($credentialsPath))) { mkdir(dirname($credentialsPath), 0700, true); } file_put_contents($credentialsPath, json_encode($accessToken)); printf("Credentials saved to %s\n", $credentialsPath); } $client->setAccessToken($accessToken); // Refresh the token if it's expired. if ($client->isAccessTokenExpired()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); file_put_contents($credentialsPath, json_encode($client->getAccessToken())); } return $client; } /** * Expands the home directory alias '~' to the full path. * @param string $path the path to expand. * @return string the expanded path. */ function expandHomeDirectory($path) { $homeDirectory = getenv('HOME'); if (empty($homeDirectory)) { $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH'); } return str_replace('~', realpath($homeDirectory), $path); } ?>
En SSH, se connecter au Pi (Nautilus pour moi)
ssh root@nautilus
Se placer dans le répertoire de travail puis exécuter le fichier :
cd /home/jf/exec ./al-pi-create-google-calendar-event.php
Un message commençant par « Open the following link in your browser: » s’affiche sur l’écran de notre Pi. On copie le lien et on le colle dans un navigateur. Ca nous renvoie à une page dans laquelle je dois autoriser le partage. On copie le code et on le colle dans l’invite de commande du Pi. Le script sauvegarde notre autorisation dans le répertoire défini (/home/jf/exec/credentials) puis nous communique l’event ID :
Nous avons été autorisé à interagir avec le calendrier Google et notre premier événement à été créé. A partir de maintenant, nous n’aurons plus besoin d’obtenir de nouveau l’autorisation de l’agenda pour y intervenir.
Et maintenant ?
Maintenant que nous savons comment interagir avec une API Google, on peut en principe faire la même chose avec d’autres API, telles que celle de Google Sheet pour stocker des informations dans un tableur Google.
Merci, merci, grace à vous j’ai enfin réussi à synchroniser mon agenda, merci encore
bonjour
je souhaite ecrire sur plusieurs calendrier, pouvez vous m indiquer comment proceder svp.
votre aide me serait tres chere je suis sur le probleme deja depuis plusieurs jours sans succes.
merc
Excusez-moi, J’ai réussi à installer le composer sur mon serveur, mais maintentant il me donne une (plusieurs) autre erreur quand j’execute le fichier. PHP Fatal error: Uncaught exception ‘InvalidArgumentException’ with message ‘missing the required redirect URI’ in /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/google-api-php-client/vendor/google/auth/src/OAuth2.php:639 Stack trace: #0 /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/google-api-php-client/src/Google/Client.php(338): Google\Auth\OAuth2->buildFullAuthorizationUri(Array) #1 /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/quickstart.php(69): Google_Client->createAuthUrl() #2 /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/quickstart.php(33): getClient() #3 /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/quickstart.php(26): al_pi_create_quick_event(‘19.8\xC2\xB0C chez Pi…’, ‘609281247174-9h…’) #4 {main} thrown in /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/google-api-php-client/vendor/google/auth/src/OAuth2.php on line 639 Fatal error: Uncaught exception ‘InvalidArgumentException’ with message ‘missing the required redirect URI’ in /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/google-api-php-client/vendor/google/auth/src/OAuth2.php:639 Stack trace: #0 /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/google-api-php-client/src/Google/Client.php(338): Google\Auth\OAuth2->buildFullAuthorizationUri(Array) #1 /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/quickstart.php(69): Google_Client->createAuthUrl() #2 /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/quickstart.php(33): getClient() #3 /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/quickstart.php(26): al_pi_create_quick_event(‘19.8\xC2\xB0C chez Pi…’, ‘609281247174-9h…’) #4 {main} thrown in /home/clients/8fe95ba8064db061b6e3ba65d19a5dfc/web/work/google-api-php-client/vendor/google/auth/src/OAuth2.php on… Lire la suite »
Bonjour,
J’ai essayé d’utilisé votre tutoriel, mais j’ai un soucis.
Je n’utilise pas sur Linux, j’ai une application web de gestion de clients, et je voudrais ajouter les rendez-vous directement depuis cette application.
Mais je ne sais pas comment y faire pour la partie d’execution du fichier.
Si j’accède le fichier en utilisant le navigateur web il me donne l’erreur « Fatal error: Uncaught Exception: This application must be run on the command line. in /home/httpd/vhosts/../quickstart.php:19 Stack trace: #0 {main} thrown in /home/httpd/vhosts/…/quickstart.php on line 19 »
Est-ce que vous pourriez m’aider avec cela?