MelancholicTurnip
MelancholicTurnip

Reputation: 33

Can't create an event using google calendar api php

I've followed all the instructions, the php quickstart and the events.insert pages by google; but when i run it the consent form pops up I click allow and then nothing happens bar the consent form resetting.If i change the redirect url to another page then it no longer resets the consent form, but still nothing happens.

$client = new Google_Client();

$client->setAuthConfig('redacted');

$client->addScope("https://www.googleapis.com/auth/calendar");

$client->addScope("https://www.googleapis.com/auth/calendar.events");

$client->setRedirectUri('http://redacted/GoogleClientWorksCalendar.php');//this is the current file

$client->setAccessType('offline');

$client->setIncludeGrantedScopes(true);

$client->setPrompt('consent');

$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
$service = new Google_Service_Calendar($client);

$event = new Google_Service_Calendar_Event(array(
  'summary' => 'test',
  'location' => 'somewhere',
  'description' => 'test description',
  'start' => array(
    'dateTime' => '2020-09-03T09:00:00+02:00',

  ),
  'end' => array(
    'dateTime' => '2020-09-03T17:00:00+02:00',

  ),



));

$calendarId = 'redacted';
$results = $service->events->insert($calendarId, $event);

Thank you.

Upvotes: 0

Views: 113

Answers (1)

MelancholicTurnip
MelancholicTurnip

Reputation: 33

I have resolved my issue. The problem was I had forgotten a part of the google Oauth2.0 code required, which meant I never received the access token. This snippet below is fully functional. Hope it helps and thank you all for answering.

$client = new Google_Client();

$client->setAuthConfig('redacted');

$client->addScope("https://www.googleapis.com/auth/calendar");

$client->addScope("https://www.googleapis.com/auth/calendar.events");

$client->setRedirectUri('http://redacted/GoogleClientWorksCalendar.php');//this is the current file

$client->setAccessType('offline');

$client->setIncludeGrantedScopes(true);

$client->setPrompt('consent');

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

$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
$client->setAccessToken($access_token);

$service = new Google_Service_Calendar($client);

$event = new Google_Service_Calendar_Event(array(
  'summary' => 'test',
  'location' => 'somewhere',
  'description' => 'test description',
  'start' => array(
    'dateTime' => '2020-09-03T09:00:00+02:00',

  ),
  'end' => array(
    'dateTime' => '2020-09-03T17:00:00+02:00',

  ),



));

$calendarId = 'redacted';
$results = $service->events->insert($calendarId, $event);

Upvotes: 1

Related Questions