Example #1
2
 private function instantiateClient()
 {
     $this->client = new \Google_Client();
     $this->client->setApplicationName($this->config['applicationName']);
     $this->client->setAuthConfig($this->config['jsonFilePath']);
     $this->client->setScopes($this->config['scopes']);
 }
Example #2
2
 public function run()
 {
     require_once 'vendor/autoload.php';
     $client = new Google_Client();
     $client->setAuthConfig(array("type" => "service_account", "client_id" => $this->config['client_id'], "client_email" => $this->config['client_email'], "private_key" => $this->config['#private_key'], "signing_algorithm" => "HS256"));
     $client->setApplicationName("GSC_Reports_Download");
     $client->setScopes(['https://www.googleapis.com/auth/webmasters.readonly']);
     $service = new Google_Service_Webmasters($client);
     $this->getCrawlErrorsCounts($service, $this->config['site_url']);
 }
Example #3
1
 /**
  * @Route("/gatest2", name="front_ga2")
  *
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function indexAction(Request $request)
 {
     $this->client = $this->get('GoogleClient');
     $this->client->setAuthConfig($this->getParameter('googleCredentialsFile'));
     $this->client->setApplicationName('Pingvin');
     $this->client->setScopes($this->getParameter('googleAnalyticsAuthUrl'));
     $this->analyticsService = $this->get('GoogleAnalyticsService');
     $accounts = $this->analyticsService->management_accounts->listManagementAccounts();
     $data = array();
     if (count($accounts->getItems()) > 0) {
         $items = $accounts->getItems();
         foreach ($items as $item) {
             $id = $item->getId();
             $properties = $this->analyticsService->management_webproperties->listManagementWebproperties($id);
             $items_e = $properties->getItems();
             foreach ($items_e as $item_e) {
                 $profiles = $this->analyticsService->management_profiles->listManagementProfiles($id, $item_e->getId());
                 $items_ee = $profiles->getItems();
                 foreach ($items_ee as $item_ee) {
                     $data[] = array($item_ee->getId(), $item_e->getId());
                 }
             }
         }
         var_dump('<pre>', $data);
     }
     return $this->render('CronBundle::message.html.twig', array('message' => '...'));
 }
 /**
  * Initialize the google calendar
  *
  * @throws \KevinDitscheid\KdCalendar\Exception\NoAuthDataException
  */
 public function initializeObject()
 {
     $this->settings = \KevinDitscheid\KdCalendar\Utility\ExtensionUtility::getMergedExtensionConfiguration();
     $this->client = new \Google_Client();
     $this->client->setApplicationName($this->settings['applicationName']);
     $this->client->setScopes(\Google_Service_Calendar::CALENDAR_READONLY);
     if ($this->settings['auth']['jsonFile']) {
         $this->client->setAuthConfigFile($this->settings['auth']['jsonFile']);
     } elseif ($this->settings['auth']['jsonString']) {
         $this->client->setAuthConfig($this->settings['auth']['jsonString']);
     } else {
         throw new \KevinDitscheid\KdCalendar\Exception\NoAuthDataException("No auth data is provided for Google Calendar!", 1454958940);
     }
     $this->client->setAccessType(self::ACCESS_TYPE_OFFLINE);
 }
Example #5
1
 public function add_google_client()
 {
     $auth_config = $this->get_auth_config();
     if (!empty($auth_config)) {
         try {
             $client = new Google_Client();
             $client->setAuthConfig($this->get_auth_config());
             $client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
             $client->setAccessType('offline');
             $token = $this->get_token();
             if ($token) {
                 $client->setAccessToken($token);
             }
             if ($client->isAccessTokenExpired()) {
                 $refresh_token = $this->get_refresh_token();
                 if ($refresh_token) {
                     $client->refreshToken($refresh_token);
                     $this->update_token($client->getAccessToken());
                 }
             }
             $this->client = $client;
             $this->service = new Google_Service_Analytics($this->client);
         } catch (Exception $e) {
             $message = 'Google Analytics Error[' . $e->getCode() . ']: ' . $e->getMessage();
             $this->disconnect($message);
             error_log($message, E_USER_ERROR);
             return;
         }
     }
 }
 /**
  * @param   Entity\CloudCredentials $entity
  * @param   Entity\CloudCredentials $prevConfig
  *
  * @throws  ApiErrorException
  */
 public function validateEntity($entity, $prevConfig = null)
 {
     parent::validateEntity($entity, $prevConfig);
     $ccProps = $entity->properties;
     $prevCcProps = isset($prevConfig) ? $prevConfig->properties : null;
     if ($this->needValidation($ccProps, $prevCcProps)) {
         $ccProps[Entity\CloudCredentialsProperty::GCE_ACCESS_TOKEN] = "";
         try {
             $client = new \Google_Client();
             $client->setApplicationName("Scalr GCE");
             $client->setScopes(['https://www.googleapis.com/auth/compute']);
             $key = base64_decode($ccProps[Entity\CloudCredentialsProperty::GCE_KEY]);
             // If it's not a json key we need to convert PKCS12 to PEM
             if (!$ccProps[Entity\CloudCredentialsProperty::GCE_JSON_KEY]) {
                 @openssl_pkcs12_read($key, $certs, 'notasecret');
                 $key = $certs['pkey'];
             }
             $client->setAuthConfig(['type' => 'service_account', 'project_id' => $ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID], 'private_key' => $key, 'client_email' => $ccProps[Entity\CloudCredentialsProperty::GCE_SERVICE_ACCOUNT_NAME], 'client_id' => $ccProps[Entity\CloudCredentialsProperty::GCE_CLIENT_ID]]);
             $client->setClientId($ccProps[Entity\CloudCredentialsProperty::GCE_CLIENT_ID]);
             $gce = new \Google_Service_Compute($client);
             $gce->zones->listZones($ccProps[Entity\CloudCredentialsProperty::GCE_PROJECT_ID]);
         } catch (Exception $e) {
             throw new ApiErrorException(400, ErrorMessage::ERR_INVALID_VALUE, "Provided GCE credentials are incorrect: ({$e->getMessage()})");
         }
         $entity->status = Entity\CloudCredentials::STATUS_ENABLED;
     }
 }
Example #7
1
 /**
  * Determine and use credentials if user has set them.
  * @param $userEmail
  * @return bool used or not
  */
 protected function useAssertCredentials($userEmail = '')
 {
     $serviceJsonUrl = array_get($this->config, 'service.file', '');
     if (empty($serviceJsonUrl)) {
         return false;
     }
     $this->client->setAuthConfig($serviceJsonUrl);
     if ($userEmail) {
         $this->client->setSubject($userEmail);
     }
     return true;
 }
 /**
  * @return Google_Client
  */
 private function getGoogleClient()
 {
     if (is_null($this->client)) {
         if (!class_exists('Google_Client')) {
             throw new Exceptions\ProviderFailureException('Could not find the Google_Client class', 404);
         }
         $this->client = new \Google_Client();
         $this->client->setApplicationName('Most_Popular');
         $this->client->setAuthConfig($this->authConfigFile);
     }
     return $this->client;
 }
Example #9
1
 protected function getClient()
 {
     if (null === $this->client) {
         $this->client = new \Google_Client();
         $this->client->setAuthConfig($this->credentials);
         $this->client->setApplicationName($this->name);
         foreach ($this->services as $serviceName => $service) {
             if (!isset($service['class'])) {
                 throw new InvalidConfigException("Not set service class for service \"{$serviceName}\"");
             }
             $service['scopes'] = (array) $service['scopes'];
             if (empty($service['scopes'])) {
                 throw new InvalidConfigException("Not set scopes for service \"{$serviceName}\"");
             }
             $this->client->addScope($service["scopes"]);
         }
         $scopes = $this->client->getScopes();
         if (empty($scopes)) {
             throw new InvalidConfigException("Not set scopes for application \"{$this->name}\"");
         }
     }
     return $this->client;
 }
Example #10
1
echo pageHeader("Retrieving An Id Token");
/*************************************************
 * Ensure you've downloaded your oauth credentials
 ************************************************/
if (!($oauth_credentials = getOAuthCredentialsFile())) {
    echo missingOAuth2CredentialsWarning();
    return;
}
/************************************************
 * NOTICE:
 * The redirect URI is to the current page, e.g:
 * http://localhost:8080/idtoken.php
 ************************************************/
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client = new Google_Client();
$client->setAuthConfig($oauth_credentials);
$client->setRedirectUri($redirect_uri);
$client->setScopes('email');
/************************************************
 * If we're logging out we just need to clear our
 * local access token in this case
 ************************************************/
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['id_token_token']);
}
/************************************************
 * If we have a code back from the OAuth 2.0 flow,
 * we need to exchange that with the
 * Google_Client::fetchAccessTokenWithAuthCode()
 * function. We store the resultant access token
 * bundle in the session, and redirect to ourself.
Example #11
1
 public function testJsonConfig()
 {
     // Device config
     $config = new Google_Config();
     $client = new Google_Client($config);
     $device = '{"installed":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret"' . ':"N0aHCBT1qX1VAcF5J1pJAn6S","token_uri":"https://accounts.google.com/o/oauth2/token",' . '"client_email":"","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","oob"],"client_x509_cert_url"' . ':"","client_id":"123456789.apps.googleusercontent.com","auth_provider_x509_cert_url":' . '"https://www.googleapis.com/oauth2/v1/certs"}}';
     $dObj = json_decode($device);
     $client->setAuthConfig($device);
     $cfg = $config->getClassConfig('Google_Auth_OAuth2');
     $this->assertEquals($cfg['client_id'], $dObj->installed->client_id);
     $this->assertEquals($cfg['client_secret'], $dObj->installed->client_secret);
     $this->assertEquals($cfg['redirect_uri'], $dObj->installed->redirect_uris[0]);
     // Web config
     $config = new Google_Config();
     $client = new Google_Client($config);
     $web = '{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret"' . ':"lpoubuib8bj-Fmke_YhhyHGgXc","token_uri":"https://accounts.google.com/o/oauth2/token"' . ',"client_email":"*****@*****.**","client_x509_cert_url":' . '"https://www.googleapis.com/robot/v1/metadata/x509/123456789@developer.gserviceaccount.com"' . ',"client_id":"123456789.apps.googleusercontent.com","auth_provider_x509_cert_url":' . '"https://www.googleapis.com/oauth2/v1/certs"}}';
     $wObj = json_decode($web);
     $client->setAuthConfig($web);
     $cfg = $config->getClassConfig('Google_Auth_OAuth2');
     $this->assertEquals($cfg['client_id'], $wObj->web->client_id);
     $this->assertEquals($cfg['client_secret'], $wObj->web->client_secret);
     $this->assertEquals($cfg['redirect_uri'], '');
 }
// Change to the project root, to simplify resolving paths
chdir(dirname(__DIR__));
require 'vendor/autoload.php';
//require_once __DIR__ . '/vendor/autoload.php';
use zaboy\utils\Api\Gmail as ApiGmail;
define('APPLICATION_NAME', 'Gmail API PHP Quickstart');
define('CREDENTIALS_PATH', ApiGmail::CREDENTIALS_PATH);
define('CLIENT_SECRET_PATH', 'www/cfg/client_secret.json');
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/gmail-php-quickstart.json
define('SCOPES', implode(' ', array(Google_Service_Gmail::GMAIL_READONLY)));
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = ApiGmail::expandHomeDirectory(CREDENTIALS_PATH);
if (file_exists($credentialsPath)) {
    printf("Credentials exist in %s\n", $credentialsPath);
    echo PHP_EOL . 'Delete it for remake and restsrt this script';
} else {
    // Request authorization from the user.
    $authUrl = $client->createAuthUrl();
    printf("Open the following link in your browser:\n%s\n", $authUrl);
    print 'Enter verification code: ';
    $authCode = trim(fgets(STDIN));
    // Exchange authorization code for an access token.
    $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
    // Store the credentials to disk.
Example #13
1
<?php

// MUST be using composer
require_once '/var/www/relle/vendor/autoload.php';
session_start();
$client = new Google_Client();
// Name of proj in GoogleDeveloperConsole
$client->setApplicationName("relle-analytics");
// Generated in GoogleDeveloperConsole --> Credentials --> Service Accounts
$client->setAuthConfig('/var/www/relle/relle-analytics-3753dd041a88.json');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// Grab token if it's set
if (isset($_SESSION['service_token'])) {
    $client->setAccessToken($_SESSION['service_token']);
}
// Refresh if expired
if ($client->isAccessTokenExpired()) {
    $client->refreshTokenWithAssertion();
}
// Pin to Session
$_SESSION['service_token'] = $client->getAccessToken();
$myToken = $client->getAccessToken();
?>
{{Analytics::trackEvent('Página', 'Logs')}}
@extends ('layout.dashboard')

@section('page')
{{trans('interface.name', ['page'=>trans('log.title')])}}        
@stop

@section("title_inside")
 public function testApplicationDefaultCredentialsWithSubject()
 {
     $sub = 'sub123';
     $client = new Google_Client();
     $client->setAuthConfig(__DIR__ . '/../config/application-default-credentials.json');
     $client->setSubject($sub);
     $http = new Client();
     $client->authorize($http);
     $listeners = $http->getEmitter()->listeners('before');
     $this->assertEquals(1, count($listeners));
     $this->assertEquals(2, count($listeners[0]));
     $this->assertInstanceOf('Google\\Auth\\AuthTokenFetcher', $listeners[0][0]);
     // access the protected $fetcher property
     $class = new ReflectionClass(get_class($listeners[0][0]));
     $property = $class->getProperty('fetcher');
     $property->setAccessible(true);
     $fetcher = $property->getValue($listeners[0][0]);
     $this->assertInstanceOf('Google\\Auth\\ServiceAccountCredentials', $fetcher);
     // access the protected $auth property
     $class = new ReflectionClass(get_class($fetcher));
     $property = $class->getProperty('auth');
     $property->setAccessible(true);
     $auth = $property->getValue($fetcher);
     $this->assertEquals($sub, $auth->getSub());
 }
$client = new Google_Client();
/************************************************
  ATTENTION: Fill in these values, or make sure you
  have set the GOOGLE_APPLICATION_CREDENTIALS
  environment variable. You can get these credentials
  by creating a new Service Account in the
  API console. Be sure to store the key file
  somewhere you can get to it - though in real
  operations you'd want to make sure it wasn't
  accessible from the webserver!
  Make sure the Books API is enabled on this
  account as well, or the call will fail.
 ************************************************/
if ($credentials_file = checkServiceAccountCredentialsFile()) {
    // set the location manually
    $client->setAuthConfig($credentials_file);
} elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
    // use the application default credentials
    $client->useApplicationDefaultCredentials();
} else {
    echo missingServiceAccountDetailsWarning();
    exit;
}
$client->setApplicationName("Client_Library_Examples");
$client->setScopes(['https://www.googleapis.com/auth/books']);
$service = new Google_Service_Books($client);
/************************************************
  We're just going to make the same call as in the
  simple query as an example.
 ************************************************/
$optParams = array('filter' => 'free-ebooks');
<?php

// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Start a session to persist credentials.
session_start();
// Create the client object and set the authorization configuration
// from the client_secrets.json you downloaded from the Developers Console.
$client = new Google_Client();
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
// Handle authorization flow from the server.
if (!isset($_GET['code'])) {
    $auth_url = $client->createAuthUrl();
    header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
    $client->authenticate($_GET['code']);
    $_SESSION['access_token'] = $client->getAccessToken();
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
 /**
  * New service client - Authentication google Api
  *
  * @return Google_Service_Client $service API service instance.
  */
 public function testService($credentials)
 {
     $scope = array('https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.readonly', 'https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive.photos.readonly');
     if ($credentials->typeAuth == 'webApplication') {
         if (file_exists($credentials->pathFileJson)) {
             $credential = file_get_contents($credentials->pathFileJson);
         } else {
             throw new Exception(G::LoadTranslation('ID_GOOGLE_FILE_JSON_ERROR'));
         }
         $client = new Google_Client();
         $client->setAuthConfig($credential);
         $client->addScope($scope);
         if (!empty($_SESSION['google_token'])) {
             $client->setAccessToken($_SESSION['google_token']);
             if ($client->isAccessTokenExpired()) {
                 unset($_SESSION['google_token']);
             }
         } else {
             if (!empty($_SESSION['CODE_GMAIL'])) {
                 $token = $client->authenticate($_SESSION['CODE_GMAIL']);
                 $_SESSION['google_token'] = $client->getAccessToken();
             } else {
                 $authUrl = $client->createAuthUrl();
                 echo '<script type="text/javascript">
                 var opciones = "width=450,height=480,scrollbars=NO, locatin=NO,toolbar=NO, status=NO, menumbar=NO, top=10%, left=25%";
                 window.open("' . $authUrl . '","Gmail", opciones);
                 </script>';
                 die;
             }
         }
     } else {
         if (file_exists($credentials->pathServiceAccountP12)) {
             $key = file_get_contents($credentials->pathServiceAccountP12);
         } else {
             throw new Exception(G::LoadTranslation('ID_GOOGLE_FILE_P12_ERROR'));
         }
         $assertionCredentials = new Google_Auth_AssertionCredentials($credentials->emailServiceAccount, $scope, $key);
         $assertionCredentials->sub = $this->user;
         $client = new Google_Client();
         $client->setApplicationName("PMDrive");
         $client->setAssertionCredentials($assertionCredentials);
     }
     $service = new Google_Service_Drive($client);
     $result = new StdClass();
     $result->success = true;
     $result->currentUserName = G::LoadTranslation('ID_SERVER_COMMUNICATION_ERROR');
     $result->rootFolderId = G::LoadTranslation('ID_SERVER_COMMUNICATION_ERROR');
     $result->quotaType = G::LoadTranslation('ID_SERVER_COMMUNICATION_ERROR');
     $result->quotaBytesTotal = G::LoadTranslation('ID_SERVER_COMMUNICATION_ERROR');
     $result->quotaBytesUsed = G::LoadTranslation('ID_SERVER_COMMUNICATION_ERROR');
     try {
         $about = $service->about->get();
         $result->currentUserName = $about->getName();
         $result->rootFolderId = $about->getRootFolderId();
         $result->quotaType = $about->getQuotaType();
         $result->quotaBytesTotal = $about->getQuotaBytesTotal();
         $result->quotaBytesUsed = $about->getQuotaBytesUsed();
         $result->responseGmailTest = G::LoadTranslation('ID_SUCCESSFUL_CONNECTION');
     } catch (Exception $e) {
         $result->success = false;
         $result->responseGmailTest = G::LoadTranslation('ID_SERVER_COMMUNICATION_ERROR');
     }
     return $result;
 }
Example #18
1
$APP['ana'] = $ana;
/* Third-party libraries should be included here. ----------------------------------------- */
require_once 'third_party/parsedown-master/Parsedown.php';
require_once 'third_party/class.upload.php-master/src/class.upload.php';
// for usage on that: https://github.com/verot/class.upload.php
// Google API autoload:
require_once $APP['src_path'] . '/third_party/google-api-php-client-master/src/Google/autoload.php';
// Snoopy class
require_once $APP['src_path'] . '/third_party/Snoopy.class.php';
// Composer Autoloader:
require __ROOT__ . '/vendor/autoload.php';
/* end third party libraries ----------------------------------------------------------------- */
// Initialize the Google client with an oAuth call.
session_start();
$client = new Google_Client();
$client->setAuthConfig($APP['google']['client_secret']);
$client->setScopes(array("https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/calendar", "https://www.googleapis.com/auth/contacts.readonly", "https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile"));
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
    $client->setAccessToken($_SESSION['access_token']);
    if ($client->isAccessTokenExpired()) {
        $authUrl = $client->createAuthUrl();
        header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
    }
} else {
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/coldreader/oauth2callback.php';
    header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// Store the google client in the App array so we can access it elsewhere.
$APP['google']['client'] = $client;
// we're finished with the google client, and we've stored it in our app array.
// let's see if we can get an email address from google, and confirm that you're good to go.
Example #19
1
 private function get_token()
 {
     $client = new Google_Client();
     if ($credentials_file = $this->checkServiceAccountCredentialsFile()) {
         $client->setAuthConfig($credentials_file);
     } elseif (getenv('GOOGLE_APPLICATION_CREDENTIALS')) {
         $client->useApplicationDefaultCredentials();
     } else {
         echo missingServiceAccountDetailsWarning();
         exit;
     }
     $client->setApplicationName("IARD Tables");
     $client->setScopes(array('https://spreadsheets.google.com/feeds'));
     $token = $client->fetchAccessTokenWithAssertion();
     return $token['access_token'];
 }
Example #20
1
/**
 * AUTHENTICATE
 *
 */
// These settings are found on google developer console
const CLIENT_APP_NAME = 'MyProject';
const CLIENT_ID = '438461248139-f7kd5sfvreoplg69qs9m803l2611e30v.apps.googleusercontent.com';
const CLIENT_EMAIL = '*****@*****.**';
const CLIENT_KEY_PATH = 'credential.p12';
// PATH_TO_KEY = where you keep your key file
const CLIENT_KEY_PW = 'e9892d96d35b97cfb2468d821c404c25610f9da5';
$SPREADSHEETS_SCOPE = 'https://spreadsheets.google.com/feeds';
$client = new Google_Client();
$client->setApplicationName('My Project');
$client->setScopes(array($SPREADSHEETS_SCOPE));
$client->setAuthConfig('credential.json');
if ($client->isAccessTokenExpired()) {
    $client->refreshTokenWithAssertion();
}
$client->setClientId(CLIENT_ID);
$objToken = $client->getAccessToken();
$accessToken = $objToken["access_token"];
/**
 * Initialize the service request factory
 */
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);
/**
 * Get spreadsheet by title
Example #21
1
<?php

$timezone = "America/Los_Angeles";
date_default_timezone_set($timezone);
$base = realpath(dirname($_SERVER["SCRIPT_FILENAME"]) . "/..");
require "{$base}/vendor/autoload.php";
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
$scopes = implode(' ', array("https://spreadsheets.google.com/feeds", Google_Service_Drive::DRIVE, Google_Service_Calendar::CALENDAR));
$privateKey = "{$base}/server/auth.p12";
$clientEmail = "*****@*****.**";
$client = new Google_Client();
$client->setAuthConfig($privateKey);
$client->addScope($scopes);
if ($client->isAccessTokenExpired()) {
    $client->refreshTokenWithAssertion();
}
$accessToken = $client->getAccessToken();
$accessToken = $accessToken["access_token"];
$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
$drive = new Google_Service_Drive($client);
$sheets = new Google_Service_Sheets($client);
function startsWith($haystack, $needle)
{
    // search backwards starting from haystack length characters from the end
    return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
}
function endsWith($haystack, $needle)
 /**
  * @return \Google_Service_Analytics
  * @throws \Exception
  * @throws \Google_Exception
  */
 public function getService($token = null)
 {
     $application = $this->applicationService->getApplication(self::RESOURCE_OWNER);
     if ($token === null) {
         $token = $this->getToken();
     }
     $authConfig = array('web' => array('client_id' => $application->getKey(), 'client_secret' => $application->getSecret()));
     $client = new \Google_Client();
     $client->setAuthConfig(json_encode($authConfig));
     $client->setAccessToken(json_encode(array('access_token' => $token->getAccessToken(), 'refresh_token' => $token->getRefreshToken())));
     return new \Google_Service_Analytics($client);
 }
 public function testApplicationDefaultCredentialsWithSubject()
 {
     $this->checkServiceAccountCredentials();
     $credentialsFile = getenv('GOOGLE_APPLICATION_CREDENTIALS');
     $sub = 'sub123';
     $client = new Google_Client();
     $client->setAuthConfig($credentialsFile);
     $client->setSubject($sub);
     $http = new Client();
     $client->authorize($http);
     $this->checkAuthHandler($http, 'AuthToken');
     $this->checkCredentials($http, 'Google\\Auth\\Credentials\\ServiceAccountCredentials', $sub);
 }
function authGoogle($get)
{
    require_once 'lib/vendor/autoload.php';
    # require_once 'lib/google-php-client/vendor/autoload.php';
    global $google_clientid, $google_secret, $google_config_file_path;
    /*************************************************
     * Ensure you've downloaded your oauth credentials
     ************************************************/
    if (!file_exists($google_config_file_path)) {
        return array("status" => false, "error" => "Bad config file path");
    }
    /************************************************
     * NOTICE:
     * The redirect URI is to the current page, e.g:
     * http://localhost:8080/idtoken.php
     ************************************************/
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    $client = new Google_Client();
    $client->setAuthConfig($google_config_file_path);
    $client->setRedirectUri($redirect_uri);
    $client->setScopes('email');
    /************************************************
     * If we're logging out we just need to clear our
     * local access token in this case
     ************************************************/
    if (isset($_REQUEST['logout'])) {
        unset($_SESSION['id_token']);
    }
    $token = $get["token"];
    try {
        /************************************************
         * If we have a code back from the OAuth 2.0 flow,
         * we need to exchange that with the
         * Google_Client::fetchAccessTokenWithAuthCode()
         * function. We store the resultant access token
         * bundle in the session, and redirect to ourself.
         ************************************************/
        if (!empty($token) && empty($get["tokens"])) {
            $fancyToken = array("access_token" => $token);
            $token = $client->fetchAccessTokenWithAuthCode($get["token"]);
            $client->setAccessToken($token);
            // store in the session also
            $_SESSION['id_token'] = $token;
            $token_data = $client->verifyIdToken();
        } else {
            if (!empty($get["tokens"])) {
                $tokens = base64_decode($get["tokens"]);
                $client->setAccessToken($get["tokens"]);
                $ta = json_decode($tokens, true);
                $token_data = $client->verifyIdToken($ta["id_token"]);
            } else {
                /************************************************
                  If we have an access token, we can make
                  requests, else we generate an authentication URL.
                    ************************************************/
                $authUrl = $client->createAuthUrl();
            }
        }
    } catch (Exception $e) {
        $token2 = $get['token'];
        if (is_string($token2)) {
            if ($json = json_decode($token2, true)) {
                $token2 = $json;
            } else {
                // assume $token is just the token string
                $token2 = array('access_token' => $token2);
            }
        }
        return array("status" => false, "error" => $e->getMessage(), "stack" => $e->getTraceAsString(), "token" => $token, "computed_token" => $token2, "tokens" => base64_decode($get["tokens"]));
    }
    /************************************************
      If we're signed in we can go ahead and retrieve
      the ID token, which is part of the bundle of
      data that is exchange in the authenticate step
      - we only need to do a network call if we have
      to retrieve the Google certificate to verify it,
      and that can be cached.
        ************************************************/
    $return = array("status" => true, "auth_url" => $authUrl, "token_data" => $token_data, "identifier" => $token_data["email"], "verifier" => computeUserPassword($token_data["sub"]));
    return $return;
}