google-api-php-client
A PHP client library for accessing Google APIs
API Client Library for PHP (Beta) | Google Developers the php library for accessing google apis.
Hi I am using Google PHP API to upload video in PHP. I have followed this tutorial to implement this and it is working fine. But there is a problem if video is already exist in my channel it is also returning the video details and I can't find it is a rejected for duplicate.
So I cant find this is a duplicate video or not and if it is duplicate then what is the main video. Means the video details of main video from which it is compared as duplicate.
Please help me to find this is a duplicate video or not?
Source: (StackOverflow)
I am trying to use Google Oauth API to get userinfo.
It works perfectly for Google Plus API but I am trying to create a backup in case the user doesn't have google plus account.
The authentication process is correct and I even get the $userinfo object but how exactly do I access the properties. I tried $userinfo->get() but it only return the id of the user.
Am I doing something wrong? Here is the code that I am using...
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId('*********************');
$client->setClientSecret('**************');
$client->setRedirectUri('***************');
$client->setDeveloperKey('**************');
$plus = new Google_Oauth2Service($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $plus->userinfo;
print_r($userinfo->get());
} else
{
$authUrl = $client->createAuthUrl();
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' rel='nofollow' href='style.css' />
</head>
<body>
<header><h1>Google+ Sample App</h1></header>
<div class="box">
<?php if(isset($personMarkup)): ?>
<div class="me"><?php print $personMarkup ?></div>
<?php endif ?>
<?php
if(isset($authUrl)) {
print "<a class='login' rel='nofollow' href='$authUrl'>Connect Me!</a>";
} else {
print "<a class='logout' rel='nofollow' href='?logout'>Logout</a>";
}
?>
</div>
</body>
</html>
Thanks...
**EDIT***
Was missing Scopes--Added
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
works now...
Source: (StackOverflow)
I am trying to upload a video to Youtube using PHP. I am using Youtube API v3 and I am using the latest checked out source code of Google API PHP Client library.
I am using the sample code given on
https://code.google.com/p/google-api-php-client/ to perform the authentication. The authentication goes through fine but when I try to upload a video I get Google_ServiceException
with error code 500 and message as null.
I had a look at the following question asked earlier:
Upload video to youtube using php client library v3 But the accepted answer doesn't describe how to specify file data to be uploaded.
I found another similar question Uploading file with Youtube API v3 and PHP, where in the comment it is mentioned that categoryId is mandatory, hence I tried setting the categoryId in the snippet but still it gives the same exception.
I also referred to the Python code on the the documentation site ( https://developers.google.com/youtube/v3/docs/videos/insert ), but I couldn't find the function next_chunk in the client library. But I tried to put a loop (mentioned in the code snippet) to retry on getting error code 500, but in all 10 iterations I get the same error.
Following is the code snippet I am trying:
$youTubeService = new Google_YoutubeService($client);
if ($client->getAccessToken()) {
print "Successfully authenticated";
$snippet = new Google_VideoSnippet();
$snippet->setTitle = "My Demo title";
$snippet->setDescription = "My Demo descrition";
$snippet->setTags = array("tag1","tag2");
$snippet->setCategoryId(23); // this was added later after refering to another question on stackoverflow
$status = new Google_VideoStatus();
$status->privacyStatus = "private";
$video = new Google_Video();
$video->setSnippet($snippet);
$video->setStatus($status);
$data = file_get_contents("video.mp4"); // This file is present in the same directory as the code
$mediaUpload = new Google_MediaFileUpload("video/mp4",$data);
$error = true;
$i = 0;
// I added this loop because on the sample python code on the documentation page
// mentions we should retry if we get error codes 500,502,503,504
$retryErrorCodes = array(500, 502, 503, 504);
while($i < 10 && $error) {
try{
$ret = $youTubeService->videos->insert("status,snippet",
$video,
array("data" => $data));
// tried the following as well, but even this returns error code 500,
// $ret = $youTubeService->videos->insert("status,snippet",
// $video,
// array("mediaUpload" => $mediaUpload);
$error = false;
} catch(Google_ServiceException $e) {
print "Caught Google service Exception ".$e->getCode()
. " message is ".$e->getMessage();
if(!in_array($e->getCode(), $retryErrorCodes)){
break;
}
$i++;
}
}
print "Return value is ".print_r($ret,true);
// We're not done yet. Remember to update the cached access token.
// Remember to replace $_SESSION with a real database or memcached.
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a rel='nofollow' href='$authUrl'>Connect Me!</a>";
}
Is it something that I am doing wrong?
Source: (StackOverflow)
I am trying to use the Google Drive API via their PHP Client Library to upload a large file. Currently it fails because the only method seemingly available is the "simple" upload method. Unfortunately that requires you to load the entire file as data and it hits my php memory limit. I would like to know if it is possible and see an example of how it is done. I know there is a method for resumable and chuncked uploads, but there is no documentation on how to use it.
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the APIs Console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
Source: (StackOverflow)
I am looking to implement a page view tracking system on one of my websites.
The website is a directory where suppliers can advertise their services. Suppliers have a unique profile page on the site, e.g mysite.com/directory/abc-profile.html
The idea is that suppliers can log in to their account area on the site and view stats on how many people are visiting their profile. Ideally I want to display this as :
Total views | Total today | This week | This month | This year
It does not matter if the data is not completely up to date.
I already have Google Analytics tracking code installed on the site. Is it possible to use the Google Analytics API to retrieve this data? If so, what kind of query do I need to make? I had a look on the documentation but could not figure whether the functions allow this or not.
I am using PHP and MySQL on the server.
Source: (StackOverflow)
when i use APPPATH.'libraries/Google/Client.php', all the files which are included in require_once, the sub file i.e(Auth/AssertionCredentials.php)
A PHP Error was encountered
Severity: Warning
Message: require_once(Google/Auth/AssertionCredentials.php): failed to open stream: No such file or directory
Filename: Google/Client.php
Line Number: 18
Source: (StackOverflow)
I would like to know with certainty if a YouTube video is widescreen or not using the v3 API. There are many old videos that have a 4:3 ratio, so I need to detect this.
This was possible with API v2, but it is officially retired now. Here are the API v3 docs.
An API call looks something like this:
https://www.googleapis.com/youtube/v3/videos?id=[VIDEOID]&part=snippet&key=[DEVELOPERKEY]
Also, the thumbnail data always returns dimensions of 4:3, so that doesn't help. Here is an example:
[thumbnails] => Array
(
[default] => Array
(
[url] => https://i.ytimg.com/vi/nnnnnnnnn/default.jpg
[width] => 120
[height] => 90
)
...
)
Any ideas?
(I'm currently hacking this by analyzing pixels in the thumbnails where tell-tale black bars on 4:3 videos will be.)
Here is a sample video in 4:3 ratio:
https://www.youtube.com/watch?v=zMJ-Dl4eJu8 (old martial arts video)
and one in 16:9:
https://www.youtube.com/watch?v=7O2Jqi-LhEI (a new workout video)
Update: One promising suggestion was to explore fileDetails.videoStreams[].aspectRatio
but it seems that this is only available to the video owner. Otherwise requesting fileDetails
results in
The request cannot access user rating information. This error may occur because the request is not properly authorized
Source: (StackOverflow)
I'm building an application that allows the admin to authenticate access to their analytics account for offline usage, and stores the refresh token in the database.
Now when I try to use the API on the frontend, it returns the following error:
"Access Token Expired. There wan a general error : The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved."
Here's my code that generates this error so far:
require_once "lib/google/Google_Client.php";
require_once "lib/google/contrib/Google_AnalyticsService.php";
$_analytics = new analytics();
$_googleClient = new Google_Client();
$_googleClient->setClientId($_analytics->gaClientId);
$_googleClient->setClientSecret($_analytics->gaClientSecret);
$_googleClient->setRedirectUri($_analytics->gaRedirectUri);
$_googleClient->setScopes($_analytics->gaScope);
$_googleClient->setAccessType($_analytics->gaAccessType);
// Returns last access token from the database (this works)
$_tokenArray['access_token'] = $_analytics->dbAccessToken($_agencyId);
$_googleClient->setAccessToken(json_encode($_tokenArray));
if($_googleClient->isAccessTokenExpired()) {
// Don't think this is required for Analytics API V3
//$_googleClient->refreshToken($_analytics->dbRefreshToken($_agencyId));
echo 'Access Token Expired'; // Debug
}
if (!$_googleClient->getAccessToken()) {
echo '<h2>Error - Admin has not setup analytics correct yet</h2>';
}
I'm after a function to run something like setRefreshToken - entering the value from the database, from the admin previously authenticating it online.
Source: (StackOverflow)
I want to use the Google php api for accessing the calendars.
I'm working with laravel. I already added the package on composer and it's downloading fine, the thing is what I have to do with the providers and aliases or whatever to link the api with my app. I want to call the Calendar class.
I do the auth properly to with another library, artdarek/oauth-4-laravel, i can show the calendar with this api but i can't insert/edit calendar, is this a simpler way ?
Here the providers :
'providers' => array(
'Illuminate\Foundation\Providers\ArtisanServiceProvider',
'Illuminate\Auth\AuthServiceProvider',
'Illuminate\Cache\CacheServiceProvider',
'Illuminate\Session\CommandsServiceProvider',
'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
'Illuminate\Routing\ControllerServiceProvider',
'Illuminate\Cookie\CookieServiceProvider',
'Illuminate\Database\DatabaseServiceProvider',
'Illuminate\Encryption\EncryptionServiceProvider',
'Illuminate\Filesystem\FilesystemServiceProvider',
'Illuminate\Hashing\HashServiceProvider',
'Illuminate\Html\HtmlServiceProvider',
'Illuminate\Log\LogServiceProvider',
'Illuminate\Mail\MailServiceProvider',
'Illuminate\Database\MigrationServiceProvider',
'Illuminate\Pagination\PaginationServiceProvider',
'Illuminate\Queue\QueueServiceProvider',
'Illuminate\Redis\RedisServiceProvider',
'Illuminate\Remote\RemoteServiceProvider',
'Illuminate\Auth\Reminders\ReminderServiceProvider',
'Illuminate\Database\SeedServiceProvider',
'Illuminate\Session\SessionServiceProvider',
'Illuminate\Translation\TranslationServiceProvider',
'Illuminate\Validation\ValidationServiceProvider',
'Illuminate\View\ViewServiceProvider',
'Illuminate\Workbench\WorkbenchServiceProvider',
'Artdarek\OAuth\OAuthServiceProvider',
'Google\Client',
),
Here's the aliases :
'aliases' => array(
'App' => 'Illuminate\Support\Facades\App',
'Artisan' => 'Illuminate\Support\Facades\Artisan',
'Auth' => 'Illuminate\Support\Facades\Auth',
'Blade' => 'Illuminate\Support\Facades\Blade',
'Cache' => 'Illuminate\Support\Facades\Cache',
'ClassLoader' => 'Illuminate\Support\ClassLoader',
'Config' => 'Illuminate\Support\Facades\Config',
'Controller' => 'Illuminate\Routing\Controller',
'Cookie' => 'Illuminate\Support\Facades\Cookie',
'Crypt' => 'Illuminate\Support\Facades\Crypt',
'DB' => 'Illuminate\Support\Facades\DB',
'Eloquent' => 'Illuminate\Database\Eloquent\Model',
'Event' => 'Illuminate\Support\Facades\Event',
'File' => 'Illuminate\Support\Facades\File',
'Form' => 'Illuminate\Support\Facades\Form',
'Hash' => 'Illuminate\Support\Facades\Hash',
'HTML' => 'Illuminate\Support\Facades\HTML',
'Input' => 'Illuminate\Support\Facades\Input',
'Lang' => 'Illuminate\Support\Facades\Lang',
'Log' => 'Illuminate\Support\Facades\Log',
'Mail' => 'Illuminate\Support\Facades\Mail',
'Paginator' => 'Illuminate\Support\Facades\Paginator',
'Password' => 'Illuminate\Support\Facades\Password',
'Queue' => 'Illuminate\Support\Facades\Queue',
'Redirect' => 'Illuminate\Support\Facades\Redirect',
'Redis' => 'Illuminate\Support\Facades\Redis',
'Request' => 'Illuminate\Support\Facades\Request',
'Response' => 'Illuminate\Support\Facades\Response',
'Route' => 'Illuminate\Support\Facades\Route',
'Schema' => 'Illuminate\Support\Facades\Schema',
'Seeder' => 'Illuminate\Database\Seeder',
'Session' => 'Illuminate\Support\Facades\Session',
'SSH' => 'Illuminate\Support\Facades\SSH',
'Str' => 'Illuminate\Support\Str',
'URL' => 'Illuminate\Support\Facades\URL',
'Validator' => 'Illuminate\Support\Facades\Validator',
'View' => 'Illuminate\Support\Facades\View',
'OAuth' => 'Artdarek\OAuth\Facade\OAuth',
'Calendar' => 'Google\Service\Calendar'
),
Composer.json
"require": {
"laravel/framework": "4.1.*",
"artdarek/oauth-4-laravel": "dev-master",
"google/apiclient": "dev-master"
},
The method for adding a calendar
public function addCalendar($calendarName){
$calendar = new Calendar();
$calendar->setSummary($calendarName);
// get google service
$googleService = OAuth::consumer( 'Google' );
$createdCalendar = $googleService->calendars->insert($calendar);
echo $createdCalendar->getId();
}
Hope you can help me ! Thanks !
Source: (StackOverflow)
Is there any way to embed a Google+ hangout app in a PHP-based website? Can I load the app inside an iframe without having to land on Google+ hangout page? If so, how?
Source: (StackOverflow)
I've been searching for days and trying new and older version of google-api-php-client along with various other examples out there, but I can't seem to get around this error.
The code below is the service-account example retrieved from GitHub and I dropped in my credentials and file from the API Console. I've got a different file I'm actually building, but for use in this question, I figure this simpler file would be easier to discuss. I'm getting the same error with both files.
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Unable to parse the p12 file. Is this a .p12 file? Is the password correct? OpenSSL error: ' in /google-api-php-client/src/Google/Signer/P12.php on line 52
I'm completely stumped about why it is throwing this error.
I've verified "file_get_contents" is actually getting the contents of the file and my "notasecret" password is getting pulled properly. I was hoping this recent commit might help, but unfortunately, it didn't solve this error for me.
Any idea what is going wrong here? Thank you for any suggestions!
<?php
session_start();
include_once "templates/base.php";
set_include_path("../src/" . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/Books.php';
$client_id = 'xxxx.apps.googleusercontent.com';
$service_account_name = 'xxxx@developer.gserviceaccount.com';
$key_file_location = 'xxxx-privatekey.p12';
echo pageHeader("Service Account Access");
if ($client_id == 'xxxx.apps.googleusercontent.com'
|| !strlen($service_account_name)
|| !strlen($key_file_location)) {
echo missingServiceAccountDetailsWarning();
}
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$service = new Google_Service_Books($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/books'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
echo "<h3>Results Of Call:</h3>";
foreach ($results as $item) {
echo $item['volumeInfo']['title'], "<br /> \n";
}
echo pageFooter(__FILE__);
Source: (StackOverflow)
I am trying to write a small script to upload a local file to Google Drive, using Google Drive PHP API. The documentation is very poor maintained, but so far I am pretty sure the code should be looking like that:
<?php
include_once 'Google/Client.php';
include_once 'Google/Service/Drive.php';
include_once 'Google/Auth/OAuth2.php';
$client = new Google_Client();
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setClientId('dfgdfgdg');
$client->setClientSecret('dfgdfgdf');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$service = new Google_Service_Drive($client);
$data = file_get_contents("a.jpg");
// create and upload a new Google Drive file, including the data
try
{
//Insert a file
$file = new Google_Service_Drive_DriveFile($client);
$file->setTitle(uniqid().'.jpg');
$file->setMimeType('image/jpeg');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'image/jpeg',
'uploadType' => 'media',
));
}
catch (Exception $e)
{
print $e->getMessage();
}
print_r($createdFile);
?>
The issue is I am not able to do the authentication right (or I am doing something else wrong?). The error I received is:
HTTP Error: Unable to connect: 'fopen(compress.zlib://https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart) [function.fopen]: failed to open stream: operation failed'
Followed by this error:
Notice: Undefined variable: createdFile in C:\wamp\www\GoogleAPI\index.php on line 39
What am I doing wrong? Can you provide a simple working script of uploading a file to Google Drive using Google Drive PHP API? Thank you in advance!
Source: (StackOverflow)
I've tried so many things in the last days but now I'm out of ideas :(
I want to verify an inAppPurchase that has been made in my android app.
1) I created a new service account in the google API console.
1a) The service account is listed unter permissions and has "can view" permission
2) I'm using the most current version of https://github.com/google/google-api-php-client
3) code snippet from my PHP script:
$client = new Google_Client();
$client->setApplicationName('myAppName' );
$client->setClientId('123456789123-vxoasdt8qwe6awerc9ysdfmjysdfysf64werweria8fh.apps.googleusercontent.com');
$key = file_get_contents('/shr/data/stor/b516cexx3123asdf3988345d8133e7f86bfas2553-privatekey.p12');
$service_account_name = '123456789123-vxoasdt8qwe6awerc9ysdfmjysdfysf64werweria8fh@developer.gserviceaccount.com';
$client->setScopes(array('https://www.googleapis.com/auth/androidpublisher') );
$cred = new Google_Auth_AssertionCredentials( $service_account_name, array('https://www.googleapis.com/auth/androidpublisher'), $key );
$client->setAssertionCredentials($cred);
try {
$service = new Google_Service_AndroidPublisher( $client );
$googleApiResult = $service->inapppurchases->get($externalAppId, $externalProductId, $purchaseToken);
} catch (Exception $e) {
var_dump( $e->getMessage() );
}
4) Response from Google:
GET https://www.googleapis.com/androidpublisher/v1.1/applications/de.test.myapp/inapp/de.test.inapp.google.balance5eur/purchases/[PURCHASETOKEN]:
(401) The current user has insufficient permissions to perform the
requested operation.
[PURCHASETOKEN] is the purchase token I received from google
5) Setting $cred->sub = 'foo@bar.de' to my mail address brings up
Error refreshing the OAuth2 token, message: '{ "error" :
"unauthorized_client", "error_description" : "Unauthorized client or
scope in request." }'
Source: (StackOverflow)