本文整理汇总了PHP中Google_Client类的典型用法代码示例。如果您正苦于以下问题:PHP Google_Client类的具体用法?PHP Google_Client怎么用?PHP Google_Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Google_Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: execute
/**
* @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();
}
示例2: make
/**
* @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']));
}
示例3: getClient
/**
* 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;
}
示例4: setupTestClient
/**
* 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;
}
示例5: createAnalyticsService
/**
* @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;
}
示例6: __construct
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);
}
示例7: actionSearch
/**
* 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));
}
示例8: execute
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);
}
示例9: actionRefresh
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()));
}
}
示例10: newYoutubeService
function newYoutubeService($key)
{
$client = new Google_Client();
$client->setDeveloperKey($key);
$service = new Google_Service_YouTube($client);
return $service;
}
示例11: _init_service
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);
}
示例12: update_with_api
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!");
}
示例13: getService
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 = 'taco-tester@nodal-strength-118806.iam.gserviceaccount.com';
//My email
$service_account_email = 'test-1-service-account@decisive-force-119018.iam.gserviceaccount.com';
$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;
}
示例14: validateEntity
/**
* @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;
}
}
示例15: index
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);
}