function getService()
{
    // Creates and returns the Analytics service object.
    // Load the Google API PHP Client Library.
    require_once 'vendor/autoload.php';
    // Use the developers console and replace the values with your
    // service account email, and relative location of your key file.
    //Charlie's email
    // $service_account_email = '*****@*****.**';
    //My email
    $service_account_email = '*****@*****.**';
    $key_file_location = 'client_secrets.p12';
    // Create and configure a new client object.
    $client = new Google_Client();
    $client->setApplicationName("HelloAnalytics");
    $analytics = new Google_Service_Analytics($client);
    // Read the generated client_secrets.p12 key.
    $key = file_get_contents($key_file_location);
    $cred = new Google_Auth_AssertionCredentials($service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key);
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    return $analytics;
}
Example #2
1
function getTheList()
{
    require 'src/Google/autoload.php';
    $service_account_name = "*****@*****.**";
    $key_file_location = "yd-tn.p12";
    $client = new Google_Client();
    $client->setApplicationName("Members");
    $directory = new Google_Service_Directory($client);
    if (isset($_SESSION['service_token']) && $_SESSION['service_token']) {
        $client->setAccessToken($_SESSION['service_token']);
    }
    $key = file_get_contents($key_file_location);
    $cred = new Google_Auth_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/admin.directory.user'), $key);
    $cred->sub = "*****@*****.**";
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $_SESSION['service_token'] = $client->getAccessToken();
    $param = array();
    $param['domain'] = "youthdecides.org";
    $list = $directory->users->listUsers($param);
    $tab = array();
    $i = 0;
    foreach ($list as $user) {
        $tab[$i]['nom'] = strtolower($user->getName()->getFullName());
        $tab[$i]['mail'] = $user->getPrimaryEmail();
        $i++;
    }
    //echo json_encode($tab);
    return $tab;
}
 private function getService()
 {
     // Creates and returns the Analytics service object.
     // Load the Google API PHP Client Library.
     ///Users/mustafahanif/WebstormProjects/influence/application/vendor/google-api-php-client/src/Google/autoload.php
     $path = dirname(__DIR__) . '/vendor/google-api-php-client/src/Google/autoload.php';
     require_once $path;
     // Use the developers console and replace the values with your
     // service account email, and relative location of your key file.
     $service_account_email = '*****@*****.**';
     $key_file_location = dirname(__DIR__) . '/vendor/client_key.p12';
     // Create and configure a new client object.
     $client = new Google_Client();
     $client->setApplicationName("HelloAnalytics");
     $analytics = new Google_Service_Analytics($client);
     // Read the generated client_secrets.p12 key.
     $key = file_get_contents($key_file_location);
     //echo $key;
     $cred = new Google_Auth_AssertionCredentials($service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key);
     //echo $cred;
     $client->setAssertionCredentials($cred);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($cred);
     }
     return $analytics;
 }
Example #4
1
function gapps_service($domain)
{
    global $directory;
    $info = libraries_load('google-api-php-client');
    if (!$info['loaded']) {
        drupal_set_message(t('Can`t authenticate with google as library is missing check Status report or Readme for requirements, download from') . l('https://github.com/google/google-api-php-client/archive/master.zip', 'https://github.com/google/google-api-php-client/archive/master.zip'), 'error');
        return FALSE;
    }
    $client_email = variable_get('gapps_service_client_email');
    $file = file_load(variable_get('gapps_service_private_key'));
    $private_key = file_get_contents(drupal_realpath($file->uri));
    if ($domain == 'teacher') {
        $user_to_impersonate = variable_get('gapps_teacher_admin');
    } else {
        $user_to_impersonate = variable_get('gapps_student_admin');
    }
    $scopes = array('https://www.googleapis.com/auth/admin.directory.orgunit', 'https://www.googleapis.com/auth/admin.directory.group', 'https://www.googleapis.com/auth/admin.directory.group.member', 'https://www.googleapis.com/auth/admin.directory.user', 'https://www.googleapis.com/auth/admin.directory.user.alias');
    $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, $private_key);
    $credentials->sub = $user_to_impersonate;
    $client = new Google_Client();
    $client->setApplicationName('Drupal gapps module');
    $client->setAssertionCredentials($credentials);
    while ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($credentials);
    }
    $directory = new Google_Service_Directory($client);
    $_SESSION['gapps_' . $domain . '_access_token'] = $client->getAccessToken();
    if ($_SESSION['gapps_' . $domain . '_access_token']) {
        return $directory;
    } else {
        return NULL;
    }
}
Example #5
1
function gevent_service()
{
    global $calendar;
    $info = libraries_load('google-api-php-client');
    if (!$info['loaded']) {
        drupal_set_message(t('Can`t authenticate with google as library is missing check Status report or Readme for requirements, download from') . l('https://github.com/google/google-api-php-client/archive/master.zip', 'https://github.com/google/google-api-php-client/archive/master.zip'), 'error');
        return FALSE;
    }
    $client_email = variable_get('gapps_service_client_email');
    $file = file_load(variable_get('gapps_service_private_key'));
    $private_key = file_get_contents(drupal_realpath($file->uri));
    $user_to_impersonate = variable_get('gevent_admin');
    $scopes = array('https://www.googleapis.com/auth/calendar');
    $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, $private_key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer', $user_to_impersonate);
    $client = new Google_Client();
    $client->setApplicationName('Drupal gevent module');
    $client->setAssertionCredentials($credentials);
    while ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion();
    }
    $calendar = new Google_Service_Calendar($client);
    $_SESSION['gevent_access_token'] = $client->getAccessToken();
    if ($_SESSION['gevent_access_token']) {
        return $calendar;
    } else {
        return NULL;
    }
}
 private function auth()
 {
     $client = new Google_Client();
     $client->setAssertionCredentials($this->credentials);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion();
     }
     return $client;
 }
 /**
  * Return the authenticated Google Client
  *
  * @return \Google_Client
  */
 private function getClient()
 {
     $credentials = new \Google_Auth_AssertionCredentials($this->parameters['client_email'], array($this->parameters['api_url']), file_get_contents($this->container->get('kernel')->getRootDir() . "/../" . $this->parameters['api_key_file']));
     $client = new \Google_Client();
     $client->setAssertionCredentials($credentials);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion();
     }
     return $client;
 }
Example #8
1
/**
 * Returns an authorized API client.
 *
 * @param string $email
 * @return \Google_Client the authorized client object
 */
function getClient($email)
{
    $privateKey = file_get_contents('google-documents-exporter.p12');
    $credentials = new Google_Auth_AssertionCredentials($email, SCOPES, $privateKey);
    $client = new Google_Client();
    $client->setAssertionCredentials($credentials);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion();
    }
    return $client;
}
 /**
  * auth and get service instance
  */
 public function getServiceCalendar()
 {
     $scopes = array('https://www.googleapis.com/auth/calendar');
     $credential = new Google_Auth_AssertionCredentials($this->auth_email, $scopes, $this->p12_key);
     $client = new Google_Client();
     $client->setAssertionCredentials($credential);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($credential);
     }
     return new Google_Service_Calendar($client);
 }
 public static function getGoogleTokenFromKeyFile()
 {
     $client = new \Google_Client();
     $client->setClientId(SERVICE_CLIENT_ID);
     $cred = new \Google_Auth_AssertionCredentials(SERVICE_EMAIL, array('https://spreadsheets.google.com/feeds'), file_get_contents(__DIR__ . '/../service_api.p12'));
     $client->setAssertionCredentials($cred);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($cred);
     }
     $service_token = json_decode($client->getAccessToken());
     return $service_token->access_token;
 }
Example #11
1
function getGoogleTokenFromKeyFile($clientId, $clientEmail, $pathToP12File)
{
    $client = new Google_Client();
    $client->setClientId($clientId);
    $cred = new Google_AssertionCredentials($clientEmail, array('https://spreadsheets.google.com/feeds'), file_get_contents($pathToP12File));
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $service_token = json_decode($client->getAccessToken());
    return $service_token->access_token;
}
 private function _GC_getService()
 {
     $client = new Google_Client();
     $client->setApplicationName("Client_Gestion_Material_Eventos");
     $creds = new Google_Auth_AssertionCredentials(Configure::read('GC_email'), array('https://www.googleapis.com/auth/calendar'), file_get_contents(APP . Configure::read('GC_keyfile')));
     $client->setAssertionCredentials($creds);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($creds);
     }
     $service = new Google_Service_Calendar($client);
     return $service;
 }
Example #13
1
 /**
  * Returns an authorized API client.
  * @return Google_Client the authorized client object
  */
 function getClient()
 {
     $client_email = '*****@*****.**';
     $private_key = file_get_contents('/var/www/asirb/vendor/google/intranet.p12');
     $scopes = array('https://www.googleapis.com/auth/admin.directory.user');
     $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, $private_key, 'notasecret', 'http://oauth.net/grant_type/jwt/1.0/bearer', '*****@*****.**');
     $client = new Google_Client();
     $client->setAssertionCredentials($credentials);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion();
     }
     return $client;
 }
 /**
  *  Connect to Google API via oAuth 2.0
  *
  *  @return Object  Returns oAuth response
  */
 public function LogIn()
 {
     /* OAUTH 2.0 */
     $private_key = self::getPrivateKey();
     $scopes = array('https://www.googleapis.com/auth/webmasters.readonly');
     $credentials = new Google_Auth_AssertionCredentials(Config::OAUTH_CREDENTIALS_EMAIL, $scopes, $private_key);
     $client = new Google_Client();
     $client->setAssertionCredentials($credentials);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion();
     }
     return $client;
 }
Example #15
1
function getToken()
{
    $client = new Google_Client();
    $client->setApplicationName('GOOGLE_APPLICATION_NAME');
    $client->setClientId(GOOGLE_CLIENT_ID);
    $key = file_get_contents(GOOGLE_KEY_FILE);
    $cred = new Google_Auth_AssertionCredentials(GOOGLE_CLIENT_EMAIL, array(GOOGLE_SPREADSHEETS_SCOPE), $key);
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $service_token = json_decode($client->getAccessToken());
    return $service_token->access_token;
}
Example #16
1
 public function authenticate()
 {
     $client = new Google_Client();
     $client->setClientId($this->clientId);
     $client_email = $this->email;
     $privateKey = file_get_contents($this->path);
     $credentials = new Google_Auth_AssertionCredentials($this->email, array($this->scope), $privateKey);
     $client->setAssertionCredentials($credentials);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($credentials);
     }
     $tok = json_decode($client->getAccessToken());
     $this->token = $tok->access_token;
 }
 /**
  * @return \Google_Client
  */
 public function getClient()
 {
     if ($this->_client == null) {
         $this->_client = new Google_Client();
         $this->_client->setApplicationName($this->appName);
         $key = file_get_contents(Yii::getAlias($this->keyFile));
         $cred = new Google_Auth_AssertionCredentials($this->serviceAccountEmail, $this->scopes, $key);
         $this->_client->setAssertionCredentials($cred);
         if ($this->_client->getAuth()->isAccessTokenExpired()) {
             $this->_client->getAuth()->refreshTokenWithAssertion($cred);
         }
     }
     return $this->_client;
 }
function writeGoogleSpreadsheet($data)
{
    if (empty($data)) {
        return FALSE;
    }
    session_start();
    include_once "google-api-php-client/examples/templates/base.php";
    require_once realpath(dirname(__FILE__) . '/google-api-php-client/src/Google/autoload.php');
    $client_id = '76948799826-4u3c0b83kqcas2j034rivdsp2ik8qjp5.apps.googleusercontent.com';
    $service_account_name = '*****@*****.**';
    $key_file_location = 'FeedBackMail-de82c85c3106.p12';
    if (strpos($client_id, "googleusercontent") == false || !strlen($service_account_name) || !strlen($key_file_location)) {
        echo missingServiceAccountDetailsWarning();
        exit;
    }
    $client = new Google_Client();
    $client->setApplicationName("FeedBackMail");
    $service = new Google_Service_Drive($client);
    if (isset($_SESSION['service_token'])) {
        $client->setAccessToken($_SESSION['service_token']);
    }
    $key = file_get_contents($key_file_location);
    $cred = new Google_Auth_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds'), $key);
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $_SESSION['service_token'] = $client->getAccessToken();
    $resultArray = json_decode($_SESSION['service_token']);
    $accessToken = $resultArray->access_token;
    $fileId = '1vlMTld652YHY0ey3NshxKjo7WriaGsv31dMpS8Fhp30';
    $url = "https://spreadsheets.google.com/feeds/list/{$fileId}/od6/private/full";
    $method = 'POST';
    $headers = ["Authorization" => "Bearer {$accessToken}", 'Content-Type' => 'application/atom+xml'];
    $postBody = '<entry xmlns="http://www.w3.org/2005/Atom" xmlns:gsx="http://schemas.google.com/spreadsheets/2006/extended">';
    $postBody .= '<gsx:created>' . $data['date_created'] . '</gsx:created>';
    $postBody .= '<gsx:fio>' . $data['fio'] . '</gsx:fio>';
    $postBody .= '<gsx:email>' . $data['email'] . '</gsx:email>';
    $postBody .= '<gsx:message>' . $data['message'] . '</gsx:message>';
    $postBody .= '</entry>';
    $req = new Google_Http_Request($url, $method, $headers, $postBody);
    $curl = new Google_IO_Curl($client);
    try {
        $curl->executeRequest($req);
        return TRUE;
    } catch (Exception $e) {
        return FALSE;
    }
}
 /**
  * Get the response from a service account authorization
  * This response will have the access token that can be
  * used for subsequent Google Api Calls
  * @param $params
  * @return json_object
  */
 public static function getAuthByServiceAccount($params)
 {
     $defaultParams = array('application_name' => '', 'client_id' => '', 'client_email' => '', 'key_file_location' => '', 'scopes' => array('https://www.googleapis.com/auth/drive', 'https://spreadsheets.google.com/feeds'));
     $params = array_merge($defaultParams, $params);
     $client = new \Google_Client();
     $client->setApplicationName($params['application_name']);
     $keyContents = file_get_contents($params['key_file_location']);
     $client->setAssertionCredentials(new \Google_Auth_AssertionCredentials($params['client_email'], $params['scopes'], $keyContents));
     $client->setClientId($params['client_id']);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion();
     }
     $authResponse = $client->getAccessToken();
     return json_decode($authResponse);
 }
function getService()
{
    require_once 'google-api-php-client/src/Google/autoload.php';
    $client = new Google_Client();
    $client->setApplicationName("Metafluanalytics");
    $analytics = new Google_Service_Analytics($client);
    global $key_file_location, $service_account_email;
    $key = file_get_contents($key_file_location);
    $cred = new Google_Auth_AssertionCredentials($service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key);
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    return $analytics;
}
 /**
  * Perform an authenticated api call
  *
  * @param string $url
  * @return Google_Http_Request
  */
 public function call($url)
 {
     $request = new Google_Http_Request($url);
     $this->client->getAuth()->sign($request);
     return $this->client->getIo()->makeRequest($request);
     /* @var $response Google_Http_Request */
 }
Example #22
1
 public function testSettersGetters()
 {
     $client = new Google_Client();
     $client->setClientId("client1");
     $client->setClientSecret('client1secret');
     $client->setState('1');
     $client->setApprovalPrompt('force');
     $client->setAccessType('offline');
     $client->setRedirectUri('localhost');
     $client->setApplicationName('me');
     $this->assertEquals('object', gettype($client->getAuth()));
     $this->assertEquals('object', gettype($client->getCache()));
     $this->assertEquals('object', gettype($client->getIo()));
     $client->setAuth(new Google_Auth_Simple($client));
     $client->setAuth(new Google_Auth_OAuth2($client));
     try {
         $client->setAccessToken(null);
         die('Should have thrown an Google_Auth_Exception.');
     } catch (Google_Auth_Exception $e) {
         $this->assertEquals('Could not json decode the token', $e->getMessage());
     }
     $token = json_encode(array('access_token' => 'token'));
     $client->setAccessToken($token);
     $this->assertEquals($token, $client->getAccessToken());
 }
Example #23
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;
 }
/**
 * Get Analytics API object
 */
function getService($service_account_email, $key)
{
    // Creates and returns the Analytics service object.
    // Load the Google API PHP Client Library.
    require_once __DIR__ . "/../../lib/Google/autoload.php";
    // Create and configure a new client object.
    $client = new Google_Client();
    $client->setApplicationName('Google Analytics Dashboard');
    $analytics = new Google_Service_Analytics($client);
    // Read the generated client_secrets.p12 key.
    $cred = new Google_Auth_AssertionCredentials($service_account_email, array(Google_Service_Analytics::ANALYTICS_READONLY), $key);
    $client->setAssertionCredentials($cred);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    return $analytics;
}
 /**
  * Authorize API with credentials
  *
  * @param \Google_Auth_AssertionCredentials $cred
  */
 public function authenticate(\Google_Auth_AssertionCredentials $cred)
 {
     $this->client = $client = new \Google_Client();
     $sitename = $this->app['config']->get('general/sitename');
     // @todo url::slugify() will be deprecated in 2.1
     $this->client->setApplicationName(\utilphp\util::slugify($sitename));
     if (isset($_SESSION['token_gapps'])) {
         $client->setAccessToken($_SESSION['token_gapps']);
     }
     $client->setClientId($this->config['ClientID']);
     $client->setAssertionCredentials($cred);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($cred);
     }
     $_SESSION[$this->getServiceSessionTk($cred->scopes)] = $client->getAccessToken();
     return $this->client;
 }
Example #26
1
/**
 * Create an authorized client that we will use to invoke BigQuery.
 *
 * @return Google_Service_Bigquery
 *
 * @throws Exception
 */
function createAuthorizedClient()
{
    $json_credentials_path = getenv('GOOGLE_APPLICATION_CREDENTIALS');
    if (!$json_credentials_path) {
        throw new Exception('Set the environment variable ' . 'GOOGLE_APPLICATION_CREDENTIALS to the path to your .json file.');
    }
    $contents = file_get_contents($json_credentials_path);
    $json_array = json_decode($contents, true);
    $credentials = new Google_Auth_AssertionCredentials($json_array['client_email'], [Google_Service_Bigquery::BIGQUERY], $json_array['private_key']);
    $client = new Google_Client();
    $client->setAssertionCredentials($credentials);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion();
    }
    $service = new Google_Service_Bigquery($client);
    return $service;
}
function pof_importer_get_google_service()
{
    set_include_path(get_include_path() . PATH_SEPARATOR . '/wp-content/plugins/pof-importer/google-api-php-client/src');
    require 'google-api-php-client/src/Google/autoload.php';
    $client_email = pof_settings_get_google_api_user();
    $private_key = pof_settings_get_google_api_certificate();
    $password = pof_settings_get_google_api_password();
    $scopes = array('https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive.metadata', 'https://www.googleapis.com/auth/drive.metadata.readonly');
    $credentials = new Google_Auth_AssertionCredentials($client_email, $scopes, $private_key, $password);
    $client = new Google_Client();
    $client->setAssertionCredentials($credentials);
    if ($client->getAuth()->isAccessTokenExpired()) {
        $client->getAuth()->refreshTokenWithAssertion();
    }
    $service = new Google_Service_Drive($client);
    return $service;
}
 private function create_client()
 {
     $full_creds_file = $this->api_creds_file;
     if (!file_exists($full_creds_file)) {
         throw new \Exception("Cannot find file " . $full_creds_file, 1);
     }
     $client = new \Google_Client();
     echo "Credentials File: " . $full_creds_file . PHP_EOL;
     $cred = $client->loadServiceAccountJson($full_creds_file, array(\Google_Service_Analytics::ANALYTICS_READONLY));
     // Setup authentication to Google.
     // This is needed because we are running via a phar file
     $client->setClassConfig("Google_IO_Curl", ["options" => [CURLOPT_CAINFO => $this->pem_file]]);
     // re-auth if needed
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($cred);
     }
     return $client;
 }
 protected function getApiClient()
 {
     if ($this->api_client == null) {
         $service_account_email = $this->service_account_email;
         $key_file_location = $this->key_file_location;
         $client = new \Google_Client();
         $client->setApplicationName("Meexo CMS");
         $analytics = new \Google_Service_Analytics($client);
         $key = file_get_contents($key_file_location);
         $cred = new \Google_Auth_AssertionCredentials($service_account_email, array(\Google_Service_Analytics::ANALYTICS_READONLY), $key);
         $client->setAssertionCredentials($cred);
         if ($client->getAuth()->isAccessTokenExpired()) {
             $client->getAuth()->refreshTokenWithAssertion($cred);
         }
         $this->api_client = $analytics;
     }
     return $this->api_client;
 }
Example #30
0
 public function dashboard_display()
 {
     $this->ci->load->model("user_model");
     if (empty($this->ci->user_model->user->profile_id)) {
         return;
     }
     @session_start();
     require_once APPPATH . 'third_party/Google_api/src/Google/autoload.php';
     $client_id = '121864429952-2fb1efk8v9rhq46iud08hvg2sdcer3uu.apps.googleusercontent.com';
     //Client ID
     $service_account_name = '*****@*****.**';
     //Email Address
     $key_file_location = APPPATH . 'third_party/Google_api/src/Google/Pando-8c981025c45b.p12';
     //key.p12
     $client = new Google_Client();
     $client->setApplicationName("ApplicationName");
     $service = new Google_Service_Analytics($client);
     if (isset($_SESSION['service_token'])) {
         $client->setAccessToken($_SESSION['service_token']);
     }
     $key = file_get_contents($key_file_location);
     $cred = new Google_Auth_AssertionCredentials($service_account_name, array('https://www.googleapis.com/auth/analytics'), $key, 'notasecret');
     $client->setAssertionCredentials($cred);
     if ($client->getAuth()->isAccessTokenExpired()) {
         $client->getAuth()->refreshTokenWithAssertion($cred);
     }
     $_SESSION['service_token'] = $client->getAccessToken();
     $analytics = new Google_Service_Analytics($client);
     $profileId = "ga:95600714";
     $profileId = "ga:" . $this->ci->user_model->user->profile_id;
     // die($profileId);
     $startDate = date('Y-m-d', strtotime('-31 days'));
     // 31 days from now
     $endDate = date('Y-m-d');
     // todays date
     $metrics = "ga:sessions,ga:newUsers,ga:users,ga:percentNewSessions,ga:timeOnPage,ga:exitRate,ga:hits";
     // $metrics = "ga:dataSource";
     $optParams = array("dimensions" => "ga:date");
     try {
         $results = $analytics->data_ga->get($profileId, $startDate, $endDate, $metrics, $optParams);
     } catch (Exception $e) {
         return;
     }
     $data_analytics = new stdClass();
     $data_analytics->total_access = $results->totalsForAllResults["ga:sessions"];
     $data_analytics->new_users_percentage = $results->totalsForAllResults["ga:percentNewSessions"];
     $data_analytics->time_on_page = gmdate("H:i:s", $results->totalsForAllResults["ga:timeOnPage"]);
     $data_analytics->exit_rate = $results->totalsForAllResults["ga:exitRate"];
     $data_analytics->hits = $results->totalsForAllResults["ga:hits"];
     $data_analytics->rows = $results->rows;
     foreach ($data_analytics->rows as &$row) {
         $row["day"] = date("d", strtotime($row[0]));
         $row["month"] = date("m", strtotime($row[0]));
         $row["year"] = date("Y", strtotime($row[0]));
     }
     // dump($data_analytics);
     $data['report'] = $data_analytics;
     return $this->ci->load->view('libraries_view/new_analytics', $data, true);
 }