-
pippuccio76
Senior Member
-
Posts: 478
Threads: 206
Joined: Jun 2017
Reputation:
2
05-18-2022, 12:50 PM
(This post was last modified: 05-18-2022, 12:53 PM by pippuccio76.)
hi , i try to create an application with google calendar , i run :
Code: composer require google/apiclient:^2.0
than create a controller :
PHP Code: <?php
namespace App\Controllers;
class Google_calendar extends BaseController {
public function __construct() {
helper(['form', 'url','filesystem']);
}
/** * Returns an authorized API client. * @return Google_Client the authorized client object */ private function getClient() { $client = new Google_Client(); $client->setApplicationName('Google Calendar API PHP Quickstart'); $client->setScopes(Google_Service_Calendar::CALENDAR_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; }
public function index() { // Get the API client and construct the service object. $client = $this->getClient(); $service = new Google_Service_Calendar($client); }
}//end class
composer don't autolad google class ?
-
pippuccio76
Senior Member
-
Posts: 478
Threads: 206
Joined: Jun 2017
Reputation:
2
(05-18-2022, 12:50 PM)pippuccio76 Wrote: hi , i try to create an application with google calendar , i run :
Code: composer require google/apiclient:^2.0
than create a controller :
PHP Code: <?php
namespace App\Controllers;
class Google_calendar extends BaseController {
public function __construct() {
helper(['form', 'url','filesystem']);
}
/** * Returns an authorized API client. * @return Google_Client the authorized client object */ private function getClient() { $client = new Google_Client(); $client->setApplicationName('Google Calendar API PHP Quickstart'); $client->setScopes(Google_Service_Calendar::CALENDAR_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; }
public function index() { // Get the API client and construct the service object. $client = $this->getClient(); $service = new Google_Service_Calendar($client); }
}//end class
composer don't autolad google class ?
-
pippuccio76
Senior Member
-
Posts: 478
Threads: 206
Joined: Jun 2017
Reputation:
2
05-19-2022, 03:42 AM
(This post was last modified: 05-19-2022, 03:51 AM by pippuccio76.)
(05-18-2022, 05:30 PM)kenjis Wrote: (05-18-2022, 12:50 PM)pippuccio76 Wrote: composer don't autolad google class ?
Composer do autoload google class if the class name is correct.
See https://github.com/googleapis/google-api...ic-example
$client = new Google\Client();
same error ...
solved by
use Google\Client;
use Google\Google_Service_Calendar;
solved by :
-
adil
Junior Member
-
Posts: 16
Threads: 6
Joined: Jul 2018
Reputation:
0
Did you finish the project?
if yes, can you provide the code?
-
pippuccio76
Senior Member
-
Posts: 478
Threads: 206
Joined: Jun 2017
Reputation:
2
12-19-2022, 02:10 PM
(This post was last modified: 12-19-2022, 02:14 PM by pippuccio76.)
(12-19-2022, 05:47 AM)adil Wrote: Did you finish the project?
if yes, can you provide the code?
this is my controller :
Code: <?php
namespace App\Controllers;
use App\Models\Google_autenticazioneModel;
use Google\Service\Calendar as Google_Service_Calendar ;
use Google\Service\Calendar\Event as Google_Service_Calendar_Event ;
use App\Libraries\Googleplus;
class Admin_google_calendar extends BaseController {
public function login()
{
$google_library =new Googleplus();
$google_client = $google_library->GetClient();
$login_button = '';
//recupero i dati google dal db
$google_utenticazione_model = new Google_autenticazioneModel();
$utente_google = $google_utenticazione_model->find(session()->get('admin_id'));
//print_r($_SESSION);
//die();
if(!$google_library->googleIsLogin())
{
$login_button = '<a class="btn btn-danger" href="'.$google_client->createAuthUrl().'">Google Login</a>';
$data['login_button'] = $login_button;
echo view('empty_view',$data);
echo view('admin/google_calendar/google_login');
}
else
{
return redirect()->to('/admin_google_calendar/show_calendar');
}
}
public function logout()
{
$google_library =new Googleplus();
$google_library->google_logout();
}
public function getCalendar() {
$google_library =new Googleplus();
if (!$google_library->googleIsLogin()) {
return redirect()->to('admin_google_calendar/login');
} else {
$google_client = $google_library->getClient();
//$client = googleGetClient();
$service = new Google_Service_Calendar($google_client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
//funziona
/*
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
*/
$optParams = array(
'maxResults' => 10,
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
'timeMin' => '2022-08-01T00:00:00-02:00',
'timeMax' => '2022-08-31T00:00:00-02:00',
);
$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);
}
}
}
}
// oauth method
public function oauth() {
$code = $this->input->get('code', true);
$this->oauthLogin($code);
return redirect()->to(base_url(), 'refresh');
}
// oauthLogin
public function oauthLogin($code) {
$google_library =new Googleplus();
$google_client = $google_library->googleGetClient();
$login = $google_client->authenticate($code);
if ($login) {
$token = $google_client->getAccessToken();
session()->set('google_calendar_access_token', $token);
session()->set('is_authenticate_user', TRUE);
return true;
}
}
public function show_calendar()
{
$data=[];
$google_library =new Googleplus();
if (!$google_library->googleIsLogin()) {
//session_destroy();
return redirect()->to('admin_google_calendar/login');
} else {
//DEBUG
//echo 'Inside';
//die();
$google_client = $google_library->googleGetClient();
//recupero i dati google dal db
$google_utenticazione_model = new Google_autenticazioneModel();
$utente_google = $google_utenticazione_model->find(session()->get('admin_id'));
$google_client->setAccessToken($utente_google->access_token);
$service = new Google_Service_Calendar($google_client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
);
$results = $service->events->listEvents($calendarId, $optParams);
$eventi = $results->getItems();
$lista_eventi= [];
$n=0;
foreach ($eventi as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
$end = $event->end->dateTime;
if (empty($start)) {
$end = $event->end->date;
}
$lista_eventi[$n]['id'] = $event->id;
$lista_eventi[$n]['title'] = $event->getSummary();
$lista_eventi[$n]['start'] = $start;
$lista_eventi[$n]['end'] = $end;
$lista_eventi[$n]['backgroundColor'] = "#00a65a";
$n++;
}
/* print_r($lista_eventi);
die();*/
}
$data['events'] = $lista_eventi;
echo view('empty_view',$data );
echo view('admin/google_calendar/show_calendar',$data);
}
public function carica_eventi_calendario_ajax()
{
$google_library =new Googleplus();
if (($this->request->getMethod() === 'post')){
$post = $this->request->getPost();
//print_r($post);
$google_client = $google_library->googleGetClient();
//recupero i dati google dal db
$google_utenticazione_model = new Google_autenticazioneModel();
$utente_google = $google_utenticazione_model->find(session()->get('admin_id'));
$google_client->setAccessToken($utente_google->access_token);
$service = new Google_Service_Calendar($google_client);
// Print the next 10 events on the user's calendar.
$calendarId = 'primary';
$optParams = array(
'orderBy' => 'startTime',
'singleEvents' => true,
'timeMin' => date('c'),
'timeMin' => $post['start'].'T00:00:00-02:00',
'timeMax' => $post['end'].'T00:00:00-02:00',
);
$results = $service->events->listEvents($calendarId, $optParams);
$eventi = $results->getItems();
$lista_eventi= [];
$n=0;
foreach ($eventi as $event) {
$start = $event->start->dateTime;
if (empty($start)) {
$start = $event->start->date;
}
$end = $event->end->dateTime;
if (empty($start)) {
$end = $event->end->date;
}
$lista_eventi[$n]['id'] = $event->id;
$lista_eventi[$n]['title'] = $event->getSummary();
$lista_eventi[$n]['start'] = $start;
$lista_eventi[$n]['end'] = $end;
$lista_eventi[$n]['backgroundColor'] = "#00a65a";
$n++;
}
echo json_encode($lista_eventi);
}else{
echo 'alert("dati non ricevuti")';
}
}//end carica_eventi_calendario_ajax
public function test_access_token()
{
$google_library =new Googleplus();
$google_library->googleIsLogin();
print_r($_SESSION);
}
public function logout_google($val=NULL)
{
$google_library =new Googleplus();
$google_library->google_logout();
return redirect()->to('admin_google_calendar/login');
}
}
This is the library :
Code: <?php
namespace App\Libraries;
// https://console.cloud.google.com/apis
/*
https://github.com/aididalam/CodeIgniter-Google-Calendar
*/
/*
https://myaccount.google.com/u/0/permissions?continue=https%3A%2F%2Fmyaccount.google.com%2Fu%2F0%2Fsecurity
*/
use Google\Client as Google_client;
use Google\Service\Calendar as Google_Service_Calendar ;
use Google\Service\Calendar\Event as Google_Service_Calendar_Event ;
use Google\Service\Oauth2 as Google_Service_Oauth2;
use App\Models\Google_autenticazioneModel;
class Googleplus
{
private $google_client;
public function __construct()
{
$this->google_client = $this->googleGetClient();
}
public function googleGetClient(){
$google_utenticazione_model = new Google_autenticazioneModel();
$google_client = new Google_client();
$google_client->setAuthConfig(WRITEPATH.'google_calendar/credentials.json');
$google_client->setRedirectUri(base_url().'/admin_google_calendar/login');
$google_client->setAccessType('offline');
//$google_client->setPrompt('consent');
$google_client->addScope('email');
$google_client->addScope('profile');
$google_client->addScope(Google_Service_Calendar::CALENDAR);
$google_client->setPrompt('consent');
if(isset($_GET["code"]))
{
$token = $google_client->authenticate($_GET["code"]);
if(!isset($token["error"]))
{
$google_client->setAccessToken($token['access_token']);
$dati_to_update = [
'access_token' => $token['access_token'],
];
$google_utenticazione_model->update(session()->get('admin_id'), $dati_to_update);
if(isset($token['refresh_token'])){
$dati_to_update = [
'refresh_token' => $token['refresh_token'],
];
$google_utenticazione_model->update(session()->get('admin_id'), $dati_to_update);
}
$google_service = new Google_Service_Oauth2($google_client);
$data_session = $google_service->userinfo->get();
$current_datetime = date('Y-m-d H:i:s');
//insert data
session()->set('user_data' , array(
'login_oauth_uid' => $data_session['id'],
'first_name' => $data_session['given_name'],
'last_name' => $data_session['family_name'],
'email_address' => $data_session['email'],
'profile_picture' => $data_session['picture'],
'created_at' => $data_session
));
}
}
//session()->set('google_client',var_dump($google_client));
return $google_client;
}//END get_Client
// check login session
public function googleIsLogin() {
$google_utenticazione_model = new Google_autenticazioneModel();
$utente_google = $google_utenticazione_model->find(session()->get('admin_id'));
if ($utente_google->access_token) {
$this->google_client->setAccessToken($utente_google->access_token);
if ($this->google_client->isAccessTokenExpired()) {
if ($this->google_client->getRefreshToken()) {
$token = $this->google_client->getRefreshToken();
$this->google_client->fetchAccessTokenWithRefreshToken($token);
$dati_to_update = [
'access_token' => $token['access_token'],
];
$google_utenticazione_model->update(session()->get('admin_id'), $dati_to_update);
if(isset($token['refresh_token'])){
$dati_to_update = [
'refresh_token' => $token['refresh_token'],
];
$google_utenticazione_model->update(session()->get('admin_id'), $dati_to_update);
}
//DEBUg
session()->set('tipo_access_token','getRefreshToken vuoto');
return TRUE;
}elseif( $this->google_client->refreshToken($utente_google->refresh_token)){
//var_dump($refresh_token);
$token=$this->google_client->getAccessToken();
$this->google_client->setAccessToken($token['access_token']);
//inserisco i valori nel db
$dati_to_update = [
'access_token' => $token['access_token'],
];
$google_utenticazione_model->update(session()->get('admin_id'), $dati_to_update);
if(isset($token['refresh_token'])){
$dati_to_update = [
'refresh_token' => $token['refresh_token'],
];
$google_utenticazione_model->update(session()->get('admin_id'), $dati_to_update);
}
return TRUE;
//DEBUg
session()->set('tipo_access_token','access_token');
}else{
//DEBUg
session()->set('tipo_access_token','FALSE1');
return FALSE;
}
//DEBUg
session()->set('tipo_access_token','getRefreshToken vuoto');
return TRUE;
}
//DEBUg
session()->set('tipo_access_token','access_token');
return TRUE;
}
//DEBUg
session()->set('tipo_access_token','FALSE2');
return FALSE;
}//end isLogin
public function google_logout()
{
$google_utenticazione_model = new Google_autenticazioneModel();
$dati_to_update = [
'access_token' => NULL
];
$google_utenticazione_model->update(session()->get('admin_id'),$dati_to_update);
}//end google_logout
public function loginUrl()
{
return $this->google_client->createAuthUrl();
}
public function getAccessToken()
{
return $this->google_client->getAccessToken();
}
public function refreshToken()
{
$this->google_client->getRefreshToken();
$token = $this->getAccessToken();
$google_utenticazione_model = new Google_autenticazioneModel();
$dati_to_update = [
'access_token' => $token['access_token']
];
$google_utenticazione_model->update(1,$dati_to_update);
}
public function revokeToken()
{
$google_utenticazione_model = new Google_autenticazioneModel();
$dati_to_update = [
'access_token' => NULL
];
$google_utenticazione_model->update(1,$dati_to_update);
return $this->google_client->revokeToken();
}
public function getUser()
{
$google_ouath = new Google_Service_Oauth2($this->google_client);
return (object)$google_ouath->userinfo->get();
}
public function isAccessTokenExpired()
{
return $this->google_client->isAccessTokenExpired();
}
public function getClient()
{
return $this->google_client;
}
// actionEvent
public function actionEvent($calendarId, $data) {
$google_client = $this->googleGetClient();
$google_utenticazione_model = new Google_autenticazioneModel();
$utente_google = $google_utenticazione_model->find(session()->get('admin_id'));
$google_client->setAccessToken($utente_google->access_token);
$google_service_calendar= new Google_Service_Calendar($google_client);
//Date Format: 2016-06-18T17:00:00+03:00
$event = new Google_Service_Calendar_Event(
array(
'summary' => $data['summary'],
'description' => $data['description'],
'start' => array(
'dateTime' => $data['start'],
'timeZone' => 'Europe/Rome',
),
'end' => array(
'dateTime' => $data['start'],
'timeZone' => 'Europe/Rome',
),
'attendees' => array(
array('email' => '[email protected]'),
),
)
);
return $google_service_calendar->events->insert($calendarId, $event);
}
// add google calendar event
public function addEvent($titolo,$data_inizio,$ora_inizio,$data_fine,$ora_fine,$descrizione) {
$json = array();
$calendarId = 'primary';
//$calendarId = '[email protected]';
if(empty(trim($titolo))){
$json['error']['summary'] = 'Please enter summary';
}
// start date time validation
if(empty(trim($data_inizio)) && empty($ora_inizio)){
$json['error']['startdate'] = 'Please enter start date time';
}
if(empty(trim($data_fine)) && empty($ora_fine)){
$json['error']['enddate'] = 'Please enter end date time';
}
if(empty(trim($descrizione))){
$json['error']['description'] = 'Please enter description';
}
if(empty($json['error'])){
$event = array(
'summary' => $titolo,
'start' => $data_inizio.'T'.$ora_inizio.':00+02:00',
'end' => $data_fine.'T'.$ora_fine.':00+02:00',
'description' => $descrizione,
);
$data = $this->actionEvent($calendarId, $event);
if ($data->status == 'confirmed') {
$json['message'] = 1;
} else {
$json['message'] = 0;
}
}
//$this->output->set_header('Content-Type: application/json');
return json_encode($json);
}//end addEvent
}
|