I am working on google drive api by using PHP. I am facing an error while using this drive api. I am using google api client library "google/apiclient ^2.0". I am trying to user login with google authentication and view all files available in drive for this purpose, i am using this library but it's showing error:
Notice: Undefined property: Google_Client::$files in
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php on line 31
Fatal error: Uncaught Error: Call to a member function listFiles() on
null in /Applications/XAMPP/xamppfiles/htdocs/google_app/index.php:31
Stack trace: #0
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php(55):
retrieveAllFiles(Object(Google_Client)) #1 {main} thrown in
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php on line 31
include_once 'vendor/autoload.php';
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType("offline"); // offline access
//$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
}
$service = new Google_service_Device();
echo retrieveAllFiles($service );
Actually i am trying to retrieve all files in my google drive with my file id and after that set status auto publish of specific files. Please help me to get rid of this error.
Thanks in advance.
"Daily limit for unauthenticated Use Exceeded"
Means that you are making a request without properly authenticating your script. there is probably something up with your fetchAccessTokenWithAuthCode.
You might consider something long these lines
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Code ripped from my sample project oauth2php
Undefined property Google_Client
Means you havent properly declared the google client
Uncaught Error: Call to a member function listFiles() on null in
what happens if you remove $parameters and just call $service->files->listFiles();
I recently upgraded to the latest version of the facebook SDK and I'm having issues logging users in. I generate the login link just fine, but when facebook sends the user back to my site with the token, I get this error:
fb sdk error: Cross-site request forgery validation failed. Required param "state" missing from persistent data.
I tried to do some trouble shooting. I printed out everything in the session data and everything in the GET request. I see that the GET has a state parameter and the session data has a FBRLH_state parameter. They both have the same value. So how is it telling me that the parameter is missing?
I've tried some suggestions I've seen on other questions (ie, starting the session), but nothing seems to work.
Any help would be greatly appreciated! I'm using the php-graph-sdk-5.5. My facebook connect file is below
if(!class_exists('facebook')){
class facebook{
private $db = null;
private $fb = null;
private $token = null;
private $DEV = null;
private $sdk_error = null;
private $api_error = null;
private $verbose = false;
private $graph_user = null;
private $db_helper = null;
private $errors = null;
public function __construct($db,
$fb_id = FB_APP_ID,
$fb_secret = FB_APP_SECRET,
$fb_version = FB_DEFAULT_GRAPH_VERSION){
if($this->verbose) echo '<pre>';
if($this->verbose) echo 'starting construction'.PHP_EOL;
$this->db = $db;
if(!$this->fb){
$this->log[] = 'no connect found. building..'.PHP_EOL;
$this->fb = new Facebook\Facebook(array(
'app_id' => $fb_id,
'app_secret' => $fb_secret,
'default_graph_version' => $fb_version));
if(!$this->fb){
die('facebook initialization failure');
}
$this->log[] = 'finished building new connection'.PHP_EOL;
}
}
public function get_login_url($callback_uri, $permissions = ['email','user_birthday']){
global $_DEV,$_config;
$helper = $this->fb->getRedirectLoginHelper();
$callback_host = ($_DEV ? $_config['dev_domain'] : $_config['live_domain']);
$callback_url = 'https://'.$callback_host.$callback_uri;
return $helper->getLoginUrl($callback_url, $permissions);
}
public function catch_token(){
if($this->token){
$this->log[] = 'already have token.'.PHP_EOL;
return $this->token;
} else if(!$this->fb){
$this->log[] = $this->error[] = 'no facebook connection in catch token()';
}
$this->log[] = 'starting catch token routine.'.PHP_EOL;
//$_SESSION['state']=$_GET['state'];
echo '<pre>' . var_export($_SESSION, true) . '</pre>';
echo '<BR><BR><pre>' . var_export($_GET, true) . '</pre>';
$helper = $this->fb->getRedirectLoginHelper();
$this->token = $helper->getAccessToken();
$this->log[] = 'caught token: '.$this->token;
$string_token = $this->token.PHP_EOL;
//die($string_token);
try {
$helper = $this->fb->getRedirectLoginHelper();
$this->token = $helper->getAccessToken();
$this->log[] = 'caught token: '.$this->token;
$string_token = $this->token.PHP_EOL;
return $this->user_flush();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$this->log[] = $this->errors[] = 'fb api error: ' . $e->getMessage();
return null;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$this->log[] = $this->errors[] = 'fb sdk error: ' . $e->getMessage();
return null;
} catch(Exception $e){
$this->log[] = $this->errors[] = 'unknown error: '.$e->getMessage();
return null;
}
}
public function get_token(){
$this->log[] = 'get token called.'.PHP_EOL;
if($this->token){
$this->log[] = 'token found in object'.PHP_EOL;
//echo '<pre>';
//die(debug_print_backtrace());
return $this->token;
} else {
$this->log[] = $this->errors[] = 'token not found in object.'.PHP_EOL;
return null;
}
}
public function get_user($override = false){
$fields = array(
'first_name',
'last_name',
'email',
'id',
'picture',
'birthday',
'gender',);
$fields = implode(',',$fields);
if($this->graph_user === null){
if($this->fb && $this->get_token()){
try {
// Returns a Facebook\FacebookResponse object
$resp_url = '/me?fields='.$fields.'&debug=all';
$this->log[] = $resp_url;
$response = $this->fb->get($resp_url, $this->get_token());
$this->graph_user = $response->getGraphUser();
return $this->graph_user;
}
catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$this->api_error = 'fb api error: ' . $e->getMessage();
$this->errors[] = $this->api_error;
return null;
}
catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$this->sdk_error = 'fb sdk error: ' . $e->getMessage();
$this->errors[] = $this->sdk_error;
return null;
}
} else {
$this->sdk_error = "get_user(): fb connection or token not set. are you logged in?";
$this->errors[] = $this->sdk_error;
//echo '<pre>';
//debug_print_backtrace();
//die('token: '.$this->token);
return null;
}
} else {
$this->sdk_error = "get_user(): graph_user already set";
$this->errors[] = $this->sdk_error;
return $this->graph_user;
}
}
public function get_user_first_name(){
return $this->get_user()['first_name'];
}
public function get_user_last_name(){
return $this->get_user()['last_name'];
}
public function get_user_id(){
return $this->get_user()['id'];
}
public function get_user_email(){
return $this->get_user()['email'];
}
public function get_user_picture(){
return $this->get_user()['picture']['url'];
}
public function get_user_birthday(){
return $this->get_user()['birthday'];
}
public function user_flush(){
//this is the command function.
// runs the basic functionality of this class
// by adding this user to the database if they're not there
// and logging them in if they are.
$this->graph_user = $this->get_user();
//$this->log['graph_user_at_user_flush'] = $this->graph_user;
$this->build_user();
$this->log['GRAPH_USER'] = $this->get_user();
$this->log['user_input_array#user_flush'] = $this->user_input;
if($return = $this->user->fb_register()){
//die(print_r(debug_backtrace(),true));
//$this->log['success return'] = '. '.$return;
return $return;
} else {
//die('<pre>'.print_r(debug_backtrace(),true));
$this->log['fb_register_fail'] = array('fb_register() (also login) failed.',$this->user->get_errors());
return null;
}
}
public function build_user(){
$this->user_input['first_name'] = $this->get_user_first_name();
//$this->user_input['last_name'] = $this->get_user_last_name();
$this->user_input['facebook_id'] = $this->get_user_id();
$this->user_input['email'] = $this->get_user_email();
$this->user_input['image_url'] = $this->get_user_picture();
$this->user_input['birthday'] = $this->get_user_birthday();
if($this->verbose)
print_r($this->user_input);
$this->user = new user($this->user_input,$this->db);
}
public function logout(){
unset($_SESSION['fb_id']);
unset($this->token);
unset($this->fb);
}
public function get_errors(){
return array_unique($this->errors);
}
public function get_log(){
return array_unique($this->log);
}
}
}
//finally, create the connection.
if(!isset($fb))
$fb = new facebook($db);
This might be kinda late but I hope it helps others.
I had this problem for a while and I've searched around and have seen a lot of different solutions, many of which disable the CSRF check. So after everything I've read, this is what worked for me.
For what I understand, you get this error when your redirect URL doesn't match the one you have setup on your app settings so my issue was fixed every easily but I have also seen people have issues by not having their session started properly, so I will cover both issues.
Step 1: Ensure your session has started when it needs to.
for example: fb-config.php
session_start();
include_once 'path/to/Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => 'your_app_id',
'app_secret' => 'your_secret_app_id',
'default_graph_version' => 'v2.10'
]);
$helper = $fb->getRedirectLoginHelper();
if your facebook callback code is on another file aside from the config, then start the session on that file too.
for example: fb-callback.php
session_start();
include_once 'path/to/fb-config.php';
try {
$accessToken = $helper->getAccessToken();
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
echo "Response Exception: " . $e->getMessage();
exit();
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
echo "SDK Exception: " . $e->getMessage();
exit();
}
/** THE REST OF YOUR CALLBACK CODE **/
Now, what solved my actual issue.
Step 3: Set up your redirect URL in your app settings.
In your Facebook Login app settings, go to the Valid OAuth redirect URIs where you should have added the url that points to your fb-callback.php file.
http://example.com/fb-callback.php
AND ALSO
http://www.example.com/fb-callback.php
then setup your redirect url as follows.
$redirectURL = "http://".$_SERVER['SERVER_NAME']."/fb-callback.php";
$permissions = ['email'];
$fLoginURL = $helper->getLoginUrl($redirectURL, $permissions);
Why both with and without www and why use SERVER_NAME?
because your Valid OAuth redirect URI needs to match your redirect url in your code and if in you app settings you only set your OAuth redirect as http://example.com/fb-callback.php and set up your $redirectURL as http://example.com/fb-bacllback.php to make it match but the user entered your site as http://www.example.com then the user will get the Facebook SDK error: Cross-site request forgery validation failed. Required param “state” missing from persistent data because the URL the user is at, doesn't EXACTLY match what you have setup. Why? I have no freaking idea.
My approach makes it so if the user enters your site as http://example.com or http://www.example.com, it will always match what you setup in your app settings. why? because $_SERVER['SERVER_NAME'] will return the domain with or without the www depending on how the user entered the url in the browser.
This are my findings and this is about the only thing that worked for me without removing the CSRF check and so far, no issues.
I hope this helps.
fb sdk error: Cross-site request forgery validation failed. Required param "state" missing from persistent data.
It has something to do with that you are going through the routine of calling getRedirectLoginHelper and $helper->getAccessToken() twice - once "on their own", and then again inside a try-catch block (copy&paste mistake, or unfortunate debug attempt maybe?)
I'm a bit too lazy to go check the SDK source right now, but I think it deliberately unsets the state parameter inside the session after the code was exchanged for a token, as part of making the whole process more secure - so that when you call getAccessToken a second time, it fails.
If anyone still with this proglem just add a session_start() at the begining of the callback file.
Well I faced the same error today and I got my solution from tutorials point
In your callback file, just add this line and you're good to go
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
I know I'm late to the party, but I faced this error, and I don't believe my solution was covered in the above responses, so here it goes:
One reason this error may arise is if you submit the same URL login request to Facebook more than once. For example, a user may impatiently click on a login button more than once, triggering multiple submissions of the URL. In my case, the solution was to intercept all clicks after the first with a JavaScript function.
Change version to v2.10 Check graph you are using in configuration php file
// Call Facebook API
Both the things didn't work for me for v14.
Adding that small code just before $helper = $fb->getRedirectLoginHelper(); worked.
Here's the code that actually worked -
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
Still got this error after clicking login..
SDK Exception: Cross-site request forgery validation failed. Required
param "state" missing from persistent data.
I'll just follow and read the previous topic and comments above. And double check URL of Valid OAuth redirect URI.
Here's what id done. Well appreciated if you can share some thoughts and correct me..
create-acc.php
///FACEBOOK SIGNUP
session_start();
include_once 'config-facebook.php';
try {
$accessToken = $helper->getAccessToken();
} catch (\Facebook\Exceptions\FacebookResponseException $e) {
echo "Response Exception: " . $e->getMessage();
exit();
} catch (\Facebook\Exceptions\FacebookSDKException $e) {
echo "SDK Exception: " . $e->getMessage();
exit();
}
$redirectURL = "http://".$_SERVER['SERVER_NAME']."/create-acc.php";
$permissions = ['email'];
$fLoginURL = $helper->getLoginUrl($redirectURL, $permissions);
$facebook_button ='
<div style="background-color:white; color:#4b5563; cursor:pointer;" class="inline-flex border-2 py-1.5 px-5 rounded text-lg border-gray-300">
<div style="margin-top:5px;">
<img style="width:25px;" src="./assets/apps/facebook-logo-2019.png"/>
</div>
<b>Sign up with Facebook</b>
</div>
';
config-facebook.php
include_once 'Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '**************',
'app_secret' => '*************',
'default_graph_version' => 'v2.10'
]);
$helper = $fb->getRedirectLoginHelper();
I'm literally new on this programming and still learning. So if you help it really save my time and learn on provided codes.And if I tried to add some callback codes to get a data, it looks like this on my work
create-acc.php add ons callback codes
///FACEBOOK SIGNUP
session_start();
include_once 'config-facebook.php';
if (isset($accessToken))
{
if (!isset($_SESSION['facebook_access_token']))
{
//get short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
//OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
//Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
//setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
else
{
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
if (isset($_GET['code']))
{
header('Location: ./');
}
try {
$fb_response = $fb->get('/me?fields=name,first_name,last_name,email');
$fb_response_picture = $fb->get('/me/picture?redirect=false&height=200');
$fb_user = $fb_response->getGraphUser();
$picture = $fb_response_picture->getGraphUser();
$_SESSION['fb_user_id'] = $fb_user->getProperty('id');
$_SESSION['fb_user_name'] = $fb_user->getProperty('name');
$_SESSION['fb_user_email'] = $fb_user->getProperty('email');
$_SESSION['fb_user_pic'] = $picture['url'];
} catch(Facebook\Exceptions\FacebookResponseException $e) {
echo 'Facebook API Error: ' . $e->getMessage();
session_destroy();
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK Error: ' . $e->getMessage();
exit;
}
}
else
{
$redirectURL = "http://".$_SERVER['SERVER_NAME']."/create-acc.php";
$permissions = ['email'];
$fLoginURL = $helper->getLoginUrl($redirectURL, $permissions);
$facebook_button ='
<div style="background-color:white; color:#4b5563; cursor:pointer;" class="inline-flex border-2 py-1.5 px-5 rounded text-lg border-gray-300">
<div style="margin-top:5px;">
<img style="width:25px;" src="./assets/apps/facebook-logo-2019.png"/>
</div>
<b>Sign up with Facebook</b>
</div>
';
}
and the config-facebook.php
session_start();
include_once 'Facebook/autoload.php';
$fb = new \Facebook\Facebook([
'app_id' => '************',
'app_secret' => '************',
'default_graph_version' => 'v2.10'
]);
$helper = $fb->getRedirectLoginHelper();
try {
if(isset($_SESSION['facebook_access_token']))
{$accessToken = $_SESSION['facebook_access_token'];}
else
{$accessToken = $helper->getAccessToken();}
} catch(FacebookResponseException $e) {
echo 'Facebook API Error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK Error: ' . $e->getMessage();
exit;
}
and the result here
Fatal error: Uncaught Facebook\Exceptions\FacebookSDKException: Cross-site request forgery validation failed. Required param "state" missing from persistent data. in /www/wwwroot/fruitask.com/Facebook/Helpers/FacebookRedirectLoginHelper.php:244 Stack trace: #0 /www/wwwroot/fruitask.com/Facebook/Helpers/FacebookRedirectLoginHelper.php(221): Facebook\Helpers\FacebookRedirectLoginHelper->validateCsrf() #1 /www/wwwroot/fruitask.com/config-facebook.php(20): Facebook\Helpers\FacebookRedirectLoginHelper->getAccessToken() #2 /www/wwwroot/fruitask.com/create-acc.php(162): include_once('/www/wwwroot/fr...') #3 {main} thrown in /www/wwwroot/fruitask.com/Facebook/Helpers/FacebookRedirectLoginHelper.php on line 244
Please do share some thoughts or any alternative way I can implement Facebook login on my website using PHP. Thanks in advance
I got a problem with Gmail API service account, I would like to get my personal email from Gmail API without ask for verifying Gmail account and password. Exactly it could be interested to get them from my back-end code.
I have tried to implement this function but it was not worked.
public function list_email()
{
$this->load->library('google');
$client = new Google_Client();
$service = new Google_Service_Gmail($client);
$client->setApplicationName('airxpress-message-api');
$client_email = '867003685660-dk6896nclmfdql86cudt65q2c06f8ooa#developer.gserviceaccount.com';
$private_key = file_get_contents(base_url().G_API.'p12/airxpress-message-api-45eb6393e620.p12');
$scopes = array('https://mail.google.com/');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$credentials->sub = 'notifications-vd#gmail.com';
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion();
}
$messages = array();
try
{
$opt_param['labelIds'] = 'INBOX';
$opt_param['q'] = 'subject:"reservation request"';
$messagesResponse = $service->users_messages->listUsersMessages('me', $opt_param);
if ($messagesResponse->getMessages())
{
$messages = array_merge($messages, $messagesResponse->getMessages());
}
}
catch (Exception $e)
{
print 'An error occurred: ' . $e->getMessage();
}
print_r($messages);
}
I met this message error :
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." }''
So, I have gotten the reference from :
https://developers.google.com/api-client-library/php/auth/service-accounts
Could anyone tell me how to solve it?
I'm passing the facebook login token from ember-cli to my laravel server to register/login my user but I'm stuck with this error.
{"error":{"type":"Facebook\FacebookAuthorizationException","message":"An active access token must be used to query information about the current user.","file":"C:\xampp\htdocs\LoginApp\vendor\facebook\php-sdk-v4\src\Facebook\FacebookRequestException.php","line":134}}
Here is my function
public function authorizeFacebookUser() {
$facebook_token = Input::get('facebook_access_token');
FacebookSession::setDefaultApplication('xxxxxxxx', 'xxxxx');
$session = new FacebookSession((string) $facebook_token);
if ($session) {
// have session
try {
$user_profile = (new FacebookRequest(
$session, 'GET', '/me'
))->execute()->getGraphObject(GraphUser::className());
echo "Name: " . $user_profile->getName();
} catch(FacebookRequestException $e) {
echo "Exception occured, code: " . $e->getCode();
echo " with message: " . $e->getMessage();
}
}
}
After creating a session with the access_token, you should validate it to make sure it's correct and working:
try {
if ( !$session->validate() ) {
$session = null;
}
} catch ( Exception $e ) {
// catch any exceptions
$session = null;
}
Then you can make the API call to get the user's profile information. Hopefully, the above code will display any errors related to the access_token.
So, i have two accounts at google, one is for personal use and one for company use. At the company account i have bought drive quota and it is at 200gb (i think), so im using it as a file storage cloud-server. My idea is to implement some of the files to the company website using google drive php api. As long as i know i can Use Application-Owned Accounts which sounds great, BUT i have to create new account it seems in order to use it with a regular account and if i want to use it with a server-side i will be not be able to use the company files at the regular account. So, im stuck at this situation!? Please, give me some advice. This is all new to me, so i need your help.
EDIT:
What it says from the link i posted above is this:
You may create a regular Google account like any user would, by going through the Google account sign-up flow or by creating an account on your Google Apps domain. Make sure it is then never used by an actual person but only by your application.
OK, but my account it is not new and it HAVE been used before. That mean that i will not be able to use my company account and if that is true, how can i achieve my goal?
i finally did it after days of researching how i can do this, here is a very simple code for how to obtain the access token and after you have it how to take the refresh token which you will need in order to access the user when he is in offline. I still have to understand how can i know when i store those values in the databse, how can i know that this user with the google id is the same user from the database and put the refresh token in the php, so the user dont have to authenticate again and he can do this only once (service account). So this simple code is using SESSIONS in order to store the access token and also the refresh token. It's not using database for the storage, but if you want when i figure out how this is done i can post the code here as well. So, here is the code:
<?php
session_start();
// Set error reporting
error_reporting(E_ALL | E_STRICT);
// Display errors
ini_set("display_errors", 1);
// require pages, you have to change it if your pages are somewhere else!
require_once 'src/Google_Client.php';
require_once "src/contrib/Google_Oauth2Service.php";
require_once "src/contrib/Google_DriveService.php";
/**
* Retrieved stored credentials for the provided user ID.
*
* #param String $userId User's ID.
* #return String Json representation of the OAuth 2.0 credentials.
*/
function getStoredCredentials($userId) {
if (!empty($_SESSION['userid'])) {
return $_SESSION['userid'];
}
}
/**
* Store OAuth 2.0 credentials in the application's database.
*
* #param String $userId User's ID.
* #param String $credentials Json representation of the OAuth 2.0 credentials to store.
*/
function storeCredentials($userId, $credentials) {
$_SERVER['userid'] = $userId;
}
/**
* Build a Drive service object.
*
* #param String credentials Json representation of the OAuth 2.0 credentials.
* #return Google_DriveService service object.
*/
function buildService($credentials) {
$apiClient = new Google_Client();
$apiClient->setUseObjects(true);
$apiClient->setAccessToken($credentials);
return new Google_DriveService($apiClient);
}
/**
* Send a request to the UserInfo API to retrieve the user's information.
*
* #param String credentials OAuth 2.0 credentials to authorize the request.
* #return Userinfo User's information.
* #throws NoUserIdException An error occurred.
*/
function getUserInfo($credentials) {
$apiClient = new Google_Client();
$apiClient->setUseObjects(true);
$apiClient->setAccessToken($credentials);
$userInfoService = new Google_Oauth2Service($apiClient);
$userInfo = null;
try {
$userInfo = $userInfoService->userinfo->get();
} catch (Google_Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
if ($userInfo != null && $userInfo->getId() != null) {
return $userInfo;
} else {
throw new NoUserIdException();
}
}
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
function printFile($service, $fileId) {
try {
$file = $service->files->get($fileId);
print "Title: " . $file->getTitle();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();
} catch (apiException $e) {
print "An error occurred: " . $e->getMessage();
}
}
// fill your details from the google console:
$client = new Google_Client();
$client->setApplicationName('***************');
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setClientId('***************');
$client->setClientSecret('***************');
$client->setRedirectUri('***************/google-drive-api-php-client/serverside.php');
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setDeveloperKey('***************');
// a simple code to check if the user have already login to the site and authenticate the site and if he does the site will not ask the user again for authentification and it will use the refresh token to "log" the user in
if (empty($_GET['code'])) {
// if the user visit the website for the first time he need to authentificate (redirecting the website to google)!
if (empty($_SESSION['access_token']) && !isset($_SESSION['refresh_token'])) {
header('Location: ' . $client->createAuthUrl());
// if the user have already visited the site, but the access token have expired use this code
} elseif (empty($_SESSION['access_token']) && isset($_SESSION['refresh_token'])) {
echo "refresh token1" . "<br>";
$google_token = json_decode($_SESSION['refresh_token'], true);
$client->refreshToken($google_token['refresh_token']);
$_SESSION['access_token']= $client->getAccessToken();
}
} elseif (!empty($_GET['code']) && empty($_SESSION['access_token'])) {
// if the user is visiting the website for the first time and dont have refresh token:
if (!isset($_SESSION['refresh_token'])) {
echo "access token" . "<br>";
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $_SESSION['access_token'];
// this will never execute, but i put it anyway :) if the user have already visited the site, but the access token have expired use this code (its the same as the above)
} elseif (isset($_SESSION['refresh_token'])) {
echo "refresh token2" . "<br>";
$google_token = json_decode($_SESSION['refresh_token'], true);
$client->refreshToken($google_token['refresh_token']);
$_SESSION['access_token']= $client->getAccessToken();
}
}
// if the access token have expired use the refresh token to gain access instead:
if ($client->isAccessTokenExpired()) {
$google_token = json_decode($_SESSION['refresh_token'], true);
$client->refreshToken($google_token['refresh_token']);
$_SESSION['access_token']= $client->getAccessToken();
}
// unset the sessions for testing:
// unset($_SESSION['access_token']);
// unset($_SESSION['refresh_token']);
// get some info from the user Google API like the file info
if (!empty($_SESSION['access_token'])) {
// create the service in this case Google Drive
$service = buildService($_SESSION['access_token']);
// mark the file ID
$fileid = "*******************";
// print the access token
echo "<pre>";
print_r(getUserInfo($_SESSION['access_token']));
echo "</pre>";
// print file metadata from google drive
// echo "<pre>";
// print_r(printFile($service, $fileid));
// echo "</pre>";
}
// printing the session for testing...
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
// print the refresh token for testing
print_r($_SESSION['refresh_token']);
// print echo to see if the code is executing till the end or there is a fatal error someone in the code :)
echo "string";
?>