/**
  * Returns an authorized API client.
  * @return Google_Client the authorized client object
  */
 private function getGoogleApiClient()
 {
     $client = new Google_Client();
     $client->setApplicationName($this->CFG['GOOGLE_API_APPLICATION_NAME']);
     $client->setScopes(Google_Service_Calendar::CALENDAR);
     $client->setAuthConfigFile($this->CFG['GOOGLE_API_CLIENT_SECRET_PATH']);
     $client->setAccessType('offline');
     // Load previously authorized credentials from a file.
     $credentialsPath = $this->CFG['GOOGLE_API_CREDENTIALS_PATH'];
     if (file_exists($credentialsPath)) {
         $accessToken = file_get_contents($credentialsPath);
     } 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->authenticate($authCode);
         // Store the credentials to disk.
         if (!file_exists(dirname($credentialsPath))) {
             mkdir(dirname($credentialsPath), 0700, true);
         }
         file_put_contents($credentialsPath, $accessToken);
         printf("Credentials saved to %s\n", $credentialsPath);
     }
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($credentialsPath, $client->getAccessToken());
     }
     return $client;
 }
Example #2
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 #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' => '...'));
 }
 /**
  * @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 #5
1
 public function googleCallbackAction()
 {
     $response = array("status" => 0, "message" => "Thao tác không thành công");
     $code = $this->request->getPost("code", null, false);
     if ($code) {
         $google = new \Google_Client();
         $google->setApplicationName($this->config["GOOGLE_NAME"]);
         $google->setClientId($this->config["GOOGLE_ID"]);
         $google->setClientSecret($this->config["GOOGLE_SECRET"]);
         $google->setRedirectUri('postmessage');
         $scopes = array("https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email");
         $google->setScopes($scopes);
         $google->authenticate($code);
         $request = new \Google_Http_Request("https://www.googleapis.com/oauth2/v2/userinfo?alt=json");
         $userinfo = $google->getAuth()->authenticatedRequest($request);
         $response = $userinfo->getResponseBody();
         $userinfo = json_decode($response, true);
         $id = $userinfo["id"];
         $username = explode("@", $userinfo["email"]);
         $username = $username[0] . "_gg_" . $id;
         $data_user = array("email" => $userinfo["email"], "nickname" => $userinfo["name"], "username" => $username, "id" => $id);
         $response = $this->doSocialLogin($data_user);
     }
     echo json_encode($response);
     exit;
 }
Example #6
0
 /**
  * @param \Google_Client $client
  */
 public function __construct(\Google_Client $client)
 {
     $this->client = $client;
     $this->client->setClientId(\Config::get('google.client_id'));
     $this->client->setClientSecret(\Config::get('google.client_secret'));
     $this->client->setDeveloperKey(\Config::get('google.api_key'));
     $this->client->setRedirectUri(\Config::get('app.url') . "/loginCallback");
     $this->client->setScopes(['https://www.googleapis.com/auth/youtube']);
     $this->client->setAccessType('offline');
 }
Example #7
0
 /**
  * Init all the youtube client service stuff.
  *
  * Instead of instantiating the service in the constructor, we delay
  * it until really neeed because it's really memory hungry (2MB). That
  * way the editor or any other artifact requiring repository instantiation
  * can do it in a cheap way. Sort of lazy loading the plugin.
  */
 private function init_youtube_service()
 {
     global $CFG;
     if (!isset($this->service)) {
         require_once $CFG->libdir . '/google/lib.php';
         $this->client = get_google_client();
         $this->client->setDeveloperKey($this->apikey);
         $this->client->setScopes(array(Google_Service_YouTube::YOUTUBE_READONLY));
         $this->service = new Google_Service_YouTube($this->client);
     }
 }
Example #8
0
 /**
  * Constructor.
  *
  * @param int $repositoryid repository instance id.
  * @param int|stdClass $context a context id or context object.
  * @param array $options repository options.
  * @param int $readonly indicate this repo is readonly or not.
  * @return void
  */
 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0)
 {
     parent::__construct($repositoryid, $context, $options, $readonly = 0);
     $callbackurl = new moodle_url(self::CALLBACKURL);
     $this->client = new Google_Client();
     $this->client->setClientId(get_config('googledocs', 'clientid'));
     $this->client->setClientSecret(get_config('googledocs', 'secret'));
     $this->client->setScopes(array('https://www.googleapis.com/auth/drive.readonly'));
     $this->client->setRedirectUri($callbackurl->out(false));
     $this->service = new Google_DriveService($this->client);
     $this->check_login();
 }
 /**
  * Init all the m27tube client service stuff.
  *
  * Instead of instantiating the service in the constructor, we delay
  * it until really neeed because it's really memory hungry (2MB). That
  * way the editor or any other artifact requiring repository instantiation
  * can do it in a cheap way. Sort of lazy loading the plugin.
  */
 private function init_m27tube_service()
 {
     global $CFG;
     if (!isset($this->service)) {
         require_once $CFG->dirroot . '/repository/m27tube/google/lib.php';
         require_once $CFG->dirroot . '/repository/m27tube/google/Google/Service/YouTube.php';
         $this->client = get_google_client();
         $this->client->setDeveloperKey($this->apikey);
         $this->client->setScopes(array(Google_Service_YouTube::YOUTUBE_READONLY));
         $this->service = new Google_Service_YouTube($this->client);
     }
 }
Example #10
0
 /**
  * Constructor.
  *
  * @param int $repositoryid repository instance id.
  * @param int|stdClass $context a context id or context object.
  * @param array $options repository options.
  * @param int $readonly indicate this repo is readonly or not.
  * @return void
  */
 public function __construct($repositoryid, $context = SYSCONTEXTID, $options = array(), $readonly = 0)
 {
     parent::__construct($repositoryid, $context, $options, $readonly = 0);
     $callbackurl = new moodle_url(self::CALLBACKURL);
     $this->client = get_google_client();
     $this->client->setClientId(get_config('googledocs', 'clientid'));
     $this->client->setClientSecret(get_config('googledocs', 'secret'));
     $this->client->setScopes(array(Google_Service_Drive::DRIVE_READONLY));
     $this->client->setRedirectUri($callbackurl->out(false));
     $this->service = new Google_Service_Drive($this->client);
     $this->check_login();
 }
Example #11
0
 /**
  * Sets the required params for authentication 
  * 
  * @param string $client_id our app's client id
  * @param string $client_secret our app's client secret 
  * @param string $redirect_uri where will the auth server send the client 
  * after generating an authorization code to authenticate
  * @param null|string $token token obtained when a code is authenticated
  * @param null|string $code response code to authenticate
  * @param null|array $scopes array of strings with OAuth2/google scopes 
  * to requested
  * @param null|Google_Client $client
  * @param bool $debug defaults to false
  */
 public function __construct($client_id, $client_secret, $redirect_uri, $token = null, $code = null, $scopes = null, $client = null, $debug = null)
 {
     $this->client_id = $client_id;
     $this->client_secret = $client_secret;
     $this->redirect_uri = $redirect_uri;
     $this->code = $code;
     $this->token = $token;
     if ($scopes !== null) {
         $this->scopes = $scopes;
     }
     if (is_bool($this->debug)) {
         $this->debug = $debug;
     } else {
         $this->debug = false;
     }
     if ($client === null) {
         $this->client = new Google_Client();
         $this->client->setClientId($this->client_id);
         $this->client->setClientSecret($this->client_secret);
         $this->client->setRedirectUri($this->redirect_uri);
         if ($token !== null) {
             $this->client->setAccessToken($token);
         }
         $this->client->setScopes($this->scopes);
     }
 }
 /**
  * Return Google Content Client Instance
  *
  * @param int  $storeId
  * @param bool $noAuthRedirect
  *
  * @return bool|Google_Client
  */
 public function getClient($storeId, $noAuthRedirect = false)
 {
     if (isset($this->_client)) {
         if ($this->_client->isAccessTokenExpired()) {
             return $this->redirectToAuth($storeId, $noAuthRedirect);
         }
         return $this->_client;
     }
     $clientId = $this->getConfig()->getConfigData('client_id', $storeId);
     $clientSecret = $this->getConfig()->getClientSecret($storeId);
     $accessToken = $this->_getAccessToken($storeId);
     if (!$clientId || !$clientSecret) {
         Mage::getSingleton('adminhtml/session')->addError("Please specify Google Content API access data for this store!");
         return false;
     }
     if (!isset($accessToken) || empty($accessToken)) {
         return $this->redirectToAuth($storeId, $noAuthRedirect);
     }
     $this->_client = new Google_Client();
     $this->_client->setApplicationName(self::APPNAME);
     $this->_client->setClientId($clientId);
     $this->_client->setClientSecret($clientSecret);
     $this->_client->setScopes('https://www.googleapis.com/auth/content');
     $this->_client->setAccessToken($accessToken);
     if ($this->_client->isAccessTokenExpired()) {
         return $this->redirectToAuth($storeId, $noAuthRedirect);
     }
     if ($this->getConfig()->getIsDebug($storeId)) {
         $this->_client->setLogger(Mage::getModel('gshoppingv2/logger', $this->_client)->setStoreID($storeId));
     }
     return $this->_client;
 }
Example #13
0
 public function callback()
 {
     $client = new Google_Client();
     $client->setApplicationName($this->__app_name);
     $client->setClientId($this->__client_id);
     $client->setClientSecret($this->__client_secret);
     $client->setRedirectUri($this->__redirect_uri);
     $client->setDeveloperKey($this->__develop_key);
     $client->setScopes('https://www.googleapis.com/auth/calendar');
     $client->setAccessType('offline');
     if (isset($_GET['code'])) {
         $client->authenticate($_GET['code']);
         $_SESSION['token'] = $client->getAccessToken();
         $this->Session->delete('HTTP_REFERER');
         header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
     }
     // 呼び出し先
     if (isset($_SESSION['oauth_referer'])) {
         $url = $_SESSION['oauth_referer'];
         $this->Session->delete('oauth_referer');
     } else {
         $url = 'index';
     }
     $this->redirect('/');
 }
Example #14
0
 /**
  * Login to facebook and get the associated cloudrexx user.
  */
 public function login()
 {
     $client = new \Google_Client();
     $client->setApplicationName('Contrexx Login');
     $client->setClientId($this->applicationData[0]);
     $client->setClientSecret($this->applicationData[1]);
     $client->setRedirectUri(\Cx\Lib\SocialLogin::getLoginUrl(self::OAUTH_PROVIDER));
     $client->setDeveloperKey($this->applicationData[2]);
     $client->setUseObjects(true);
     $client->setApprovalPrompt('auto');
     $client->setScopes(self::$scopes);
     self::$google = new \Google_Oauth2Service($client);
     self::$googleplus = new \Google_PlusService($client);
     if (isset($_GET['code'])) {
         try {
             $client->authenticate();
         } catch (\Google_AuthException $e) {
         }
     }
     if (!$client->getAccessToken()) {
         \Cx\Core\Csrf\Controller\Csrf::header('Location: ' . $client->createAuthUrl());
         exit;
     }
     self::$userdata = $this->getUserData();
     $this->getContrexxUser(self::$userdata['oauth_id']);
 }
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');
    $credentialsPath = CREDENTIALS_PATH;
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n%s\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        $accessToken = $client->authenticate($authCode);
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}
Example #16
0
function getClient()
{
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET);
    $client->setAccessType('offline');
    // Load previously authorized credentials from a file.
    $credentialsPath = expandHomeDirectory(CREDENTIAL_PATH);
    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        printf("Open the following link in your browser:\n\n\t%s\n\n", $authUrl);
        print 'Enter verification code: ';
        $authCode = trim(fgets(STDIN));
        // Exchange authorization code for an access token.
        $accessToken = $client->authenticate($authCode);
        // Store the credentials to disk.
        if (!file_exists(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        file_put_contents($credentialsPath, $accessToken);
        printf("Credentials saved to %s\n", $credentialsPath);
    }
    $client->setAccessToken($accessToken);
    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client->refreshToken($client->getRefreshToken());
        file_put_contents($credentialsPath, $client->getAccessToken());
    }
    return $client;
}
 /**
  * Change the scope of the calendar, can be one of \Google_Service_Calendar::CALENDAR or \Google_Service_Calendar::CALENDAR_READONLY
  *
  * @param string $scope
  * @throws \KevinDitscheid\KdCalendar\Exception\ScopeNotSupportedException
  */
 public function changeScope($scope)
 {
     if ($scope !== \Google_Service_Calendar::CALENDAR || $scope !== \Google_Service_Calendar::CALENDAR_READONLY) {
         throw new \KevinDitscheid\KdCalendar\Exception\ScopeNotSupportedException("The scope \"{$scope}\" is not supported!", 1454959374);
     }
     $this->client->setScopes($scope);
 }
 /**
  * @throws MissingConfigurationException
  * @return \Google_Client
  */
 public function create()
 {
     $client = new \Google_Client();
     $requiredAuthenticationSettings = array('applicationName', 'clientId', 'clientSecret', 'developerKey');
     foreach ($requiredAuthenticationSettings as $key) {
         if (!isset($this->authenticationSettings[$key])) {
             throw new MissingConfigurationException(sprintf('Missing setting "TYPO3.Neos.GoogleAnalytics.authentication.%s"', $key), 1415796352);
         }
     }
     $client->setApplicationName($this->authenticationSettings['applicationName']);
     $client->setClientId($this->authenticationSettings['clientId']);
     $client->setClientSecret($this->authenticationSettings['clientSecret']);
     $client->setDeveloperKey($this->authenticationSettings['developerKey']);
     $client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
     $client->setAccessType('offline');
     $accessToken = $this->tokenStorage->getAccessToken();
     if ($accessToken !== NULL) {
         $client->setAccessToken($accessToken);
         if ($client->isAccessTokenExpired()) {
             $refreshToken = $this->tokenStorage->getRefreshToken();
             $client->refreshToken($refreshToken);
         }
     }
     return $client;
 }
 public static function revokeAccessToken()
 {
     $xmpData = erLhcoreClassModelChatConfig::fetch('xmp_data');
     $data = (array) $xmpData->data;
     try {
         if (isset($data['gtalk_client_token']) && $data['gtalk_client_token'] != '') {
             require_once 'lib/core/lhxmp/google/Google_Client.php';
             $client = new Google_Client();
             $client->setApplicationName('Live Helper Chat');
             $client->setScopes(array("https://www.googleapis.com/auth/googletalk", "https://www.googleapis.com/auth/userinfo.email"));
             $client->setClientId($data['gtalk_client_id']);
             $client->setClientSecret($data['gtalk_client_secret']);
             $client->setAccessType('offline');
             $client->setApprovalPrompt('force');
             $token = $data['gtalk_client_token'];
             $client->setAccessToken($data['gtalk_client_token']);
             // Refresh token if it's
             if ($client->isAccessTokenExpired()) {
                 $tokenData = json_decode($token);
                 $client->refreshToken($tokenData->refresh_token);
                 $accessToken = $client->getAccessToken();
             }
             if ($accessToken = $client->getAccessToken()) {
                 $client->revokeToken();
             }
             unset($data['gtalk_client_token']);
             $xmpData->value = serialize($data);
             $xmpData->saveThis();
         }
         return true;
     } catch (Exception $e) {
         throw $e;
     }
 }
 public static function getClient()
 {
     $creds = GoogleSessionController::getCreds();
     $client = new Google_Client();
     $env = Config::getEnvironment();
     if ($env == 'local' && $creds->oauth_local_path) {
         $client->setAuthConfigFile($creds->oauth_local_path);
     } else {
         if ($creds->oauth_remote_path) {
             $client->setAuthConfigFile($creds->oauth_remote_path);
         } else {
             $client->setApplicationName($creds->app_name);
             $client->setClientId($creds->client_id);
             $client->setClientSecret($creds->client_secret);
         }
     }
     $client->setRedirectUri(GoogleSessionController::getRedirectURI());
     $hd = Config::get('config.google.hd');
     if ($hd) {
         $client->setHostedDomain($hd);
     }
     $client->setAccessType('offline');
     $client->addScope("https://www.googleapis.com/auth/userinfo.profile");
     $client->addScope("https://www.googleapis.com/auth/userinfo.email");
     $client->setScopes($creds->scopes);
     return $client;
 }
/**
 * Returns an authorized API client.
 * @return Google_Client the authorized client object
 */
function getClient()
{
    global $credentialsPath;
    $client = new Google_Client();
    $client->setApplicationName(APPLICATION_NAME);
    $client->setScopes(GAPI_SCOPES);
    $client->setAuthConfigFile(CLIENT_SECRET_PATH);
    $client->setAccessType('offline');


    if (file_exists($credentialsPath)) {
        $accessToken = file_get_contents($credentialsPath);
    } else {
        die("Please, get token via connect.php");
    }

    $client->setAccessToken($accessToken);

    // Refresh the token if it's expired.
    if ($client->isAccessTokenExpired()) {
        $client = refreshToken($client);
    }

    return $client;
}
Example #22
0
function getClient()
{
    $config = (include __DIR__ . '/ini.php');
    $client = new Google_Client();
    $client->setApplicationName("Webkameleon");
    $client->setClientId($config['oauth2_client_id']);
    $client->setClientSecret($config['oauth2_client_secret']);
    $client->setRedirectUri($config['oauth2_redirect_uri']);
    $client->setScopes($config['oauth2_scopes']);
    $client->setState('offline');
    $client->setAccessType('offline');
    $client->setApprovalPrompt('force');
    if (isset($_GET['code'])) {
        $client->authenticate($_GET['code']);
        die($client->getAccessToken());
    } elseif (!isset($config['token'])) {
        Header('Location: ' . $client->createAuthUrl());
    } else {
        $client->setAccessToken($config['token']);
        if ($client->isAccessTokenExpired()) {
            $token = json_decode($config['token'], true);
            $client->refreshToken($token['refresh_token']);
        }
    }
    return $client;
}
 /**
  *  get google client
  *  @return Google_Client the authorized client object
  */
 public static function getClient()
 {
     // $scopes = implode(' ', [Google_Service_Gmail::GMAIL_READONLY]);
     /*
         $scopes = [
             'https://www.googleapis.com/auth/gmail.readonly',
             'https://www.googleapis.com/auth/gmail.modify',
             'https://www.googleapis.com/auth/gmail.send',
         ];
     */
     $scopes = ['https://mail.google.com/'];
     $clientSecretFile = conf('gmail.client_secret');
     if (!file_exists($clientSecretFile)) {
         pr('Error: client secret file not found', true);
         pr('Please create "OAuth 2.0 client IDs"');
         pr('login to https://console.developers.google.com/apis/credentials/');
         exit;
     }
     $client = new Google_Client();
     $client->setScopes($scopes);
     $client->setAuthConfigFile($clientSecretFile);
     $client->setAccessType('offline');
     // $client->setApprovalPrompt('force');
     $tokenFile = conf('gmail.access_token');
     $accessToken = self::accessToken($client, $tokenFile);
     $client->setAccessToken($accessToken);
     // Refresh the token if it's expired.
     if ($client->isAccessTokenExpired()) {
         $client->refreshToken($client->getRefreshToken());
         file_put_contents($tokenFile, $client->getAccessToken());
     }
     return $client;
 }
 private function createClient()
 {
     $options = ['auth' => 'google_auth', 'exceptions' => false];
     if ($proxy = getenv('HTTP_PROXY')) {
         $options['proxy'] = $proxy;
         $options['verify'] = false;
     }
     // adjust constructor depending on guzzle version
     if (!$this->isGuzzle6()) {
         $options = ['defaults' => $options];
     }
     $httpClient = new GuzzleHttp\Client($options);
     $client = new Google_Client();
     $client->setApplicationName('google-api-php-client-tests');
     $client->setHttpClient($httpClient);
     $client->setScopes(["https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/tasks", "https://www.googleapis.com/auth/adsense", "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/drive"]);
     if ($this->key) {
         $client->setDeveloperKey($this->key);
     }
     list($clientId, $clientSecret) = $this->getClientIdAndSecret();
     $client->setClientId($clientId);
     $client->setClientSecret($clientSecret);
     $client->setCache($this->getCache());
     return $client;
 }
Example #25
0
 /**
  * Constructor stores the passed Google Client object, sets a bunch of config options from the config file, and also
  * creates and instance of the \Google_Service_YouTube class and stores this for later use.
  *
  * @param \Google_Client $client
  */
 public function __construct(\Google_Client $client)
 {
     $this->client = $client;
     $this->client->setApplicationName(\Config::get('laravel-youtube::application_name'));
     $this->client->setClientId(\Config::get('laravel-youtube::client_id'));
     $this->client->setClientSecret(\Config::get('laravel-youtube::client_secret'));
     $this->client->setScopes(\Config::get('laravel-youtube::scopes'));
     $this->client->setAccessType(\Config::get('laravel-youtube::access_type'));
     $this->client->setApprovalPrompt(\Config::get('laravel-youtube::approval_prompt'));
     $this->client->setRedirectUri(\URL::to(\Config::get('laravel-youtube::redirect_uri')));
     $this->client->setClassConfig('Google_Http_Request', 'disable_gzip', true);
     $this->youtube = new \Google_Service_YouTube($this->client);
     $accessToken = $this->getLatestAccessTokenFromDB();
     if ($accessToken) {
         $this->client->setAccessToken($accessToken);
     }
 }
 public function __construct($datastoreDatasetId)
 {
     $this->datasetId = $datastoreDatasetId;
     $client = new \Google_Client();
     $client->setScopes([Google_Service_Datastore::CLOUD_PLATFORM, Google_Service_Datastore::DATASTORE, Google_Service_Datastore::USERINFO_EMAIL]);
     $client->useApplicationDefaultCredentials();
     $this->datastore = new \Google_Service_Datastore($client);
 }
Example #27
0
 public function __construct(\Google_Client $client)
 {
     $client->setApplicationName("magicpi");
     $client->setScopes([\Google_Service_Calendar::CALENDAR_READONLY]);
     $client->setAuthConfigFile(__DIR__ . "/../config/piauth.json");
     $client->setAccessType('offline');
     $client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/auth');
     $this->client = $client;
 }
 /**
  * Returns an authorized API client.
  *
  * @return \Google_Client the authorized client object
  */
 public function getClient()
 {
     $client = new \Google_Client();
     $client->setApplicationName($this->applicationName);
     $client->setScopes(implode(' ', $this->scopes));
     $client->setAuthConfigFile($this->authConfigFile);
     $client->setAccessType('offline');
     $client->setApprovalPrompt('force');
     return $client;
 }
Example #29
-1
 public function testPrepareService()
 {
     $client = new Google_Client();
     $client->setScopes(array("scope1", "scope2"));
     $scopes = $client->prepareScopes();
     $this->assertEquals("scope1 scope2", $scopes);
     $client->setScopes(array("", "scope2"));
     $scopes = $client->prepareScopes();
     $this->assertEquals(" scope2", $scopes);
     $client->setScopes("scope2");
     $client->addScope("scope3");
     $client->addScope(array("scope4", "scope5"));
     $scopes = $client->prepareScopes();
     $this->assertEquals("scope2 scope3 scope4 scope5", $scopes);
     $client->setClientId('test1');
     $client->setRedirectUri('http://localhost/');
     $client->setScopes(array("http://test.com", "scope2"));
     $scopes = $client->prepareScopes();
     $this->assertEquals("http://test.com scope2", $scopes);
     $this->assertEquals('' . 'https://accounts.google.com/o/oauth2/auth' . '?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2F' . '&client_id=test1' . '&scope=http%3A%2F%2Ftest.com+scope2&access_type=online' . '&approval_prompt=auto', $client->createAuthUrl());
     // This should not trigger a request.
     $client->setDefer(true);
     $dr_service = new Google_Service_Drive($client);
     $this->assertInstanceOf('Google_Http_Request', $dr_service->files->listFiles());
 }
Example #30
-1
 function setAppConfig($approval = 'auto')
 {
     $this->client = new Google_Client();
     /* Set Retries */
     $this->client->setClassConfig('Google_Task_Runner', 'retries', 5);
     $this->userInfoService = new Google_Service_Oauth2($this->client);
     $this->googleDriveService = new Google_Service_Drive($this->client);
     $this->googleUrlshortenerService = new Google_Service_Urlshortener($this->client);
     if (!empty($this->settings['googledrive_app_client_id']) && !empty($this->settings['googledrive_app_client_secret'])) {
         $this->client->setClientId($this->settings['googledrive_app_client_id']);
         $this->client->setClientSecret($this->settings['googledrive_app_client_secret']);
     } else {
         $this->client->setClientId('538839470620-fvjmtsvik53h255bnu0qjmbr8kvd923i.apps.googleusercontent.com');
         $this->client->setClientSecret('UZ1I3I-D4rPhXpnE8T1ggGhE');
     }
     $this->client->setRedirectUri('http://www.florisdeleeuw.nl/use-your-drive/index.php');
     $this->client->setApprovalPrompt($approval);
     $this->client->setAccessType('offline');
     $this->client->setScopes(array('https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/urlshortener'));
     $page = isset($_GET["page"]) ? '?page=' . $_GET["page"] : '';
     $location = get_admin_url(null, 'admin.php' . $page);
     $this->client->setState(strtr(base64_encode($location), '+/=', '-_~'));
     /* Logger */
     $this->client->setClassConfig('Google_Logger_File', array('file' => USEYOURDRIVE_CACHEDIR . '/log', 'mode' => 0640, 'lock' => true));
     $this->client->setClassConfig('Google_Logger_Abstract', array('level' => 'debug', 'log_format' => "[%datetime%] %level%: %message% %context%\n", 'date_format' => 'd/M/Y:H:i:s O', 'allow_newlines' => true));
     /* Uncomment the following line to log communcations.
      * The log is located in /cache/log
      */
     //$this->client->setLogger(new Google_Logger_File($this->client));
     return true;
 }