Bonjour à tous,
J'aimerai ajouter une entrée à Google Agenda depuis une page php (quickstart.php du site developers.google.com).

Sur ma console.cloud.google.com j'ai activé l'API Calendar, créé un User Type Externe pour OAuth 2.0, un identifiant Compte de Service puis ajouté une clé de type JSON à ce compte.
Voici mon code d'insertion d'event :

<?php
require __DIR__ . '/vendor/autoload.php';

/*
if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}
*/

use Google\Client;
use Google\Service\Calendar;

/**
 * Returns an authorized API client.
 * @return Client the authorized client object
 */
function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google Calendar API PHP Quickstart');
    $client->setScopes('https://www.googleapis.com/auth/calendar.events');//.events.readonly');
    $client->setAuthConfig('credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } 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);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Calendar($client);

// Print the next 10 events on the user's calendar.
/*try{

    $calendarId = 'primary';
    $optParams = array(
        'maxResults' => 10,
        'orderBy' => 'startTime',
        'singleEvents' => true,
        'timeMin' => date('c'),
    );
    $results = $service->events->listEvents($calendarId, $optParams);
    $events = $results->getItems();

    if (empty($events)) {
        print "No upcoming events found.\n";
    } else {
        print "Upcoming events:\n";
        foreach ($events as $event) {
            $start = $event->start->dateTime;
            if (empty($start)) {
                $start = $event->start->date;
            }
            printf("%s (%s)\n", $event->getSummary(), $start);
        }
    }
}
catch(Exception $e) {
    // TODO(developer) - handle error appropriately
    echo 'Message: ' .$e->getMessage();
}*/

// AJOUT À L'AGENDA : 
try{
    $event = new Google_Service_Calendar_Event(array(
      'summary' => 'ETIENNE',
      'location' => '800 Howard St., San Francisco, CA 94103',
      'description' => 'A chance to hear more about Google\'s developer products.',
      'start' => array(
        'dateTime' => '2023-01-01T09:00:00-07:00',
        'timeZone' => 'America/Los_Angeles',
      ),
      'end' => array(
        'dateTime' => '2023-01-05T17:00:00-07:00',
        'timeZone' => 'America/Los_Angeles',
      ),
      'recurrence' => array(
        'RRULE:FREQ=DAILY;COUNT=2'
      ),
      'attendees' => array(),
      'reminders' => array(),
    ));

    $calendarId = 'primary';
    $event = $service->events->insert($calendarId, $event);
    printf('Event created: %s\n', $event->htmlLink);
}
catch(Exception $e) {
    // TODO(developer) - handle error appropriately
    echo 'Message: ' .$e->getMessage();
}
?>

Ce que j'obtiens
En retour j'obtiens :
Event created: https://www.google.com/calendar/event?eid=RRRWNwdm5vYjBpcnRRRRRRcjFqb2dfMjAyMjARRRRRdGlvbi1hZ2VuZGRRRRR2VuZGEtMzU3NDA5LmlhbS5RRRRVydmljZWFjRRRRRbnQuY29t%5Cn
Mais l'agenda reste tristement vide !
Pourtant, si je dé-commente la partie Print the next 10 events on the user's calendar j'obtiens :
Upcoming events: TEST AJOUT (2023-01-01) TEST AJOUT (2023-01-02)

Donc ça a fonctionné mais toujours rien dans l'agenda !
Merci d'avance pour vos lumières !

2 réponses


Etienne69
Auteur
Réponse acceptée

Quand j'ai créé dans console.cloud.google.com un compte de service, puis ensuite pour ce compte j'ai créé une clé j'ai obtenu un fichier JSON + une adresse mail de type nomdemonprojet@nomdemonprojet-785123.iam.gserviceaccount.com

  1. Je suis allé dans mon Agenda Google, sur l'agenda GESTION créé pour recevoir les event de mon code PHP pour ajouter cette adresse mail dans "partager avec des personnes en particulier".

  2. J'ai récupéré l'ID de cet Agenda GESTION pour l'affecter à la variable $calendarId.

J'ai relancé ma page quickstart.php et là, mon ajout est apparu !
Seulement problème, je me fais grignoter un jour !
Avec le code ci-dessous, j'ai un event du 01 au 04/12/2022 !
Une idée ?

<?php
require __DIR__ . '/api/vendor/autoload.php';

/*
if (php_sapi_name() != 'cli') {
    throw new Exception('This application must be run on the command line.');
}
*/

use Google\Client;
use Google\Service\Calendar;

/**
 * Returns an authorized API client.
 * @return Client the authorized client object
 */
function getClient()
{
    $client = new Client();
    $client->setApplicationName('Google Calendar API PHP Quickstart');
    $client->setScopes('https://www.googleapis.com/auth/calendar');//.events.readonly');
    $client->setAuthConfig('api/credentials.json');
    $client->setAccessType('offline');
    $client->setPrompt('select_account consent');

    // Load previously authorized token from a file, if it exists.
    // The file token.json stores the user's access and refresh tokens, and is
    // created automatically when the authorization flow completes for the first
    // time.
    $tokenPath = 'api/token.json';
    if (file_exists($tokenPath)) {
        $accessToken = json_decode(file_get_contents($tokenPath), true);
        $client->setAccessToken($accessToken);
    }

    // If there is no previous token or it's expired.
    if ($client->isAccessTokenExpired()) {
        // Refresh the token if possible, else fetch a new one.
        if ($client->getRefreshToken()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
        } 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);
            $client->setAccessToken($accessToken);

            // Check to see if there was an error.
            if (array_key_exists('error', $accessToken)) {
                throw new Exception(join(', ', $accessToken));
            }
        }
        // Save the token to a file.
        if (!file_exists(dirname($tokenPath))) {
            mkdir(dirname($tokenPath), 0700, true);
        }
        file_put_contents($tokenPath, json_encode($client->getAccessToken()));
    }
    return $client;
}

// Get the API client and construct the service object.
$client = getClient();
$service = new Calendar($client);

// AJOUT À L'AGENDA :
$summary = $data_client['nom']; 
$description = $data_client['notes']; 
try{
    $event = new Google_Service_Calendar_Event(array(
      'summary' => $summary,
      'location' => '',
      'description' => $description,
      'start' => array(
        'date' => $date_debut,  //<============='2022-12-01'
    ),
      'end' => array(
        'date' => $date_fin,        //<============='2022-12-05'
      ),
      'recurrence' => array(),
      'attendees' => array(),
      'reminders' => array(),
    ));

    $calendarId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx@group.calendar.google.com';
    $event = $service->events->insert($calendarId, $event);
    /*printf('Event created: %s\n', $event->htmlLink);*/
}
catch(Exception $e) {
    // TODO(developer) - handle error appropriately
    echo 'Message: ' .$e->getMessage();
}
?>