本文整理汇总了PHP中Google_Client类的典型用法代码示例。如果您正苦于以下问题:PHP Google_Client类的具体用法?PHP Google_Client怎么用?PHP Google_Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Google_Client类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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();
}
开发者ID:bzis,项目名称:zomba,代码行数:37,代码来源:GetYouTubeDataCommand.php
示例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']));
}
开发者ID:Superbalist,项目名称:laravel4-storage,代码行数:39,代码来源:StorageAdapterFactory.php
示例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;
}
开发者ID:glennfriend,项目名称:gmail-import-use-api,代码行数:37,代码来源:GmailApiHelper.php
示例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;
}
开发者ID:gonejack,项目名称:tumblr-images-datastore,代码行数:12,代码来源:JSONTest.php
示例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;
}
开发者ID:israbbani,项目名称:analytics-archiver,代码行数:28,代码来源:Analytics.class.php
示例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);
}
开发者ID:GetInTheGo,项目名称:JohnsonFinancialService,代码行数:7,代码来源:Test2.php
示例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));
}
开发者ID:tymiles003,项目名称:X2CRM,代码行数:28,代码来源:GooglePlusController.php
示例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);
}
开发者ID:OlivierBarbier,项目名称:google-api-php-client,代码行数:31,代码来源:Batch.php
示例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()));
}
}
开发者ID:axeJustice,项目名称:YTDataAPISampleProject,代码行数:27,代码来源:SiteController.php
示例10: newYoutubeService
function newYoutubeService($key)
{
$client = new Google_Client();
$client->setDeveloperKey($key);
$service = new Google_Service_YouTube($client);
return $service;
}
开发者ID:Jeezymang,项目名称:web_skypebot,代码行数:7,代码来源:youtube_api.php
示例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);
}
开发者ID:eduardodomingos,项目名称:eduardodomingos.com,代码行数:7,代码来源:CdnEngine_GoogleDrive.php
示例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!");
}
开发者ID:abhinav4848,项目名称:Veritasium-Collector,代码行数:27,代码来源:update.php
示例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 = '[email protected]';
//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;
}
开发者ID:anniehoogendoorn,项目名称:sq1-api-client,代码行数:25,代码来源:helloAnalytics.php
示例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;
}
}
开发者ID:scalr,项目名称:scalr,代码行数:33,代码来源:GceCloudCredentialsAdapter.php
示例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);
}
开发者ID:SaintGrey,项目名称:sheets2,代码行数:25,代码来源:docs.php
示例16: authorizeGoogleUser
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);
}
开发者ID:kahvazquez,项目名称:trouble,代码行数:25,代码来源:User.php
示例17: refreshAuthToken
private function refreshAuthToken(\Google_Client $client)
{
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents(CREDENTIALS_FILE, $client->getAccessToken());
}
}
开发者ID:embracingelement,项目名称:bahai-community-site,代码行数:7,代码来源:CalendarClient.php
示例18: 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->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);
}
开发者ID:andytan2624,项目名称:andytan.net,代码行数:35,代码来源:Batch.php
示例19: __construct
public function __construct()
{
$google = new \Google_Client();
$google->setClientId(Setting::get('google.clientId'));
$google->setClientSecret(Setting::get('google.clientSecret'));
$this->google = $google;
}
开发者ID:Junyue,项目名称:zidisha2,代码行数:7,代码来源:GoogleService.php
示例20: get
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;
}
开发者ID:kris-nova,项目名称:API,代码行数:26,代码来源:Google.php
注:本文中的Google_Client类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论