php composer.phar require google / apiclient
class Google { /* @var \Google_Client */ private $client; /* @var \Google_Service_Calendar */ private $calendar; private $scope; public function __construct($scope) { $this->client = new \Google_Client(); $this->scope = $scope; } public function setCredentialsP12($p12Path, $email) { $credentials = new \Google_Auth_AssertionCredentials( $email, $this->scope, file_get_contents($p12Path) ); $this->client->setAssertionCredentials($credentials); } public function setCredentialsJson($jsonPath) { $this->client->loadServiceAccountJson($jsonPath, $this->scope); } /** * @return \Google_Service_Calendar */ public function getCalendar() { if (!$this->calendar) { $this->calendar = new \Google_Service_Calendar($this->client); } return $this->calendar; } }
services: google.client: class: MyBundle\Google arguments: ['https://www.googleapis.com/auth/calendar.readonly'] #
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class CredentialsPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $googleClient = $container->getDefinition('google.client'); // if ($container->hasParameter('google_p12_path') && $container->hasParameter('google_p12_email')) { $path = $container->getParameter('google_p12_path'); $email = $container->getParameter('google_p12_email'); $googleClient->addMethodCall('setCredentialsP12', [$path, $email]); } elseif ($container->hasParameter('google_json_path')) { $googleClient->addMethodCall('setCredentialsJson', [$container->getParameter('google_json_path')]); } } }
parameters: google_p12_path: my-certificate.p12 google_p12_email: my-email@mail.com
or parameters: google_json_path: my-certificate.json
try { /* @var $start \DateTime */ $start; /* @var $end \DateTime */ $end; $events = $google->getCalendar()->events->listEvents('example@mail.com', [ 'timeMin' => $start->format('c'), 'timeMax' => $end->format('c'), ]); } catch (\Google_Service_Exception $exception) { //TODO implement error catching }
Source: https://habr.com/ru/post/259577/
All Articles