Christian Nyembo
Christian Nyembo

Reputation: 1

Using PHP to export an event to a Google Calendar

I would like to export calendar events from my website to an existing google calendar using PHP (note: this is not the calendar of the user that is logged in, but a predefined calendar that is linked to my own account). I could not find a full exemple in the official documentation. The documentation exemple uses PHP in the command line. However, I want to have it set up within my website, without using the command line. I found the folling post: Google Calendar API (v3) - PHP can write but not read? which uses curl, so I tried using this:

$api_key = 'api-key-from-google-console';
$calendar_id = "calendar_id";

$start = array(
  "dateTime" => $date . "T" . $start_time . ":00",
  "timeZone" => "Africa/Johannesburg"
);

$end = array(
  "dateTime" => $date . "T" . $end_time . ":00",
  "timeZone" => "Africa/Johannesburg"
);

$headerarray = array(
  'Content-type: application/json',
  'Authorization: Bearer ' . $api_key,
  'X-JavaScript-User-Agent: Google APIs Explorer'
);

$post_data = array(
  "start"       => $start,
  "end"         => $end,
  "summary"     => $title,
  "description" => $description,
  "key"         => "$api_key"
);

$url = 'https://www.googleapis.com/calendar/v3/calendars/' . $calendar_id . '/events';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerarray);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = json_decode($response);

However, this returns with an error that my credentials are invalid. What is wrong in this code? I am using an active API key, but when I look at the Google documentation I am unclear how exactly I should use this in this curl code. In the example from Stackoverflow there were no additional instructions either.?

Upvotes: 0

Views: 1603

Answers (1)

Linda Lawton - DaImTo
Linda Lawton - DaImTo

Reputation: 117321

First off you should consider using a service account. A service account is like a dummy user. It has its own google calendar account for example. However because it is a user you can share your person google calendar with the service account and it will be able to access it without you needing to login.

Asuming you are open to using the google apis php client library you can use ServiceAccount.php to authenticate your code and then call that when ever you need. I recommend following php quickstart

require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}
/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

I havent tried getting this to work with curl but if you want to this might help https://developers.google.com/api-client-library/php/auth/service-accounts

Upvotes: 1

Related Questions