Клиент Google аутентифицирует Сервисную учетную запись, чтобы получать события Календаря от Темы
Я создаю календарь, который будет получать события от выбранного пользователя, а также создавать новые события в повестке дня субъекта. Читая здесь документы и некоторые вопросы о переполнении стека, я понял, что для того, чтобы сделать то, что мне нужно, мне придется использовать служебную учетную запись для олицетворения пользователя и получения / создания событий. Также я пытался реализовать это, но всегда получаю следующее сообщение об ошибке:
{"error": "unauthorized_client", "error_description": "Клиент не авторизован для получения токенов доступа с помощью этого метода." }
Код:
BaseClient.php
abstract class BaseClient
{
/**
* The Google client instance
* @var \Google_Client
*/
protected $client = null;
/**
* The scopes of this client
* @var array
*/
protected $scopes = [];
/**
* @var array
*/
protected $config = [];
/**
* Constructs the object and initializes basic settings
* @param \Google_Client $client The client instance
* @param array $config The configuration array
*/
public function __construct(GoogleClient $client, array $config)
{
$this->config = $config;
$this->client = $client;
$this->client->setApplicationName($config['name']);
$this->client->setAccessType('offline');
$this->client->setScopes($this->scopes);
$this->init();
}
/**
* Returns an instance of the calendar service
* @throws \PlanetExpat\Google\Service\ServiceNotAvailableException If the service is not available
* @return Google_Service_Calendar The service
*/
public function getCalendarService()
{
if (!$this->hasCalendarService()) {
throw new Service\ServiceNotAvailableException('Calendar');
}
$service = new CalendarService($this->client);
return new Service\Calendar($service);
}
/**
* Returns an instance of the google plus service
* @throws \PlanetExpat\Google\Service\ServiceNotAvailableException If the service is not available
* @return Google_Service_Plus The service
*/
public function getPlusService()
{
if (!$this->hasPlusService()) {
throw new Service\ServiceNotAvailableException('Plus');
}
$service = new PlusService($this->client);
return new Service\Plus($service);
}
/**
* Returns an instance of the google drive service
* @throws \PlanetExpat\Google\Service\ServiceNotAvailableException If the service is not available
* @return Google_Service_Drive The service
*/
public function getDriveService()
{
if (!$this->hasDriveService()) {
throw new Service\ServiceNotAvailableException('Drive');
}
$service = new DriveService($this->client);
return new Service\Drive($service, $this->config['drive']);
}
/**
* Returns an instance of the gmail service
* @throws \PlanetExpat\Google\Service\ServiceNotAvailableException If the service is not available
* @return Google_Service_Gmail The service
*/
public function getGmailService()
{
throw new Service\ServiceNotAvailableException('Gmail');
}
/**
* Initializes the google client
*/
abstract public function init();
/**
* Checks if the client implements the calendar service
* @return bool
*/
abstract public function hasCalendarService();
/**
* Checks if the client implements the G+ service
* @return bool
*/
abstract public function hasPlusService();
/**
* Checks if the client implements the GDrive service
* @return bool
*/
abstract public function hasDriveService();
/**
* Checks if the client implements the GMail service
* @return bool
*/
abstract public function hasGmailService();
}
ServiceAccountClient.php
class ServiceAccountClient extends BaseClient
{
/**
* {@inheritDoc}
*/
protected $scopes = [
Plus::USERINFO_PROFILE,
Calendar::CALENDAR,
Drive::DRIVE,
Drive::DRIVE_FILE,
Gmail::GMAIL_MODIFY
];
/**
* {@inheritDoc}
*/
public function init($subject=null)
{
$this->client->setAuthConfig($this->config['file']->getRealPath());
$this->client->setRedirectUri($this->config['redirect_uri']);
$this->client->setSubject('arthur@planetexpat.org');
}
/**
* Returns the authentication URI
* @return string The authentication URI
*/
public function getAuthUrl()
{
return filter_var($this->client->createAuthUrl(), FILTER_SANITIZE_URL);
}
/**
* {@inheritDoc}
*/
public function hasCalendarService()
{
return true;
}
/**
* {@inheritDoc}
*/
public function hasPlusService()
{
return true;
}
/**
* {@inheritDoc}
*/
public function hasDriveService()
{
return false;
}
/**
* {@inheritDoc}
*/
public function hasGmailService()
{
return false;
}
}
GoogleClientServiceProvider.php (глобальная реализация)
$google_config = $app['config']->get('google');
$app['google.client.service_account'] = $app->share(function() use ($google_config, $app) {
$relpath = '/../../../';
$path = __DIR__ . $relpath . $google_config['credentials-file'];
$config = [
'file' => new SplFileInfo($path, $relpath, $relpath),
'redirect_uri' => $google_config['redirect-uri'],
'name' => $google_config['app-name'],
];
$client = new ServiceAccountClient(new GoogleClient(), $config);
return $client;
});
Вызов контроллера
$google_sa = $app['google.client.service_account'];
$google_sa->init($recruiter_calendar->recruiter->user->handle);
$calendar = $google_sa->getCalendarService();
$events = $calendar->getCalendarEvents('email here'); //got error here
Доступ к ссылкам:
https://developers.google.com/api-client-library/php/auth/service-accounts
Вставка записей Календаря Google с учетной записью службы
Другие ссылки на комментарий к этому вопросу