How to Access Google Calendar With PHP Using Google API


Accessing Google Calendar with PHP using Google API involves several steps. Here is a step-by-step guide:

Step 1: Create a Google API project Go to the Google API Console (https://console.developers.google.com/) and create a new project. Once created, enable the Google Calendar API by going to the "APIs & Services" section, then "Library", search for "Google Calendar API" and enable it.

Step 2: Create OAuth Credentials To access Google Calendar API, you need to create OAuth credentials. Go to the "Credentials" section and click on "Create Credentials" > "OAuth client ID". Select "Web application" as the application type, enter a name for your client ID and enter the authorized JavaScript origins and redirect URIs. After you create the credentials, download the client ID and secret.

Step 3: Install Google API PHP Client Library Install the Google API PHP client library using Composer, which is a package manager for PHP. You can do this by running the following command in the terminal: ``` composer require google/apiclient:^2.0 ```

Step 4: Authenticate the user To access the Google Calendar API, you need to authenticate the user. This involves getting an access token, which you can do by using the Google API PHP client library. Here is an example code snippet:

``` require_once __DIR__ . '/vendor/autoload.php';

$client = new Google\Client(); $client->setApplicationName('Google Calendar API PHP'); $client->setScopes(Google\Service\Calendar::CALENDAR); $client->setAuthConfig('path/to/client_secret.json'); $client->setAccessType('offline'); $client->setApprovalPrompt('force');

$authUrl = $client->createAuthUrl(); header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL)); ```

In the code above, `setAuthConfig` should be the path to the client ID and secret that you downloaded in step 2.

Step 5: Access the calendar Once the user is authenticated, you can access the Google Calendar API using the Google API PHP client library. Here is an example code snippet:

``` require_once __DIR__ . '/vendor/autoload.php';

$client = new Google\Client(); $client->setApplicationName('Google Calendar API PHP'); $client->setScopes(Google\Service\Calendar::CALENDAR); $client->setAuthConfig('path/to/client_secret.json'); $client->setAccessType('offline'); $client->setApprovalPrompt('force');

$accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']); $client->setAccessToken($accessToken);

$service = new Google\Service\Calendar($client); $calendarList = $service->calendarList->listCalendarList();

foreach ($calendarList->getItems() as $calendar) {

 echo $calendar->getSummary();

} ```

In the code above, `$accessToken` is the access token returned by Google after the user authenticates.

That's it! With these steps, you can access Google Calendar with PHP using Google API.