I'm trying to create an authentication with google API. I always get my page refreshed I can't get access to the user information I see always the two alerts "here 1" and "here 2" any idea to help ?
<?php
/* GOOGLE LOGIN BASIC - Tutorial
* file - index.php
* Developer - Krishna Teja G S
* Website - http://packetcode.com/apps/google-login/
* Date - 28th Aug 2015
* license - GNU General Public License version 2 or later
*/
// REQUIREMENTS - PHP v5.3 or later
// Note: The PHP client library requires that PHP has curl extensions configured.
/*
* DEFINITIONS
*
* load the autoload file
* define the constants client id,secret and redirect url
* start the session
*/
require_once __DIR__.'/gplus-lib/vendor/autoload.php';
const CLIENT_ID = 'my code';
const CLIENT_SECRET = 'my code';
const REDIRECT_URI = 'http://www.servicebigdeals.com/google-login/';
session_start();
/*
* INITIALIZATION
*
* Create a google client object
* set the id,secret and redirect uri
* set the scope variables if required
* create google plus object
*/
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes('email');
$plus = new Google_Service_Plus($client);
/*
* PROCESS
*
* A. Pre-check for logout
* B. Authentication and Access token
* C. Retrieve Data
*/
/*
* A. PRE-CHECK FOR LOGOUT
*
* Unset the session variable in order to logout if already logged in
*/
if (isset($_REQUEST['logout'])) {
session_unset();
}
/*
* B. AUTHORIZATION AND ACCESS TOKEN
*
* If the request is a return url from the google server then
* 1. authenticate code
* 2. get the access token and store in session
* 3. redirect to same url to eliminate the url variables sent by google
*/
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
else {
echo "<script>alert(\"here 1 \")</script>";
}
/*
* C. RETRIEVE DATA
*
* If access token if available in session
* load it to the client object and access the required profile data
*/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$me = $plus->people->get('me');
// Get User data
$id = $me['id'];
$name = $me['displayName'];
$email = $me['emails'][0]['value'];
$profile_image_url = $me['image']['url'];
$cover_image_url = $me['cover']['coverPhoto']['url'];
$profile_url = $me['url'];
}
else {
echo "<script>alert(\"here 2 \")</script>";
// get the login url
$authUrl = $client->createAuthUrl();
}
?>
<!-- HTML CODE with embedded PHP-->
<div>
<?php
/*
* If login url is there then display login button
* else print the retrieved data
*/
if (isset($authUrl)) {
echo "<a class='login' href='" . $authUrl . "'><img src='gplus-lib/signin_button.png' height='50px'/></a>";
} else {
print "ID: {$id} <br>";
print "Name: {$name} <br>";
print "Email: {$email } <br>";
print "Image : {$profile_image_url} <br>";
print "Cover :{$cover_image_url} <br>";
print "Url: {$profile_url} <br><br>";
echo "<a class='logout' href='?logout'><button>Logout</button></a>";
}
?>
</div>
Related
i have successfully integrated google api login and logout and both are working fine but after i logged in and try to refresh the webpage .. it shows me the below error-
Fatal error: Uncaught GuzzleHttp\Exception\ClientException: Client error: POST https://oauth2.googleapis.com/token resulted in a 400 Bad Request response: { "error":
"invalid_grant", "error_description": "Bad Request" } in
C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php:113 Stack
trace: #0 C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\guzzle\src\Middleware.php(69):
GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request),
Object(GuzzleHttp\Psr7\Response), NULL, Array, NULL) #1
C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\promises\src\Promise.php(204):
GuzzleHttp\Middleware::GuzzleHttp{closure}(Object(GuzzleHttp\Psr7\Response)) #2
C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\promises\src\Promise.php(153):
GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), NULL) #3
C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\promises\src\TaskQueue.php(48):
GuzzleHttp\Promise\Promise::GuzzleHttp\Promise{closure}() #4 C:\xamppNew\ht in
C:\xamppNew\htdocs\realestate\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 113
My config.php -
<?php
session_start();
require_once 'vendor/autoload.php';
$google_client = new Google_Client();
$google_client->setAccessType('offline');
$google_client->setClientId('client key');
$google_client->setClientSecret('client secret key');
$google_client->setRedirectUri('http://localhost/realestate/index.php');
$google_client->addScope('email');
$google_client->addScope('profile');
?>
My index.php google api session codes-
<?php
include('config.php');
$login_button = '';
if(isset($_GET["code"]))
{
$token = $google_client->fetchAccessTokenWithAuthCode($_GET["code"]);
if(!isset($token['error']))
{
$google_client->setAccessToken($token['access_token']);
$_SESSION['access_token'] = $token['access_token'];
$google_service = new Google_Service_Oauth2($google_client);
$data = $google_service->userinfo->get();
if(!empty($data['given_name']))
{
$_SESSION['user_first_name'] = $data['given_name'];
}
if(!empty($data['family_name']))
{
$_SESSION['user_last_name'] = $data['family_name'];
}
if(!empty($data['email']))
{
$_SESSION['user_email_address'] = $data['email'];
}
if(!empty($data['gender']))
{
$_SESSION['user_gender'] = $data['gender'];
}
if(!empty($data['picture']))
{
$_SESSION['user_image'] = $data['picture'];
}
}
}
if(!isset($_SESSION['access_token']))
{
$login_button = '<a href="'.$google_client->createAuthUrl().'">Login With
Google</a>';
}
?>
//this is for testing purpose
<?php if($login_button == '') {echo '<h3><b>Name :</b>
'.$_SESSION['user_first_name'].' '.$_SESSION['user_last_name'].'</h3>';
echo '<h3><a href="logout.php">Logout</h3>
</div>'; }?>
//this is the login button-
<?php echo '<a class="btn connect-google">'.$login_button . '</a>'; ?>
My logout.php-
<?php
include('config.php');
$accesstoken=$_SESSION['access_token'];
//Reset OAuth access token
$google_client->revokeToken($accesstoken);
//Destroy entire session data.
session_destroy();
//redirect page to index.php
header('location:index');
?>
I have no idea how why it is happening and how to fix this. Btw after i logged in though google api in my website and refresh the page , it should refresh successfully while staying logged in . But it shows me the error and when i click back it takes to me google login page again.
I think your issue is that your not using your refresh token properly
oauth2callback.php
Notice how when the code is returned that i am storing both the access token and the refresh token into the session.
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Oauth2Authentication.php
Then check this to see how i test if the access token is expired and if it is i use the refresh token to fetch a new one.
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example: array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());
return $client;
}
/**
* Builds the redirect uri.
* Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to oauth2callback.php
* #return A redirect uri.
*/
function getRedirectUri(){
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if(strrpos($url, '?') > 0)
$url = substr($url, 0, strrpos($url, '?') ); // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/') ); // Removeing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
* #return A google client object.
*/
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();
}
}
userinfo
Also you should consider going though the People api instead of the userinfo endpoint its much more stable when requesting user profile information, as you are already requesting email and profile scopes you should already have access.
I'll like to update the title, short description and full description of my apps in google developper console.
I cannot do it in PHP, I have found some examples in python but I need in PHP.
Here is what I've done till now :
function updateListing($configFileJSON) {
echo "Updating Listings"."\n";
$packageName = 'com.mycompany.myapp';
$client = new Google_Client();
$client->setApplicationName($packageName);
$client->setClientId('100......usercontent.com');
$key = "Rdhmg......5_t";
$client->setClientSecret($key);
$client->setScopes(array('https://www.googleapis.com/auth/androidpublisher') );
try {
$service = new Google_Service_AndroidPublisher($client);
$app_edit = new Google_Service_AndroidPublisher_AppEdit();
$edits = $service->edits;
$edit_request = $edits->insert($packageName,$app_edit);
$edit = $edit_request->execute();
$editId = $edit->getId();
echo ("Created edit with id: $editId");
$listing = $service->listings;
$listing.setTitle("WWW");
$listing.setFullDescription("WWW");
$listing.setShortDescription("WWW");
// $listing.setVideo("WWW");
$updateListingsRequest = $edits->listings()->update($packageName,$editId,"af", $listing);
$updatedUsListing = $updateListingsRequest->execute();
echo("Created new AF app listing with title: " . $$updatedUsListing->getTitle());
} catch (Exception $e) {
var_dump( $e->getMessage() );
}
echo "ENDING"."\n";
}
I know there is still some code missing, but until now I get :
string(238) "{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
the sample in python is:
def main(argv):
# Authenticate and construct service.
service, flags = sample_tools.init(
argv,
'androidpublisher',
'v2',
__doc__,
__file__, parents=[argparser],
scope='https://www.googleapis.com/auth/androidpublisher')
# Process flags and read their values.
package_name = flags.package_name
try:
edit_request = service.edits().insert(body={}, packageName=package_name)
result = edit_request.execute()
edit_id = result['id']
listing_response_us = service.edits().listings().update(
editId=edit_id, packageName=package_name, language='af',
body={'fullDescription': 'Dessert trunk truck',
'shortDescription': 'Bacon ipsum',
'title': 'App Title US'}).execute()
print ('Listing for language %s was updated.'
% listing_response_us['language'])
listing_response_gb = service.edits().listings().update(
editId=edit_id, packageName=package_name, language='am',
body={'fullDescription': 'Pudding boot lorry',
'shortDescription': 'Pancetta ipsum',
'title': 'App Title UK'}).execute()
print ('Listing for language %s was updated.'
% listing_response_gb['language'])
commit_request = service.edits().commit(
editId=edit_id, packageName=package_name).execute()
# print 'Edit "%s" has been committed' % (commit_request['id'])
except client.AccessTokenRefreshError:
print ('The credentials have been revoked or expired, please re-run the '
'application to re-authorize')
if __name__ == '__main__':
main(sys.argv)
what I'm missing in the authentificate part? anyone have a sample of updating app listing in PHP?
Thanks
Your code appears to be missing the entire authentication section.
Oauth2Authentication.php
require_once __DIR__ . '/vendor/autoload.php';
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
$client = getOauth2Client();
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
return $client;
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Scopes will need to be changed depending upon the API's being accessed.
* Example: array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function buildClient(){
$client = new Google_Client();
$client->setAccessType("offline"); // offline access. Will result in a refresh token
$client->setIncludeGrantedScopes(true); // incremental auth
$client->setAuthConfig(__DIR__ . '/client_secrets.json');
$client->addScope([YOUR SCOPES HERE]);
$client->setRedirectUri(getRedirectUri());
return $client;
}
/**
* Builds the redirect uri.
* Documentation: https://developers.google.com/api-client-library/python/auth/installed-app#choosingredirecturi
* Hostname and current server path are needed to redirect to oauth2callback.php
* #return A redirect uri.
*/
function getRedirectUri(){
//Building Redirect URI
$url = $_SERVER['REQUEST_URI']; //returns the current URL
if(strrpos($url, '?') > 0)
$url = substr($url, 0, strrpos($url, '?') ); // Removing any parameters.
$folder = substr($url, 0, strrpos($url, '/') ); // Removeing current file.
return (isset($_SERVER['HTTPS']) ? "https" : "http") . '://' . $_SERVER['HTTP_HOST'] . $folder. '/oauth2callback.php';
}
/**
* Authenticating to Google using Oauth2
* Documentation: https://developers.google.com/identity/protocols/OAuth2
* Returns a Google client with refresh token and access tokens set.
* If not authencated then we will redirect to request authencation.
* #return A google client object.
*/
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();
}
}
oauth2callback.php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/Oauth2Authentication.php';
// Start a session to persist credentials.
session_start();
// Handle authorization flow from the server.
if (! isset($_GET['code'])) {
$client = buildClient();
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client = buildClient();
$client->authenticate($_GET['code']); // Exchange the authencation code for a refresh token and access token.
// Add access token and refresh token to seession.
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $client->getRefreshToken();
//Redirect back to main script
$redirect_uri = str_replace("oauth2callback.php",$_SESSION['mainScript'],$client->getRedirectUri());
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
I've been trying to set up OAuth for Etsy to use in a project but having trouble even getting the login page to load using PhpoAuthLib. Highly likely my low level of knowledge regarding the use of Oauth.
Currently this is my login page which is almost identical to the example given by the developer.
<?php
/**
* Example of retrieving an authentication token of the Etsy service
*
* PHP version 5.4
*
* #author IƱaki Abete <inakiabt+github#gmail.com>
* #copyright Copyright (c) 2013 The authors
* #license http://www.opensource.org/licenses/mit-license.html MIT License
*/
use OAuth\OAuth1\Service\Etsy;
use OAuth\Common\Storage\Session;
use OAuth\Common\Consumer\Credentials;
/**
* Bootstrap the example
*/
require_once 'OAuth/bootstrap.php';
// init contains my secret and key values
require_once 'OAuth/init.php';
// Session storage
$storage = new Session();
// Setup the credentials for the requests
$credentials = new Credentials(
$servicesCredentials['etsy']['key'],
$servicesCredentials['etsy']['secret'],
$currentUri->getAbsoluteUri()
);
// Instantiate the Etsy service using the credentials, http client and storage mechanism for the token
/** #var $etsyService Etsy */
$etsyService = $serviceFactory->createService('Etsy', $credentials, $storage);
if (!empty($_GET['oauth_token'])) {
$token = $storage->retrieveAccessToken('Etsy');
// This was a callback request from Etsy, get the token
$etsyService->requestAccessToken(
$_GET['oauth_token'],
$_GET['oauth_verifier'],
$token->getRequestTokenSecret()
);
// Send a request now that we have access token
$result = json_decode($etsyService->request('/private/users/__SELF__'));
echo 'result: <pre>' . print_r($result, true) . '</pre>';
} elseif (!empty($_GET['go']) && $_GET['go'] === 'go') {
$response = $etsyService->requestRequestToken();
$extra = $response->getExtraParams();
$url = $extra['login_url'];
header('Location: ' . $url);
} else {
$url = $currentUri->getRelativeUri() . '?go=go';
echo "<a href='$url'>Login with Etsy!</a>";
}
When running the page i get a fatal error of
Call to a member function getAbsoluteUri() on a non-object
I've been into the bootstrap.php and echoed a statement at the end which works fine so doesnt seem to be erroring there.
The error is on the line with
$currentUri->getAbsoluteUri()
not sure if it matters but the login page is located at mywebsite/folder/folder/etsylogin.php.. would this make any difference?
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";
?>
I am new to integrating api and I am trying to working with the google-api-php-client-0.6.0 and I registered my app at Google and also configured them in simple.php in dev.siva.com virtual host
<?php
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
require_once 'src/Google_Client.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/contacts/");
// Documentation: http://code.google.com/apis/gdata/docs/2.0/basics.html
// Visit https://code.google.com/apis/console?api=contacts to generate your
// oauth2_client_id, oauth2_client_secret, and register your oauth2_redirect_uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
$req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
// The contacts api only returns XML responses.
$response = json_encode(simplexml_load_string($val->getResponseBody()));
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
}
if (isset($auth)) {
print "<a class=login href='$auth'>Connect Me!</a>";
} else {
print "<a class=logout href='?logout'>Logout</a>";
}
I am able to login and I gave the redirect url to above code and I am being redirected but the problem is I am getting unable to connect page. Why?
The url is like this after redirection
https://dev.siva.com/simple.php?code=4/hqJo9FDtjcn46uuP6JXE
DuWLKTQn.Eo91flf65bgaXE-sT2ZLcbRbNNSqdQI
You can not use virtual host as redirect uri - refer https://developers.google.com/accounts/docs/OAuth2InstalledApp for more details. So you have two options - process it on {http://localhost} or get the code in title bar instead of query parameter. I would choose the first.