Cannot get access token with Google Calendar Api v

2020-04-18 07:33发布

问题:

I am trying to put a calendar event into a calendar without the authentication prompt. I have read that using an OAuth Service Account allows you to do this. I have set up the Service account in my Google Developer Console and am not having any luck with this.

We have a Google business account and I am setting my delegated user to an admin of our account so they can access anyone's calendar but it will not create the event. I believe the issue is with the access token. When I var_dump($accessToken) it shows NULL.

<?php
error_reporting(E_ALL);
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
session_start();    

/* Authentication ID's */    
const CLIENT_ID = '[MY CLIENT ID]';
const SERVICE_ACCOUNT_NAME = '[MY SERVICE ACCOUNT]';
const KEY_FILE = '[MY KEY FILE].p12';
const CALENDAR_SCOPE = "https://www.googleapis.com/auth/calendar";
$key = file_get_contents(KEY_FILE);
$auth = new Google_Auth_AssertionCredentials(
  SERVICE_ACCOUNT_NAME,
  array(CALENDAR_SCOPE),
  $key
);
$auth->sub = "adminaccount@email.com";

$client = new Google_Client();
$client->setScopes(array(CALENDAR_SCOPE));
$client->setAssertionCredentials($auth);

$client->getAuth()->refreshTokenWithAssertion();
$accessToken = $client->getAccessToken();

$client->setClientId(CLIENT_ID);

$user = "testaccount@email.com";

if($accessToken){

  $cal = new Google_Service_Calendar($client);

  $event = new Google_Service_Calendar_Event();
  $event->setSummary('TITLE');
  $event->setLocation('World');
  $event->setDescription('test');

  $start = new Google_Service_Calendar_EventDateTime();
  $start->setDate(date('yyyy-mm-dd'));
  $event->setStart($start);

  $end = new Google_Service_Calendar_EventDateTime();
  $end->setDate(date('yyyy-mm-dd'));
  $event->setEnd($end);

  $cal->events->insert($user, $event);
}
?>

I have referenced this other thread (Using a Service Account, getAccessToken() is returning null) to try and troubleshoot this issue but have had no luck with it.

Any help would be greatly appreciated!

回答1:

It sounds like you need to grant access to the google apps domain user data. Link below under section "Delegate domain-wide authority to your service account".

https://developers.google.com/drive/web/delegation



回答2:

You may try set the auth like this:

$auth = new Google_Auth_AssertionCredentials(
        SERVICE_ACCOUNT_NAME,
        SCOPES,
        $key,
        'notasecret',
        'http://oauth.net/grant_type/jwt/1.0/bearer',
        ADMIN_USER
        );