I am trying to access a users contact list using google Oauth2 but seem to be running into an error insufficient permision. My code is as below
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Google extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
require_once 'google-api-php-client/autoload.php'; // or wherever
autoload.php is located
$client = new Google_Client();
$scriptUri = "http://localhost/tcaller/google/";
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('Tcaller');
$client->setClientId('******');
$client->setClientSecret('****');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('******'); // API key
$client->setScopes(array('https://www.google.com/m8/feeds' , 'https://www.googleapis.com/auth/contacts.readonly'));
$plus = new Google_Service_Plus($client);
if (isset($_GET['logout'])) { // logout: destroy token
$this->session->unset_userdata("token");
die('Logged out.');
}
if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
$client->authenticate($_GET['code']);
$tokenArr = array('token' => $client->getAccessToken());
$this->session->set_userdata($tokenArr);//gets valid access token
$redirect = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; //set into session storage
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if ($this->session->userdata('token')) { // extract token from session and configure client
$token = $this->session->userdata('token');
$client->setAccessToken($token);
try {
$me = $plus->people->get('me');
print_r($me);
} catch (apiServiceException $e) {
// Handle exception. You can also catch Exception here.
// You can also get the error code from $e->getCode();
echo 'error';
}
}
if (!$client->getAccessToken()) { // auth call to google
$authUrl = $client->createAuthUrl();
header("Location: ".$authUrl);
die();
}
}
}
?>
I am getting the error
Fatal error: Uncaught exception 'Google_Service_Exception' with
message 'Error calling GET
https://www.googleapis.com/plus/v1/people/me?key=%2A%2A%2A%2A%2A%2A:
(403) Insufficient Permission' in
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php:111
Stack trace: #0
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php(63):
Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request),
Object(Google_Client)) #1 [internal function]:
Google_Http_REST::doExecute(Object(Google_Client),
Object(Google_Http_Request)) #2
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Task\Runner.php(172):
call_user_func_array(Array, Array) #3
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php(47):
Google_Task_Runner->run() #4
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Client.php(564):
Google_Http_REST::execute(Object(Google_Client), Object(Google_H in
C:\xampp\htdocs\tcaller\application\controllers\google-api-php-client\src\Google\Http\REST.php
on line 111
Am i missing something
You should not need to use a separate API key and call $client->setDeveloperKey() as you're obtaining and using an OAuth 2.0 access token already with a client secret. Moreover, it seems that that is incorrect and/or not associated with the same project. So please try with that call removed.
Related
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 integrated both google and facebook oauth in my application .
First I initiated the class for google like this
$client = new Google_Client();
$client->setApplicationName("urmk google login");
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
return;
}
Google login process is working fine and i am able to get user info too. But
Then I integrated facebook oauth
FacebookSession::setDefaultApplication('APP_ID', 'APP_SECRET');
$helper = new FacebookRedirectLoginHelper('http://example.com/');
$loginUrl = $helper->getLoginUrl();
try {
$session = $helper->getSessionFromRedirect();
} catch(FacebookRequestException $ex) {
// When Facebook returns an error
} catch(\Exception $ex) {
// When validation fails or other local issues
}
if ($session) {
// Logged in
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
}
It successfully takes me to user account where it ask for the user permission, but while redirecting to my SITE it throws an error saying
Fatal error: Uncaught exception 'Google_AuthException' with message
'Error fetching OAuth2 access token, message: 'invalid_grant'' in
C:\xampp\htdocs\urmk\lib\src\auth\Google_OAuth2.php:113 Stack trace:
#0 C:\xampp\htdocs\urmk\lib\src\Google_Client.php(131):
Google_OAuth2->authenticate(Array, 'AQASSzhhLhYIYxI...') #1
C:\xampp\htdocs\urmk\index.php(66):
Google_Client->authenticate('AQASSzhhLhYIYxI...') #2 {main} thrown in
C:\xampp\htdocs\urmk\lib\src\auth\Google_OAuth2.php on line 113**
And again if i change the if (isset($_GET['code'])) to if (isset($_GET['something else'])) . It works fine. So how to resolve this error. Any help would be appreciated.
I believe the problem is that you have parameters in the 'authenticate' function call. From what I saw in the Google code for 'Google_OAuth2.php', it calls it itself. You will need to make sure that you set the variables. Check out the code below.
Also make sure you are using the correct version of the Google code... Online vs. Installed. I read that Installed version is Native.
if(isset($_GET['code']))
{
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
You can set the access token by...
if(isset($_SESSION['access_token']))
{
$client->setAccessToken($_SESSION['access_token']);
}
If all else fails then read this document...
http://25labs.com/tutorial-implementing-google-api-using-oauth-2-0-in-php/
Also, catch the exception so you can at least get one or the other as a successful authentication rather than erroring out all together.
I'm writing a Wordpress plugin which displays visits on a page. Everything's done and it works perfectly... for an hour. I can't refresh the token when it expires, so the end-user can't see Analytics results. I don't know what am I doing wrong, maybe I misunderstood the authentication process.
This is how I manage the first connection to the API:
$client->setClientId(get_option('client_ID'));
$client->setClientSecret(get_option('client_secret'));
$client->setRedirectUri(get_option('redirectURI'));
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline');
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'><button>Authorize Google</button></a>";
And then i do this:
try {
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
update_option('token', $_SESSION['token']);
$tok = json_decode($_SESSION['token']);
update_option('refresh_token', $tok->refresh_token);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
?><script type="text/javascript">
window.location="<?php filter_var($redirect, FILTER_SANITIZE_URL)?>";
</script><?php
}
if (isset($_SESSION['token'])) {
update_option('token', $_SESSION['token']);
$client->setAccessToken($_SESSION['token']);
}
} catch (Google_AuthException $e){
return FALSE;
}
This works fine. Now here's the part, where it should use the token thats stored as an option and if it expired, use refresh_token to get a new one automatically. Here's the code:
$client = new Google_Client();
$client->setApplicationName('AnalyticsPK Plugin for Wordpress');
$client->setClientId(get_option('client_ID'));
$client->setClientSecret(get_option('client_secret'));
$client->setRedirectUri(get_option('redirectURI'));
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
$client->setAccessType('offline');
$client->setApprovalPrompt("force");
echo "Token: ".get_option('token')."<br>";
echo "Refresh token: ".get_option('refresh_token')."<br>";
$client->setAccessToken(get_option('token'));
if ($client->isAccessTokenExpired()){
echo "Token expired <br>";
$client->refreshToken(get_option('refresh_token'));
echo "New token: ".$client->getAccessToken();
}
//echo "Token: ".get_option('token');
//echo "Refresh token: ".get_option('refresh_token');
// Magic. Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
$analytics = new Google_AnalyticsService($client);
When the token expiration time passes, I get an error:
Fatal error: Uncaught exception 'Google_AuthException' with message
'Error refreshing the OAuth2 token, message: '{ "error" :
"invalid_request", "error_description" : "Client must specify either
client_id or client_assertion, not both" }'' in
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/google-api-php-client/src/auth/Google_OAuth2.php:288
Stack trace: #0
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/google-api-php-client/src/auth/Google_OAuth2.php(248):
Google_OAuth2->refreshTokenRequest(Array) #1
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/google-api-php-client/src/Google_Client.php(311):
Google_OAuth2->refreshToken('1/XCyf8ofh6H3kL...') #2
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/AnalyticsPK.php(90):
Google_Client->refreshToken('1/XCyf8ofh6H3kL...') #3
/_wpsu/analytics/wp-includes/widgets.php(182):
AnalyticsPK->widget(Array, Array) #4 [internal function]:
WP_Widget->display_callback(Array, Array) #5
/_wpsu/analytics/wp-includes/widgets.php(895):
call_user_func_array(Array, Array) #6 /_wpsu/analytics/ in
/_wpsu/analytics/wp-content/plugins/AnalyticsPK/google-api-php-client/src/auth/Google_OAuth2.php
on line 288
What am I doing wrong with refreshing the token?
Thanks to Emily, I found the php client library already. I need to retrieve a users data. There is a function in the API that can do so :
Google_DirectoryService.php
/**
* retrieve user (users.get)
*
* #param string $userKey Email or immutable Id of the user
* #param array $optParams Optional parameters.
* #return Google_User
*/
public function get($userKey, $optParams = array()) {
$params = array('userKey' => $userKey);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Google_User($data);
} else {
return $data;
}
}
index.php
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DirectoryService.php';
$client = new Google_Client();
$client->setApplicationName("IAA SIS");
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://mypage.com/oauth2callback');
$client->setDeveloperKey('xxx');
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly'));
$service = new Google_DirectoryService($client);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$results = $service->users->get('$email', 'public', $optParams); //Pass email to function parameter ? I'm not sure.
?>
I think the way I pass the parameter is wrong which i got error after adding the last line. How do I pass users login email to the function correctly ?
The error i got is :
[08-Jan-2014 03:17:33 America/Chicago] PHP Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/admin/directory/v1/users/me?key=: (403) Insufficient Permission' in /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php:66
Stack trace:
#0 /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
#1 /home2/iaapro/public_html/php/google-api-php-client/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest))
#2 /home2/iaapro/public_html/php/google-api-php-client/src/contrib/Google_DirectoryService.php(653): Google_ServiceResource->__call('get', Array)
#3 /home2/iaapro/public_html/php/google-plus-access.php(44): Google_UsersServiceResource->get('me')
#4 /home2/iaapro/public_html/php/index.php(2): include_once('/home2/iaapro/p...')
#5 {main}
thrown in /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php on line 66
In addition, I have checked "Enable API Access" on admin.google.com and enable Admin SDK on Google APIs Console.
Can anyone gives me some help please ?
Finally, I figured out how to call the array using Google directory service API. Please refer to the code below:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
require_once 'google-api-php-client/src/contrib/Google_DirectoryService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
//*********** Replace with Your API Credentials **************
$client->setClientId('Your_Client_ID');
$client->setClientSecret('Your_Client_Sercret');
$client->setRedirectUri('http://example.com/oauth2callback');
$client->setDeveloperKey('Your_API_Key');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly'));
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address
$adminService = new Google_DirectoryService($client); // Call directory API
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_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()) {
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$users = $adminService->users->get($email);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
Have you checked out the Google API PHP client library? (https://code.google.com/p/google-api-php-client/)
Also, they have a github page: https://github.com/google/google-api-php-client
Once you downloaded the library from the site, you can see that the library has the Google_DirectoryService
I'm attempting to use the Google Calendar API version3 (PHP) to manage calendars.
I can easily retrieve information regarding a calendar such as calendar names and calendar lists, but I am unsuccessful in actually 'writing' to a calendar such as adding events or creating a secondary calendar. I always receive the following error in my attempt.
Anybody out there that can help? I have looked everywhere in Google's documentation but can't find any answers.
The error (if trying to post, not retrieve info):
Fatal error: Uncaught exception 'apiServiceException' with message 'Error calling POST https://www.googleapis.com/calendar/v3/calendars?key=eyfheufheuwehwi: (400) Invalid Value' in /home/incs/google-api-php-client/src/io/apiREST.php:86 Stack trace: #0 /home/incs/google-api-php-client/src/io/apiREST.php(56): apiREST::decodeHttpResponse(Object(apiHttpRequest)) #1 /home/incs/google-api-php-client/src/service/apiServiceResource.php(187): apiREST::execute(Object(apiServiceRequest)) #2 /home/incs/google-api-php-client/src/contrib/apiCalendarService.php(228): apiServiceResource->__call('insert', Array) #3 /home/public_html/gateway/google/index.php(130): CalendarsServiceResource->insert(Object(Calendar)) #4 {main} thrown in /home/incs/google-api-php-client/src/io/apiREST.php on line 86
the code (by the way my access keys are set in the config.php hence the commented $client lines)
require("/home/incs/google-api-php-client/src/apiClient.php");
require("/home/incs/google-api-php-client/src/contrib/apiCalendarService.php");
session_start();
$client = new apiClient();
$client->setApplicationName("Google Calendar PHP Starter Application");
// Visit https://code.google.com/apis/console?api=calendar to generate your
// client id, client secret, and to register your redirect uri.
// $client->setClientId('insert_your_oauth2_client_id');
// $client->setClientSecret('insert_your_oauth2_client_secret');
// $client->setRedirectUri('insert_your_oauth2_redirect_uri');
// $client->setDeveloperKey('insert_your_developer_key');
$service = new apiCalendarService($client);
if (isset($_GET['logout']))
{
unset($_SESSION['token']);
}
if (isset($_GET['code']))
{
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token']))
{
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken())
{
$calendar = new Calendar();
$calendar->setSummary('calendarSummary');
$calendar->setTimeZone('American/Los_Angeles');
$createdCalendar = $service->calendars->insert($calendar);
$calList = $service->calendarList->listCalendarList();
print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
}
else
{
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
As it is right now, Google has an error in their code sample (which is where I got the code that I pasted here). In that sample the following needs to be corrected for it to work:
$calendar->setTimeZone('American/Los_Angeles');
needs to be corrected to
$calendar->setTimeZone('America/Los_Angeles');
And then no error will be thrown.