/** * @see Command */ protected function execute(InputInterface $input, OutputInterface $output) { /** @var \Doctrine\ORM\EntityManager $em */ $em = $this->getContainer()->get('doctrine.orm.default_entity_manager'); $campaignRepo = $em->getRepository('VifeedCampaignBundle:Campaign'); $campaigns = new ArrayCollection($campaignRepo->getActiveCampaigns()); $hashes = []; foreach ($campaigns as $campaign) { /** @var Campaign $campaign */ $hashes[] = $campaign->getHash(); } $hashes = array_unique($hashes); $client = new \Google_Client(); $client->setDeveloperKey($this->getContainer()->getParameter('google.api.key')); $youtube = new \Google_Service_YouTube($client); /* Опытным путём выяснилось, что ютуб принимает не больше 50 хешей за раз */ $hash = 'TjvivnmWcn4'; $request = $youtube->videos->listVideos('status', ['id' => $hash]); foreach ($request as $video) { /** @var \Google_Service_YouTube_Video $video */ /** @var \Google_Service_YouTube_VideoStatistics $stats */ $stats = $video->getStatistics(); $hash = $video->getId(); /* не исключается ситуация, что может быть несколько кампаний с одинаковым hash */ $filteredCampaigns = $campaigns->filter(function (Campaign $campaign) use($hash) { return $campaign->getHash() == $hash; }); foreach ($filteredCampaigns as $campaign) { $campaign->setSocialData('youtubeViewCount', $stats->getViewCount())->setSocialData('youtubeCommentCount', $stats->getCommentCount())->setSocialData('youtubeFavoriteCount', $stats->getFavoriteCount())->setSocialData('youtubeLikeCount', $stats->getLikeCount())->setSocialData('youtubeDislikeCount', $stats->getDislikeCount()); $em->persist($campaign); } } $em->flush(); }
/** * @param string $name * @return \League\Flysystem\AdapterInterface * @throws \RuntimeException */ public static function make($name) { $connections = Config::get('storage.connections'); if (!isset($connections[$name])) { throw new \RuntimeException(sprintf('The storage connection %d does not exist.', $name)); } $connection = $connections[$name]; $connection['adapter'] = strtoupper($connection['adapter']); switch ($connection['adapter']) { case 'LOCAL': return new Local($connection['root_path'], $connection['public_url_base']); case 'RACKSPACE': $service = isset($connection['service']) ? Config::get($connection['service']) : Config::get('services.rackspace'); $client = new Rackspace($service['api_endpoint'], array('username' => $service['username'], 'tenantName' => $service['tenant_name'], 'apiKey' => $service['api_key'])); $store = $client->objectStoreService($connection['store'], $connection['region']); $container = $store->getContainer($connection['container']); return new RackspaceAdapter($container); case 'AWS': $service = isset($connection['service']) ? Config::get($connection['service']) : Config::get('services.aws'); $client = S3Client::factory(array('credentials' => array('key' => $service['access_key'], 'secret' => $service['secret_key']), 'region' => $service['region'], 'version' => 'latest')); return new AwsS3Adapter($client, $connection['bucket']); case 'GCLOUD': $service = isset($connection['service']) ? Config::get($connection['service']) : Config::get('services.google_cloud'); $credentials = new \Google_Auth_AssertionCredentials($service['service_account'], [\Google_Service_Storage::DEVSTORAGE_FULL_CONTROL], file_get_contents($service['key_file']), $service['secret']); $config = new \Google_Config(); $config->setAuthClass(GoogleAuthOAuth2::class); $client = new \Google_Client($config); $client->setAssertionCredentials($credentials); $client->setDeveloperKey($service['developer_key']); $service = new \Google_Service_Storage($client); return new GoogleStorageAdapter($service, $connection['bucket']); } throw new \RuntimeException(sprintf('The storage adapter %s is invalid.', $connection['adapter'])); }
/** * @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' => '...')); }
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; }
/** * @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; } }
/** * 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; }
/** * Setup the Google Cient with our 'monitored' HTTP IO * * @return \Google_Client */ private function setupTestClient() { $obj_client = new \Google_Client(); $this->obj_fake_io = new Google_IO_Fake($obj_client); $obj_client->setIo($this->obj_fake_io); return $obj_client; }
/** * @return object | $service | Google Analytics Service Object used to run queries **/ private function createAnalyticsService() { /** * Create and Authenticate Google Analytics Service Object **/ $client = new Google_Client(); $client->setApplicationName(GOOGLE_API_APP_NAME); /** * Makes sure Private Key File exists and is readable. If you get an error, check path in apiConfig.php **/ if (!file_exists(GOOGLE_API_PRIVATE_KEY_FILE)) { array_push($GLOBALS['criticalErrors'], "CRITICAL-ERROR: Unable to find GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE); criticalErrorOccurred($criticalErrors, $errors); exit("CRITICAL-ERROR: Unable to find GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE . ' Backup aborted.'); } elseif (!is_readable(GOOGLE_API_PRIVATE_KEY_FILE)) { array_push($GLOBALS['criticalErrors'], "CRITICAL-ERROR: Unable to read GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE); criticalErrorOccurred($criticalErrors, $errors); exit("CRITICAL-ERROR: Unable to read GOOGLE_API_PRIVATE_KEY_FILE p12 file at " . GOOGLE_API_PRIVATE_KEY_FILE . ' Backup aborted.'); } $client->setAssertionCredentials(new Google_AssertionCredentials(GOOGLE_API_SERVICE_EMAIL, array('https://www.googleapis.com/auth/analytics.readonly'), file_get_contents(GOOGLE_API_PRIVATE_KEY_FILE))); $client->setClientId(GOOGLE_API_SERVICE_CLIENT_ID); $client->setUseObjects(true); $service = new Google_AnalyticsService($client); return $service; }
public function __construct($clientId, $serviceAccountName, $key) { $client = new Google_Client(); $client->setClientId($clientId); $client->setAssertionCredentials(new Google_Auth_AssertionCredentials($serviceAccountName, $this->scope, file_get_contents($key))); $this->sef = new Google_Service_Drive($client); }
/** * Find profiles matching search string */ public function actionSearch($searchString, $nextPageToken = null) { $creds = GooglePlusResources::getGooglePlusAPICredentials(); if (!$creds) { throw new CException(Yii::t('app', 'Google+ integration isn\'t configured.')); } $client = new Google_Client(); $client->setDeveloperKey($creds['apiKey']); $plus = new Google_Service_Plus($client); $params = array(); if ($nextPageToken) { $params['pageToken'] = $nextPageToken; } $params['fields'] = 'nextPageToken,items(displayName,image/url,url,id)'; try { $searchResults = $plus->people->search($searchString, $params); } catch (Google_Exception $e) { throw new CHttpException(500, Yii::t('app', 'Failed to retrieve Google+ profiles.')); } $profiles = array(); foreach ($searchResults->items as $item) { $profiles[] = array('displayName' => $item->displayName, 'image' => $item->image ? $item->image->url : null, 'url' => $item->url, 'id' => $item->id); } echo CJSON::encode(array('profiles' => $profiles, 'nextPageToken' => $searchResults->nextPageToken)); }
/** * @visible for testing. * * @param Google_Http_Request $request * * @return Google_Http_Request|bool Returns the cached object or * false if the operation was unsuccessful. */ public function getCachedRequest(Google_Http_Request $request) { if (false === Google_Http_CacheParser::isRequestCacheable($request)) { return false; } return $this->client->getCache()->get($request->getCacheKey()); }
public function execute() { $body = ''; $classes = array(); $batchHttpTemplate = <<<EOF --%s Content-Type: application/http Content-Transfer-Encoding: binary MIME-Version: 1.0 Content-ID: %s %s%s %s EOF; /** @var Google_Http_Request $req */ foreach ($this->requests as $key => $request) { $firstLine = sprintf('%s %s HTTP/%s', $request->getMethod(), $request->getResource(), $request->getProtocolVersion()); $content = (string) $request->getBody(); $body .= sprintf($batchHttpTemplate, $this->boundary, $key, $firstLine, Request::getHeadersAsString($request), $content ? "\n" . $content : ''); $classes['response-' . $key] = $request->getHeader('X-Php-Expected-Class'); } $body .= "--{$this->boundary}--"; $body = trim($body); $url = Google_Client::API_BASE_PATH . '/' . self::BATCH_PATH; $headers = array('Content-Type' => sprintf('multipart/mixed; boundary=%s', $this->boundary), 'Content-Length' => strlen($body)); $request = $this->client->getHttpClient()->createRequest('POST', $url, ['headers' => $headers, 'body' => Stream::factory($body)]); $response = $this->client->getHttpClient()->send($request); return $this->parseResponse($response, $classes); }
function newYoutubeService($key) { $client = new Google_Client(); $client->setDeveloperKey($key); $service = new Google_Service_YouTube($client); return $service; }
public function actionRefresh() { echo "hi"; $DEVELOPER_KEY = 'AIzaSyCzTX4jeGnhS1Cvkz0KP-1rFf9EnYhrVJM'; $client = new \Google_Client(); $client->setDeveloperKey($DEVELOPER_KEY); $youtube = new \Google_Service_YouTube($client); try { $searchResponse = $youtube->search->listSearch('id,snippet', array('maxResults' => 5)); $videoResults = array(); foreach ($searchResponse['items'] as $searchResult) { array_push($videoResults, $searchResult['id']['videoId']); } $videoIds = join(',', $videoResults); $videosResponse = $youtube->videos->listVideos('snippet, statistics', array('id' => $videoIds)); Yii::$app->db->createCommand('TRUNCATE videos')->execute(); for ($i = 0; $i < sizeof($videosResponse); $i++) { $channelsResponse = $youtube->channels->listChannels('statistics', array('id' => $videosResponse[$i]['snippet']['channelId'])); Yii::$app->db->createCommand()->insert('videos', ['id_video' => $videosResponse[$i]['id'], 'id_channel' => $videosResponse[$i]['snippet']['channelId'], 'video_title' => $videosResponse[$i]['snippet']['title'], 'channel_title' => $videosResponse[$i]['snippet']['channelTitle'], 'video_description' => $videosResponse[$i]['snippet']['description'], 'video_thumbnail' => $videosResponse[$i]['snippet']['thumbnails']['medium']['url'], 'views_count' => $videosResponse[$i]['statistics']['viewCount'], 'comments_count' => $videosResponse[$i]['statistics']['commentCount'], 'likes_count' => $videosResponse[$i]['statistics']['likeCount'], 'dislikes_count' => $videosResponse[$i]['statistics']['dislikeCount'], 'subscribers_count' => $channelsResponse[0]['statistics']['subscriberCount']])->execute(); } return null; } catch (Google_Service_Exception $e) { echo sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } catch (Google_Exception $e) { echo sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage())); } }
private function _init_service($access_token) { $client = new \Google_Client(); $client->setClientId($this->_client_id); $client->setAccessToken($access_token); $this->_service = new \Google_Service_Drive($client); }
function update_with_api() { error_log("Update triggered..."); $client = new Google_Client(); global $api_key; $client->setDeveloperKey($api_key); $youtube = new Google_Service_YouTube($client); global $greyChannelIDs, $bradyChannelIDs; $vids = array(); foreach ($greyChannelIDs as $channelID) { $vids = array_merge($vids, getUploads($channelID, $youtube, 1)); } foreach ($bradyChannelIDs as $channelID) { $vids = array_merge($vids, getUploads($channelID, $youtube, 20)); } foreach ($vids as $vid) { // If this video is already in the database, delete it (we need the updated view count) addVideoReplacing($vid); } // Delete unnecessary videos from both creators. deleteExtraneousVids(); // Record the time recordUpdate(); // Clear the cache (so this update will apply) refresh(); error_log("Updated successfully!"); }
public function index() { //Config items added to global config file $clientId = $this->config->item('clientId'); $clientSecret = $this->config->item('clientSecret'); $redirectUrl = $this->config->item('redirectUrl'); #session_start(); $client = new Google_Client(); $client->setClientId($clientId); $client->setClientSecret($clientSecret); $client->setRedirectUri($redirectUrl); #$client->setScopes(array('https://spreadsheets.google.com/feeds')); $client->addScope(array('https://spreadsheets.google.com/feeds')); $client->addScope('email'); $client->addScope('profile'); $client->setApprovalPrompt('force'); //Useful if you had already granted access to this application. $client->setAccessType('offline'); //Needed to get a refresh_token $data['base_url'] = $this->config->item('base_url'); $data['auth_url'] = $client->createAuthUrl(); //Set canonical URL $data['canonical'] = $this->config->item('base_url') . 'docs'; $this->load->view('docs', $data); }
function authorizeGoogleUser($access_code) { $client = new \Google_Client(); $google = $this->config->google; $client->setApplicationName('Portal da Rede'); $client->setClientId($google->clientId); $client->setClientSecret($google->secret); $client->setRedirectUri('postmessage'); $client->addScope('https://www.googleapis.com/auth/userinfo.profile'); $client->addScope('https://www.googleapis.com/auth/userinfo.email'); $client->authenticate($access_code); $json_token = $client->getAccessToken(); $client->setAccessToken($json_token); $plus = new \Google_Service_Plus($client); $user = $plus->people->get('me'); if (!$user->emails || !is_array($user->emails)) { return; } $email = $user->emails[0]['value']; $user_email = $this->db->user_email->find_one($email); if (!$user_email) { return; } $this->login($user_email->user); }
private function refreshAuthToken(\Google_Client $client) { if ($client->isAccessTokenExpired()) { $client->refreshToken($client->getRefreshToken()); file_put_contents(CREDENTIALS_FILE, $client->getAccessToken()); } }
public function execute() { $body = ''; $classes = array(); $batchHttpTemplate = <<<EOF --%s Content-Type: application/http Content-Transfer-Encoding: binary MIME-Version: 1.0 Content-ID: %s %s%s %s EOF; /** @var Google_Http_Request $req */ foreach ($this->requests as $key => $request) { $firstLine = sprintf('%s %s HTTP/%s', $request->getMethod(), $request->getRequestTarget(), $request->getProtocolVersion()); $content = (string) $request->getBody(); $headers = ''; foreach ($request->getHeaders() as $name => $values) { $headers .= sprintf("%s:%s\r\n", $name, implode(', ', $values)); } $body .= sprintf($batchHttpTemplate, $this->boundary, $key, $firstLine, $headers, $content ? "\n" . $content : ''); $classes['response-' . $key] = $request->getHeaderLine('X-Php-Expected-Class'); } $body .= "--{$this->boundary}--"; $body = trim($body); $url = Google_Client::API_BASE_PATH . '/' . self::BATCH_PATH; $headers = array('Content-Type' => sprintf('multipart/mixed; boundary=%s', $this->boundary), 'Content-Length' => strlen($body)); $request = new Request('POST', $url, $headers, $body); $response = $this->client->execute($request); return $this->parseResponse($response, $classes); }
public function __construct() { $google = new \Google_Client(); $google->setClientId(Setting::get('google.clientId')); $google->setClientSecret(Setting::get('google.clientSecret')); $this->google = $google; }
public function get() { $callback = 'http://api.soundeavor.com/User/Auth/Login/Google/index.php'; $config = new \Google_Config(); $config->setApplicationName('Soundeavor'); $config->setClientId(Config::getConfig('GoogleClientId')); $config->setClientSecret(Config::getConfig('GoogleClientSecret')); $config->setRedirectUri($callback); $client = new \Google_Client($config); /* * Add scopes (permissions) for the client https://developers.google.com/oauthplayground/ */ $client->addScope('https://www.googleapis.com/auth/plus.me'); if (!isset($_GET['code'])) { $loginUrl = $client->createAuthUrl(); header('Location: ' . $loginUrl); } $code = $_GET['code']; $client->authenticate($code); $accessToken = $client->getAccessToken(); $accessToken = $accessToken['access_token']; $service = new \Google_Service_Plus($client); $scopes = $service->availableScopes; print_r($scopes); die; }
public function call_back() { $config = new Controllers_Api_Google_Config_App(); $client = new Google_Client(); $client->setClientId($config->config['client_id']); $client->setClientSecret($config->config['client_secret']); $client->setRedirectUri($config->config['redirect_uri']); $client->addScope("email"); $client->addScope("profile"); $service = new Google_Service_Oauth2($client); if (isset($_GET['code'])) { $client->authenticate($_GET['code']); $_SESSION['access_token'] = $client->getAccessToken(); header('Location: ' . filter_var($config->config['redirect_uri'], FILTER_SANITIZE_URL)); exit; } /************************************************ If we have an access token, we can make requests, else we generate an authentication URL. ************************************************/ if (isset($_SESSION['access_token']) && $_SESSION['access_token']) { $client->setAccessToken($_SESSION['access_token']); } else { $authUrl = $client->createAuthUrl(); } if (isset($authUrl)) { //show login url echo json_encode(array('status' => false, 'data' => $authUrl)); } else { $user = $service->userinfo->get(); //get user info echo json_encode(array('status' => true, 'data' => $user)); } }
function getClient() { $client = new Google_Client(); $client->setAuthConfigFile('includes/OAuth2/client_secret.json'); $client->setAccessToken($_SESSION['access_token']); return $client; }
public function getYouTubeVideos($maxResults = 5) { $client = new Google_Client(); $client->setDeveloperKey(self::$apiKey); $youtube = new Google_Service_YouTube($client); try { $searchResponse = $youtube->search->listSearch('id,snippet', array('type' => 'video', 'q' => urlencode($this->keyword), 'maxResults' => $maxResults, 'order' => 'viewCount')); $videos = array(); $videoIds = array(); foreach ($searchResponse['items'] as $result) { array_push($videoIds, $result['id']['videoId']); $videos[$result['id']['videoId']] = array('url' => $this->youtubeBaseURL . $result['id']['videoId'], 'thumbnail' => $result['snippet']['thumbnails']['high']['url']); } $videoResponse = $youtube->videos->listVideos('id,contentDetails,statistics', array('id' => join(',', $videoIds))); foreach ($videoResponse['items'] as $videoResult) { $duration = $this->getYouTubeDurations($videoResult['contentDetails']['duration']); $videos[$videoResult['id']]['duration'] = "{$duration[0]}:{$duration[1]}"; $videos[$videoResult['id']]['views'] = $videoResult['statistics']['viewCount']; } return $videos; } catch (Google_Service_Exception $e) { die(sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()))); } catch (Google_Exception $e) { die(sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()))); } return null; }
/** * Initializes the Google Drive connection * * @param array $params Any connection params needed * @return object **/ public static function init($params = []) { // Get the params $pparams = Plugin::params('filesystem', 'googledrive'); $app_id = isset($params['app_id']) && $params['app_id'] != '' ? $params['app_id'] : $pparams->get('app_id'); $app_secret = isset($params['app_secret']) && $params['app_secret'] != '' ? $params['app_secret'] : $pparams->get('app_secret'); $client = new \Google_Client(); $client->setClientId($app_id); $client->setClientSecret($app_secret); $client->addScope(Google_Service_Drive::DRIVE); $client->setAccessType('offline'); $client->setApprovalPrompt('force'); $client->setIncludeGrantedScopes(true); if (isset($params['app_token'])) { $accessToken = $params['app_token']; // json encode turned our array into an object, we need to undo that $accessToken = (array) $accessToken; } else { \Session::set('googledrive.app_id', $app_id); \Session::set('googledrive.app_secret', $app_secret); \Session::set('googledrive.connection_to_set_up', Request::getVar('connection', 0)); // Set upp a return and redirect to Google for auth $return = Request::getVar('return') ? Request::getVar('return') : Request::current(true); $return = base64_encode($return); $redirectUri = trim(Request::root(), '/') . '/developer/callback/googledriveAuthorize'; $client->setRedirectUri($redirectUri); Session::set('googledrive.state', $return); App::redirect($client->createAuthUrl()); } $client->setAccessToken($accessToken); $service = new \Google_Service_Drive($client); $adapter = new \Hypweb\Flysystem\GoogleDrive\GoogleDriveAdapter($service, 'root'); return $adapter; }
function getClient() { $client = new Google_Client(); $client->setApplicationName(getGAAppName()); $client->setClientId(getGAClientID()); return $client; }
function do_something_with_user($email) { global $key; $user_client = new Google_Client(); $user_client->setApplicationName("Google+ Domains API Sample"); $user_credentials = new Google_AssertionCredentials(SERVICE_ACCOUNT_EMAIL, array("https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/plus.stream.read"), $key); // Set the API Client to act on behalf of the specified user $user_credentials->sub = $email; $user_client->setAssertionCredentials($user_credentials); $user_client->setClientId(CLIENT_ID); $plusService = new Google_PlusService($user_client); // Try to retrieve Google+ Profile information about the current user try { $result = $plusService->people->get("me"); } catch (Exception $e) { printf(" / Not a Google+ User<br><br>\n"); return; } printf(" / <a href=\"%s\">Google+ Profile</a>\n", $result["url"]); // Retrieve a list of Google+ activities for the current user $activities = $plusService->activities->listActivities("me", "user", array("maxResults" => 100)); if (isset($activities["items"])) { printf(" / %s activities found<br><br>\n", count($activities["items"])); } else { printf(" / No activities found<br><br>\n"); } }
function __construct($API_SERVER_TOKEN) { $this->apiClient = new \Google_Client(); $this->apiClient->setApplicationName("EHF-YouTube-Playlist"); $this->apiClient->setDeveloperKey($API_SERVER_TOKEN); $this->apiService = new \Google_Service_YouTube($this->apiClient); }
/** * 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; }