Google_API.php
<?php class Google_API { public function __construct($redirect_uri = null) { $this->client_id = GOOGLE_CLIENT_ID; $this->client_secret = GOOGLE_CLIENT_SECRET; } public function Dialog($scope = null) { } return sprintf("https://accounts.google.com/o/oauth2/auth?client_id=%s&scope=%s&redirect_uri=%s&state=%s&response_type=code", $this->client_id, $scope, $this->redirect_uri, $state ); } public function GetAccessToken($scope) { if ($this->IsAccessToken($scope) === true) { } $params = sprintf("code=%s&client_id=%s&client_secret=%s&redirect_uri=%s&grant_type=authorization_code", $_GET['code'], $this->client_id, $this->client_secret, $this->redirect_uri ); $oCURL = curl_init(); curl_setopt($oCURL, CURLOPT_URL, 'https://accounts.google.com/o/oauth2/token'); curl_setopt($oCURL, CURLOPT_POST, 1); curl_setopt($oCURL, CURLOPT_POSTFIELDS, $params); curl_setopt($oCURL, CURLOPT_RETURNTRANSFER, 1); $response = json_decode(curl_exec($oCURL), true); curl_close($oCURL); return 0; } return $response['access_token']; } public function Get($scope = null) { $access_token = $this->GetAccessToken($scope); } $oCURL = curl_init(); curl_setopt($oCURL, CURLOPT_URL, $scope); curl_setopt($oCURL, CURLOPT_RETURNTRANSFER, true); $response = curl_exec($oCURL); curl_close($oCURL); return $response; } public function IsAccessToken($scope = null) { return true; } return false; } }
kod dołączany do index.php
<?php include_once('Google_API.php'); // Tutaj ustawiamy przekierowanie powrotne, na które Google zwróci dane $oGoogle_API = new Google_API('https://mojastrona.pl/tasks/index.php'); $dialog = $oGoogle_API->Dialog('email'); } $google_access_state = empty($_COOKIE['google_access_state']) ? 0 : $_COOKIE['google_access_state']; if ($_GET['state'] !== $google_access_state) { // tutaj np. przekierowanie, jeżeli dane są błędne } $graph = $oGoogle_API->Get('https://www.googleapis.com/oauth2/v3/userinfo'); $graph = json_decode($graph, true); // tutaj np. przekierowanie, jeżeli nie udało się pobrać danych konta Google } // Wyświetlamy adres e-mail użytkownika, który dokonał autoryzacji. # echo $graph['email']; ?>