Last active
July 2, 2018 03:19
-
-
Save hrsetyono/5d8623bd8f28da3e282441ce1314f022 to your computer and use it in GitHub Desktop.
PHP Google Calendar API with Service Accounts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
IMPORTANT! | |
If you came here from my WP Plugin (https://github.com/hrsetyono/google-calendar-api), you don't need to require the API Client. | |
Aside from that, you need to download the client from https://github.com/google/google-api-php-client/releases | |
Put it in this directory, then uncomment the require_once code below. | |
*/ | |
// require_once 'vendor/autoload.php'; | |
class MyCalendar { | |
private $client; | |
private $calendar_id = 'your-calendar-id@gmail.com'; // find this in Calendar Settings > Click the calendar in sidebar > Integrate | |
function __construct() { | |
$this->client = new Google_Client(); | |
/* | |
The one you download when creating Service Account. Put it in the same folder as this file | |
In production, please do not put the file openly like this. Use Environment Variables instead | |
If you do that, use getenv() instead of file_exists() | |
Example: https://github.com/google/google-api-php-client/blob/master/examples/service-account.php | |
*/ | |
$cred = __DIR__ . '/service-creds.json'; | |
if( file_exists($cred) ) { | |
$this->client->setAuthConfig( $cred ); | |
$this->client->addScope( Google_Service_Calendar::CALENDAR_READONLY ); | |
} else { | |
return false; | |
} | |
} | |
function get() { | |
$args = array( | |
'orderBy' => 'startTime', | |
'singleEvents' => TRUE, | |
'timeMax' => date('c', strtotime('+6 day') ) | |
); | |
$service = new Google_Service_Calendar( $this->client ); | |
$results = $service->events->listEvents( $this->calendar_id, $args ); | |
// if found | |
if( count( $results->getItems() ) >= 1 ) { | |
return $results->getItems(); | |
} else { | |
return false; | |
} | |
} | |
} | |
//// | |
$cal = new MyCalendar(); | |
$cal_data = $cal->get(); | |
var_dump( $cal_data ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment