public function __construct(Container $container) { $this->helper = $container->helper; $this->config = $container->config; $this->view = $container->view; $this->provider = new Google(['clientId' => $this->config->getClientId(), 'clientSecret' => $this->config->getClientSecret(), 'redirectUri' => $this->helper->getCallbackUrl(self::AREA)]); }
/** * Sends request: * curl --data "code=[GET->code] * &grant_type=authorization_code * &client_id=[client_id] * &client_secret=[client_secret] * &redirect_uri=[url_of_this_function]" * https://www.googleapis.com/oauth2/v3/token * * Gets response: * [ * 'code' => '4/PTIwf4eUb3ajdD21_access_code' * 'scope' => 'https://www.googleapis.com/auth/drive.readonly' * ] * @param Request $request * @param Response $response * @return \Psr\Http\Message\MessageInterface|\Psr\Http\Message\ResponseInterface */ public function authenticateCallback(Request $request, Response $response) { $code = $request->getQueryParams()['code'] ?? ''; try { if (!$code) { throw new \Exception('No access code provided.'); } $client = new Client(); $params = ['code' => $code, 'grant_type' => 'authorization_code', 'client_id' => $this->config->getClientId(), 'client_secret' => $this->config->getClientSecret(), 'redirect_uri' => $this->helper->getCallbackUrl(self::AREA)]; $response = $client->post($this->config->getTokenUri(), ['form_params' => $params]); $json = json_decode($response->getBody(), true); $this->helper->setAccessToken($json); if (!isset($json['access_token'])) { throw new \Exception("Access token not returned."); } return $response->withStatus(301)->withHeader('Location', '/' . self::AREA); } catch (\Exception $ex) { return $this->view->render($response, 'error.twig', ['error' => $ex->getMessage()]); } }