Api google calendar php -> suppression evenement

Fermé
tichritophe Messages postés 6 Date d'inscription mardi 29 novembre 2022 Statut Membre Dernière intervention 23 décembre 2022 - 29 nov. 2022 à 23:03
 tichritophe - 10 févr. 2023 à 22:42

Bonjour,

en cherchant sur le net, j'ai pu trouver des morceaux de code (étant amateur) pour me connecte et ajouter depuis PHP des événements sur un agenda google.

J'ai pu le modifier et celui répond comment je le souhaite pour un petit projet interne.

Maintenant que j'arrive à ajouter des événements, la suite serait de pouvoir les supprimer et la surprise.

Je ne trouve pas de tuto m'expliquât la suppression en PHP.

Est-ce qu'une âme charitable pourrait m'orienter ou m'aider pour l'explication ?

En vous remerciant

Christophe


Windows / Chrome 107.0.0.0

A voir également:

9 réponses

jordane45 Messages postés 38144 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 21 avril 2024 4 650
30 nov. 2022 à 07:09

Bonjour

La documentation de l'API devrait te permettre de trouver ton bonheur

https://developers.google.com/calendar/api/v3/reference/events/delete#php


1
tichritophe Messages postés 6 Date d'inscription mardi 29 novembre 2022 Statut Membre Dernière intervention 23 décembre 2022
30 nov. 2022 à 20:34

Merci Jordan 45, mais comme je disais, n'étant pas à l'origine de la création du script, je ne sais où insérer et comment adapter cette ligne de code :-(

je connais l'id de l'élément à supprimer que je peux envoyer à la requête en get ou en session.

Si pourrait m'accorder quelque peu de ton temps pour regarder juste mon script et m'orienter ce serait génial :-)

0
jordane45 Messages postés 38144 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 21 avril 2024 4 650 > tichritophe Messages postés 6 Date d'inscription mardi 29 novembre 2022 Statut Membre Dernière intervention 23 décembre 2022
30 nov. 2022 à 21:15

On peut essayer de t'aider, mais pour ça, il faudrait d'abord que tu nous montre le code...

0
tichritophe Messages postés 6 Date d'inscription mardi 29 novembre 2022 Statut Membre Dernière intervention 23 décembre 2022
30 nov. 2022 à 21:30

Oui bien sur je comprend

Donc ma page d'index.php

<?php
// Include configuration file
include_once 'config.php';

$postData = '';
if(!empty($_SESSION['postData'])){
    $postData = $_SESSION['postData'];
    unset($_SESSION['postData']);
}

$status = $statusMsg = '';
if(!empty($_SESSION['status_response'])){
    $status_response = $_SESSION['status_response'];
    $status = $status_response['status'];
    $statusMsg = $status_response['status_msg'];
    
    unset($_SESSION['status_response']);
}
?>

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Add Event to Google Calendar using PHP by CodexWorld</title>
<meta charset="utf-8">

<!-- Bootstrap library -->
<link href="css/bootstrap.min.css" rel="stylesheet">

<!-- Stylesheet file -->
<link rel="stylesheet" href="css/style.css">

</head>
<body>
<div class="container">
    <h1>ADD EVENT TO GOOGLE CALENDAR</h1>
	
	<div class="wrapper">
		
		<!-- Status message -->
        <?php if(!empty($statusMsg)){ ?>
            <div class="alert alert-<?php echo $status; ?>"><?php echo $statusMsg; ?></div>
        <?php } ?>
		
		<div class="col-md-12">
            <form method="post" action="addEvent.php" class="form">
                <div class="form-group">
                    <label>Event Title</label>
                    <input type="text" class="form-control" name="title" value="<?php echo !empty($postData['title'])?$postData['title']:''; ?>" required="">
                </div>
                <div class="form-group">
                    <label>Event Description</label>
					<textarea name="description" class="form-control"><?php echo !empty($postData['description'])?$postData['description']:''; ?></textarea>
                </div>
				<div class="form-group">
                    <label>Location</label>
					<input type="text" name="location" class="form-control" value="<?php echo !empty($postData['location'])?$postData['location']:''; ?>">
                </div>
                <div class="form-group">
                    <label>Date</label>
                    <input type="date" name="date" class="form-control" value="<?php echo !empty($postData['date'])?$postData['date']:''; ?>" required="">
					<label>Datefin</label>
                    <input type="date" name="datefin" class="form-control" value="<?php echo !empty($postData['datefin'])?$postData['datefin']:''; ?>" required="">
                </div>
				<div class="form-group time">
                    <label>Time</label>
                    <input type="time" name="time_from" class="form-control" value="<?php echo !empty($postData['time_from'])?$postData['time_from']:''; ?>">
					<span>TO</span>
					<input type="time" name="time_to" class="form-control" value="<?php echo !empty($postData['time_to'])?$postData['time_to']:''; ?>">
                </div>
				<div class="form-group">
					<input type="submit" class="form-control btn-primary" name="submit" value="Ajouter Evenement"/>
				</div>
            </form>
        </div>
	</div>
</div>
</body>
</html>

Ensuite ca envoi sur ma page addevent.php

<?php    
// Include database configuration file
require_once 'dbConfig.php';

$postData = $statusMsg = $valErr = '';
$status = 'danger';

// If the form is submitted
if(isset($_POST['submit'])){
    
    // Get event info
    $_SESSION['postData'] = $_POST;
    $title = !empty($_POST['title'])?trim($_POST['title']):'';
    $description = !empty($_POST['description'])?trim($_POST['description']):'';
    $location = !empty($_POST['location'])?trim($_POST['location']):'';
    $date = !empty($_POST['date'])?trim($_POST['date']):'';
      $datefin = !empty($_POST['datefin'])?trim($_POST['datefin']):'';

	$time_from = !empty($_POST['time_from'])?trim($_POST['time_from']):'';
    $time_to = !empty($_POST['time_to'])?trim($_POST['time_to']):'';
    
    // Validate form input fields
    if(empty($title)){
        $valErr .= 'Please enter event title.<br/>';
    }
    if(empty($date)){
        $valErr .= 'Please enter event date.<br/>';
    }
      if(empty($datefin)){
        $valErr .= 'Please enter event date.<br/>';
    }
    // Check whether user inputs are empty
    if(empty($valErr)){
        // Insert data into the database
        $sqlQ = "INSERT INTO events (title,description,location,date,datefin,time_from,time_to,created) VALUES (?,?,?,?,?,?,?,NOW())";
        $stmt = $db->prepare($sqlQ);
        $stmt->bind_param("sssssss", $db_title, $db_description, $db_location, $db_date,$db_datefin, $db_time_from, $db_time_to);
        $db_title = $title;
        $db_description = $description;
        $db_location = $location;
        $db_date = $date;
		 $db_datefin = $datefin;

        $db_time_from = $time_from;
        $db_time_to = $time_to;
        $insert = $stmt->execute();
        
        if($insert){
            $event_id = $stmt->insert_id;
            
            unset($_SESSION['postData']);
            
            // Store event ID in session
            $_SESSION['last_event_id'] = $event_id;
            
            header("Location: $googleOauthURL");
            exit();
        }else{
            $statusMsg = 'Something went wrong, please try again after some time.';
        }
    }else{
        $statusMsg = '<p>Please fill all the mandatory fields:</p>'.trim($valErr, '<br/>');
    }
}else{
    $statusMsg = 'Form submission failed!';
}

$_SESSION['status_response'] = array('status' => $status, 'status_msg' => $statusMsg);

header("Location: index.php");
exit();
?>

qui appel la page google_calendar_event_sync.php

<?php
// Include Google calendar api handler class
include_once 'GoogleCalendarApi.class.php';
    
// Include database configuration file
require_once 'dbConfig.php';

$statusMsg = '';
$status = 'danger';
if(isset($_GET['code'])){
    // Initialize Google Calendar API class
    $GoogleCalendarApi = new GoogleCalendarApi();
    
    // Get event ID from session
    $event_id = $_SESSION['last_event_id'];

    if(!empty($event_id)){
        
        // Fetch event details from database
        $sqlQ = "SELECT * FROM events WHERE id = ?";
        $stmt = $db->prepare($sqlQ); 
        $stmt->bind_param("i", $db_event_id);
        $db_event_id = $event_id;
        $stmt->execute();
        $result = $stmt->get_result();
        $eventData = $result->fetch_assoc();
        
        if(!empty($eventData)){
            $calendar_event = array(
                'summary' => $eventData['title'],
                'location' => $eventData['location'],
                'description' => $eventData['description']
            );
            
            $event_datetime = array(
                'event_date' => $eventData['date'],
			    'event_datefin' => $eventData['datefin'],

                'start_time' => $eventData['time_from'],
                'end_time' => $eventData['time_to']
            );
            
            // Get the access token
            $access_token_sess = $_SESSION['google_access_token'];
            if(!empty($access_token_sess)){
                $access_token = $access_token_sess;
            }else{
                $data = $GoogleCalendarApi->GetAccessToken(GOOGLE_CLIENT_ID, REDIRECT_URI, GOOGLE_CLIENT_SECRET, $_GET['code']);
                $access_token = $data['access_token'];
                $_SESSION['google_access_token'] = $access_token;
            }
            
            if(!empty($access_token)){
                try {
                    // Get the user's calendar timezone
                    $user_timezone = $GoogleCalendarApi->GetUserCalendarTimezone($access_token);
                
                    // Create an event on the primary calendar
                    $google_event_id = $GoogleCalendarApi->CreateCalendarEvent($access_token, 'primary', $calendar_event, 0, $event_datetime, $user_timezone);
                    
                    //echo json_encode([ 'event_id' => $event_id ]);
                    
                    if($google_event_id){
                        // Update google event reference in the database
                        $sqlQ = "UPDATE events SET google_calendar_event_id=? WHERE id=?";
                        $stmt = $db->prepare($sqlQ);
                        $stmt->bind_param("si", $db_google_event_id, $db_event_id);
                        $db_google_event_id = $google_event_id;
                        $db_event_id = $event_id;
                        $update = $stmt->execute();
                        
                        unset($_SESSION['last_event_id']);
                        unset($_SESSION['google_access_token']);
                        
                        $status = 'success';
                        $statusMsg = '<p>Event #'.$event_id.' has been added to Google Calendar successfully!</p>';
                        $statusMsg .= '<p><a href="https://calendar.google.com/calendar/" target="_blank">Open Calendar</a>';
                    }
                } catch(Exception $e) {
                    //header('Bad Request', true, 400);
                    //echo json_encode(array( 'error' => 1, 'message' => $e->getMessage() ));
                    $statusMsg = $e->getMessage();
                }
            }else{
                $statusMsg = 'Failed to fetch access token!';
            }
        }else{
            $statusMsg = 'Event data not found!';
        }
    }else{
        $statusMsg = 'Event reference not found!';
    }
    
    $_SESSION['status_response'] = array('status' => $status, 'status_msg' => $statusMsg);
    
    header("Location: index.php");
    exit();
}
?>

qu'il l'interprete grace a la page GoogleCalendarApi.class

<?php
/**
 *
 * This Google Calendar API handler class is a custom PHP library to handle the Google Calendar API calls.
 *
 * @class		GoogleCalendarApi
 * @author		CodexWorld
 * @link		http://www.codexworld.com
 * @version		1.0
 */
class GoogleCalendarApi {
	const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'; //https://oauth2.googleapis.com/token
	const CALENDAR_TIMEZONE_URI = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
	const CALENDAR_LIST = 'https://www.googleapis.com/calendar/v3/users/me/calendarList';
	const CALENDAR_EVENT = 'https://www.googleapis.com/calendar/v3/calendars/';
	
	//var $baseURL		= '';
    
	function __construct($params = array()) {
		if (count($params) > 0){
			$this->initialize($params);		
		}
	}
	
	function initialize($params = array()) {
		if (count($params) > 0){
			foreach ($params as $key => $val){
				if (isset($this->$key)){
					$this->$key = $val;
				}
			}		
		}
	}
	
	public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
		$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, self::OAUTH2_TOKEN_URI);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_POST, 1);		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		
		if ($http_code != 200) {
			$error_msg = 'Failed to receieve access token';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}
			
		return $data;
	}

	public function GetUserCalendarTimezone($access_token) {
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, self::CALENDAR_TIMEZONE_URI);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));	
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		
		if ($http_code != 200) {
			$error_msg = 'Failed to fetch timezone';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}

		return $data['value'];
	}

	public function GetCalendarsList($access_token) {
		$url_parameters = array();

		$url_parameters['fields'] = 'items(id,summary,timeZone)';
		$url_parameters['minAccessRole'] = 'owner';

		$url_calendars = self::CALENDAR_LIST.'?'. http_build_query($url_parameters);
		
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $url_calendars);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));	
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		
		if ($http_code != 200) {
			$error_msg = 'Failed to get calendars list';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}

		return $data['items'];
	}

	public function CreateCalendarEvent($access_token, $calendar_id, $event_data, $all_day, $event_datetime, $event_timezone) {
		$apiURL = self::CALENDAR_EVENT . $calendar_id . '/events';
		
		$curlPost = array();
		
		if(!empty($event_data['summary'])){
			$curlPost['summary'] = $event_data['summary'];
		}
		
		if(!empty($event_data['location'])){
			$curlPost['location'] = $event_data['location'];
		}
		
		if(!empty($event_data['description'])){
			$curlPost['description'] = $event_data['description'];
		}
		
		$event_datefin = !empty($event_datetime['event_datefin'])?$event_datetime['event_datefin']:date("Y-m-d");
		$event_date = !empty($event_datetime['event_date'])?$event_datetime['event_date']:date("Y-m-d");
		$start_time = !empty($event_datetime['start_time'])?$event_datetime['start_time']:date("H:i:s");
		$end_time = !empty($event_datetime['end_time'])?$event_datetime['end_time']:date("H:i:s");

		if($all_day == 1){
			$curlPost['start'] = array('date' => $event_date);
			$curlPost['end'] = array('date' => $event_date);
		}else{
			$timezone_offset = $this->getTimezoneOffset($event_timezone);
			$timezone_offset = !empty($timezone_offset)?$timezone_offset:'07:00';
			$dateTime_start = $event_date.'T'.$start_time.$timezone_offset;
			$dateTime_end = $event_datefin.'T'.$end_time.$timezone_offset;
			
			$curlPost['start'] = array('dateTime' => $dateTime_start, 'timeZone' => $event_timezone);
			$curlPost['end'] = array('dateTime' => $dateTime_end, 'timeZone' => $event_timezone);
		}
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $apiURL);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_POST, 1);		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));	
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		
		if ($http_code != 200) {
			$error_msg = 'Failed to create event';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}

		return $data['id'];
	}
	
	private function getTimezoneOffset($timezone = 'America/Los_Angeles'){
		$current   = timezone_open($timezone);
		$utcTime  = new \DateTime('now', new \DateTimeZone('UTC'));
		$offsetInSecs =  timezone_offset_get($current, $utcTime);
		$hoursAndSec = gmdate('H:i', abs($offsetInSecs));
		return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
	}
}
?>

J'ai bien sur mon fichier config et dbconfig ou les renseignements sont intégrés pour la connexion à la base de donnée et m'authentifier à Google.

J'aimerais une page qui supprimer l'élément du calendrier choisit grâce à l'id de l'événement.

Je n'ai pas encore construit mon tableau, mais en gros celui-ci listera tous mes événements présents dans ma base de donnée et lorsque je cliquerai sur supprimer, celui-ci se supprimera.

Je cherche juste a comprendre comment faire pour créer se script :-)

0
jordane45 Messages postés 38144 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 21 avril 2024 4 650
Modifié le 30 nov. 2022 à 22:23

Je pense que tu pourras faire une fonction dans le fichier  GoogleCalendarApi.class du genre

public function DeleteCalendarEvent($access_token, $calendar_id, $event_id) {
    //DELETE https://www.googleapis.com/calendar/v3/calendars/calendarId/events/eventId
		$apiURL = self::CALENDAR_EVENT . $calendar_id . '/events/' . $event_id;
		

		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $apiURL);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_POST, 1);	// Si ça ne marche pas, remplacer par la ligne ci-dessous
        //curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); //	
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));	
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		
		if ($http_code != 200) {
			$error_msg = 'Failed to delete event';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}

		return $data['id'];
	}
0
tichritophe Messages postés 6 Date d'inscription mardi 29 novembre 2022 Statut Membre Dernière intervention 23 décembre 2022
2 déc. 2022 à 00:02

Merci de ta réponse, je vais essayer de me mettre début de semaine pour essayer ça.

0

Alors après quelque essai ca ne fonctionne pas, mais ça avance, je pense.

J'ai créé un nouveau répertoire juste pour la suppression.

ça revient bien jusqu'à la page d'index sans erreurs, mais ça ne se supprime pas.

j'ai ma page d'index

<?php
// Include configuration file
include_once 'config.php';

$postData = '';
if(!empty($_SESSION['postData'])){
    $postData = $_SESSION['postData'];
    unset($_SESSION['postData']);
}

$status = $statusMsg = '';
if(!empty($_SESSION['status_response'])){
    $status_response = $_SESSION['status_response'];
    $status = $status_response['status'];
    $statusMsg = $status_response['status_msg'];
    
    unset($_SESSION['status_response']);
}
?>

<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Add Event to Google Calendar using PHP by CodexWorld</title>
<meta charset="utf-8">

<!-- Bootstrap library -->
<link href="css/bootstrap.min.css" rel="stylesheet">

<!-- Stylesheet file -->
<link rel="stylesheet" href="css/style.css">

</head>
<body>
<div class="container">
    <h1>ADD EVENT TO GOOGLE CALENDAR</h1>
	
	<div class="wrapper">
		
		<!-- Status message -->
        <?php if(!empty($statusMsg)){ ?>
            <div class="alert alert-<?php echo $status; ?>"><?php echo $statusMsg; ?></div>
        <?php } ?>
		
		<div class="col-md-12">
            <form method="post" action="addEvent.php" class="form">
                <div class="form-group">
                    <label>Event Title</label>
                    <input type="text" class="form-control" name="idevenement" value="<?php echo !empty($postData['idevenement'])?$postData['idevenement']:''; ?>" required="">
                </div>
                
				
              
				
				<div class="form-group">
					<input type="submit" class="form-control btn-primary" name="submit" value="Ajouter Evenement"/>
				</div>
            </form>
        </div>
	</div>
</div>
</body>
</html>

qui envoi mon inscription dans mon fichier addEvent.php

<?php    
// Include database configuration file
require_once 'dbConfig.php';

$postData = $statusMsg = $valErr = '';
$status = 'danger';

// If the form is submitted
if(isset($_POST['submit'])){
    
    // Get event info
    $_SESSION['postData'] = $_POST;
    $idevenement = !empty($_POST['idevenement'])?trim($_POST['idevenement']):'';
    
    // Validate form input fields
    if(empty($idevenement)){
        $valErr .= 'Please enter event title.<br/>';
    }
    // Check whether user inputs are empty
    if(empty($valErr)){
        // Insert data into the database
       
            
            // Store event ID in session
            $_SESSION['idevenement'] = $idevenement;
            
            header("Location: $googleOauthURL");
            exit();
        }else{
            $statusMsg = 'Something went wrong, please try again after some time.';
        }
    }else{
        $statusMsg = '<p>Please fill all the mandatory fields:</p>'.trim($valErr, '<br/>');
    }

$_SESSION['status_response'] = array('status' => $status, 'status_msg' => $statusMsg);

header("Location: index.php");
exit();
?>

avec le fichier config ou j'ai bien recrée une redirection sur le nouveau repertoire.

et donc reviens vers la page google_calendar_event_sync.php

<?php
// Include Google calendar api handler class
include_once 'GoogleCalendarApi.class.php';
    
// Include database configuration file
require_once 'dbConfig.php';

$statusMsg = '';
$status = 'danger';
    // Initialize Google Calendar API class
    $GoogleCalendarApi = new GoogleCalendarApi();
    
    // Get event ID from session
    $event_id = $_SESSION['idevenement'];

    if(!empty($event_id)){
        
        // Fetch event details from database
       
        
        if(!empty($eventData)){
           
          
            
            // Get the access token
            $access_token_sess = $_SESSION['google_access_token'];
            if(!empty($access_token_sess)){
                $access_token = $access_token_sess;
            }else{
                $data = $GoogleCalendarApi->GetAccessToken(GOOGLE_CLIENT_ID, REDIRECT_URI, GOOGLE_CLIENT_SECRET, $_GET['code']);
                $access_token = $data['access_token'];
                $_SESSION['google_access_token'] = $access_token;
            }
            
            if(!empty($access_token)){
                try {
                    // Get the user's calendar timezone
                    $user_timezone = $GoogleCalendarApi->GetUserCalendarTimezone($access_token);
                
                    // Create an event on the primary calendar
                    $google_event_id = $GoogleCalendarApi->DeleteCalendarEvent($access_token, 'primary', $event_id);
                    
                    //echo json_encode([ 'event_id' => $event_id ]);
                    
                   
                } catch(Exception $e) {
                    //header('Bad Request', true, 400);
                    //echo json_encode(array( 'error' => 1, 'message' => $e->getMessage() ));
                    $statusMsg = $e->getMessage();
                }
            }else{
                $statusMsg = 'Failed to fetch access token!';
            }
        }
    }else{
        $statusMsg = 'Event reference not found!';
    }
    
    $_SESSION['status_response'] = array('status' => $status, 'status_msg' => $statusMsg);
    
    header("Location: index.php");
    exit();

?>

avec le fichier GoogleCalendarApi.class.php

<?php
/**
 *
 * This Google Calendar API handler class is a custom PHP library to handle the Google Calendar API calls.
 *
 * @class		GoogleCalendarApi
 * @author		CodexWorld
 * @link		http://www.codexworld.com
 * @version		1.0
 */
class GoogleCalendarApi {
	const OAUTH2_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'; //https://oauth2.googleapis.com/token
	const CALENDAR_TIMEZONE_URI = 'https://www.googleapis.com/calendar/v3/users/me/settings/timezone';
	const CALENDAR_LIST = 'https://www.googleapis.com/calendar/v3/users/me/calendarList';
	const CALENDAR_EVENT = 'https://www.googleapis.com/calendar/v3/calendars/';
	
	//var $baseURL		= '';
    
	function __construct($params = array()) {
		if (count($params) > 0){
			$this->initialize($params);		
		}
	}
	
	function initialize($params = array()) {
		if (count($params) > 0){
			foreach ($params as $key => $val){
				if (isset($this->$key)){
					$this->$key = $val;
				}
			}		
		}
	}
	
	public function GetAccessToken($client_id, $redirect_uri, $client_secret, $code) {
		$curlPost = 'client_id=' . $client_id . '&redirect_uri=' . $redirect_uri . '&client_secret=' . $client_secret . '&code='. $code . '&grant_type=authorization_code';
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, self::OAUTH2_TOKEN_URI);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_POST, 1);		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		
		if ($http_code != 200) {
			$error_msg = 'Failed to receieve access token';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}
			
		return $data;
	}

	public function GetUserCalendarTimezone($access_token) {
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, self::CALENDAR_TIMEZONE_URI);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));	
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		
		if ($http_code != 200) {
			$error_msg = 'Failed to fetch timezone';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}

		return $data['value'];
	}

	public function GetCalendarsList($access_token) {
		$url_parameters = array();

		$url_parameters['fields'] = 'items(id,summary,timeZone)';
		$url_parameters['minAccessRole'] = 'owner';

		$url_calendars = self::CALENDAR_LIST.'?'. http_build_query($url_parameters);
		
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $url_calendars);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);	
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token));	
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
		
		if ($http_code != 200) {
			$error_msg = 'Failed to get calendars list';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}

		return $data['items'];
	}

	public function CreateCalendarEvent($access_token, $calendar_id, $event_data, $all_day, $event_datetime, $event_timezone) {
		$apiURL = self::CALENDAR_EVENT . $calendar_id . '/events';
		
		$curlPost = array();
		
		if(!empty($event_data['summary'])){
			$curlPost['summary'] = $event_data['summary'];
		}
		
		if(!empty($event_data['location'])){
			$curlPost['location'] = $event_data['location'];
		}
		
		if(!empty($event_data['description'])){
			$curlPost['description'] = $event_data['description'];
		}
		
		$event_datefin = !empty($event_datetime['event_datefin'])?$event_datetime['event_datefin']:date("Y-m-d");
		$event_date = !empty($event_datetime['event_date'])?$event_datetime['event_date']:date("Y-m-d");
		$start_time = !empty($event_datetime['start_time'])?$event_datetime['start_time']:date("H:i:s");
		$end_time = !empty($event_datetime['end_time'])?$event_datetime['end_time']:date("H:i:s");

		if($all_day == 1){
			$curlPost['start'] = array('date' => $event_date);
			$curlPost['end'] = array('date' => $event_date);
		}else{
			$timezone_offset = $this->getTimezoneOffset($event_timezone);
			$timezone_offset = !empty($timezone_offset)?$timezone_offset:'07:00';
			$dateTime_start = $event_date.'T'.$start_time.$timezone_offset;
			$dateTime_end = $event_datefin.'T'.$end_time.$timezone_offset;
			
			$curlPost['start'] = array('dateTime' => $dateTime_start, 'timeZone' => $event_timezone);
			$curlPost['end'] = array('dateTime' => $dateTime_end, 'timeZone' => $event_timezone);
		}
		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $apiURL);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_POST, 1);		
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));	
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		
		if ($http_code != 200) {
			$error_msg = 'Failed to create event';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}

		return $data['id'];
	}
	
	public function DeleteCalendarEvent($access_token, $calendar_id, $event_id) {
    //DELETE https://www.googleapis.com/calendar/v3/calendars/calendarId/events/eventId
		$apiURL = self::CALENDAR_EVENT . $calendar_id . '/events/' . $event_id;
		

		$ch = curl_init();		
		curl_setopt($ch, CURLOPT_URL, $apiURL);		
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);		
		curl_setopt($ch, CURLOPT_POST, 1);	// Si ça ne marche pas, remplacer par la ligne ci-dessous
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");//
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer '. $access_token, 'Content-Type: application/json'));	
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($curlPost));	
		$data = json_decode(curl_exec($ch), true);
		$http_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);		
		
		if ($http_code != 200) {
			$error_msg = 'Failed to delete event';
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			throw new Exception('Error '.$http_code.': '.$error_msg);
		}

		return $data['id'];
	}
	
	private function getTimezoneOffset($timezone = 'America/Los_Angeles'){
		$current   = timezone_open($timezone);
		$utcTime  = new \DateTime('now', new \DateTimeZone('UTC'));
		$offsetInSecs =  timezone_offset_get($current, $utcTime);
		$hoursAndSec = gmdate('H:i', abs($offsetInSecs));
		return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
	}
}
?>
0

Vous n’avez pas trouvé la réponse que vous recherchez ?

Posez votre question

Bonjour à tous, pour ce qui suivre, je n'ai toujours pas trouvé ma solution, mais je ne désespère pas. :-)

Si quelqu'un voit mon souci et peut m'orienter ça serait génial :-)

0
tichritophe Messages postés 6 Date d'inscription mardi 29 novembre 2022 Statut Membre Dernière intervention 23 décembre 2022
21 déc. 2022 à 23:01

Bonjour a tous je me permet de relancer savoir si quelqu'un  pourrai m'orienter  vers la solution?

En vous remerciant davance car mon projet ne peux avancer temo que je narrive pas la suppression d'événement. 

Merci d'avance 

0
jordane45 Messages postés 38144 Date d'inscription mercredi 22 octobre 2003 Statut Modérateur Dernière intervention 21 avril 2024 4 650
21 déc. 2022 à 23:11

Bonjour

Il faudrait que tu retires les redirections que tu as mis dans ton script et que tu essayes de voir le résultat des appels que tu fais à l'API ça devrait te donner un minima un message d'erreur expliquant pourquoi ça ne fonctionne pas.

0
tichritophe Messages postés 6 Date d'inscription mardi 29 novembre 2022 Statut Membre Dernière intervention 23 décembre 2022
23 déc. 2022 à 19:02

Merci jordane45, j'essaie ça après les fêtes et je reviens vers toi te dire se qu'il en es. Merci beaucoup.

0

Bonjour à tous, je n'avais pas encore eu le temps de revenir après les fêtes.

J'ai avancé un peu sur mon projet avec la programmation pour quelque onglet de mon projet 

Pour la partie agenda calendar l'insert fonctionne parfaitement

la suppression toujours pas trouvée mon problème.

je vais essayer de reprendre un projet vierge juste pour la suppression voir si j'arrive a quelque chose :-)

0

Bonjour à tous,

je viens vous donner quelque petite nouvelle :-)

d'abord merci à jordane45 qui a su me guider sur la bonne voix :-)

Je commence à réussir à ajouter, supprimer et modifier.

J'ai une déco quelques fois, mais je vais réussir à trouver, je pense.

J'essayerai de vous faire une vidéo de mon projet une fois finit

0