I am using the following code which was largely lifted from this tutorial - http://www.daimto.com/google-oauth2-php/
I have added the line client->setAccessType("offline"); in order to receive a refresh token from Google which I can see coming through from print "Access from google: " . $_SESSION['token'];.
I'm struggling to understand how to use the refresh token in order to get authorisation. What I'd ideally like to is update this script to
- use a refresh token if one is available, or
- present the existing "Connect Me" link if one is not
I plan to store the refresh token in a DB eventually, however to get it working initially I will just hard code.
Any help is much appreciated!
<?php
set_include_path('src');
require_once 'Google/Client.php';
require_once 'Google/Service/Calendar.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("XXXXXXXXXXXXXXXXXXXX");
$client->setClientId('XXXXXXXXXXXXXXXXXXXX');
$client->setClientSecret('XXXXXXXXXXXXXXXXXXXX');
$client->setRedirectUri('XXXXXXXXXXXXXXXXXXXX');
$client->setAccessType("offline");
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));
//For loging out.
if ($_GET['logout'] == "1") {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
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));
}
// Step 1: The user has not authenticated we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$client->setAccessToken($_SESSION['token']);
$service = new Google_Service_Calendar($client);
}
print "<br>";
print "Access from google: " . $_SESSION['token'];
print "<br><br>";
require_once 'calendar_app.php';
?>
Related
After finally getting something besides NULL to be returned for an access token or refresh token, I am now getting an error saying my authorization token is expired. I've tried authorizing with 2 different Google accounts at different hours of the day, but I keep on getting the same authorization token.
How do I get a new, valid authorization token? When I go to account settings to remove authorization access for the app I am building in hopes to reset it, it isn't listed as an authorized app / service.
Here is my code:
require_once 'vendor/autoload.php';
$redirect_uri = 'site url';
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setRedirectUri($redirect_uri);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
$client->authenticate($_GET['code']);
$refreshToken = $client->getRefreshToken();
var_dump($refreshToken);
$accessToken = $client->getAccessToken();
$aT = $client->fetchAccessTokenWithAuthCode($_GET['code']);
var_dump($accessToken);
var_dump($aT);
The last line is what returns the error. The other var_dumps return NULL.
The process you are following for authentication is not the proper one, or at least that what it seems. After setting the client configuration you have to check if you have an access code, if there is no access code then you redirect the user to authenticate and after the user is authenticated, you redirect the user to do what you want. You are also missing the scopes your app needs in order to get proper access. Delete your app from the connected apps and sites in your Google profile and then try the following please:
<?php session_start();
//INCLUDE PHP CLIENT LIBRARY
require_once 'vendor/autoload.php';
$scopes = array("email");
// Create client object
$client = new Google_Client();
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/index.php');
$client->setAuthConfig("client_secrets.json");
$client->addScope($scopes);
$client->setAccessType('offline');
$client->setApprovalPrompt('force');
if ( isset($_SESSION['access_token']) && $_SESSION["access_token"]){
$client->setAccessToken($_SESSION['access_token']);
print_r($_SESSION['access_token']);
echo "<br>***************************************************************************************************************************************<br>";
print "Access token creation time: ".date('M d, Y - H:i:s', $_SESSION['access_token']['created']);
echo "<br>*********************************************************************<br>";
print "Refresh token: ".$_SESSION['access_token']['refresh_token'];
} else {
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/index.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
Please don't forget to review the documentation that explains the authorization process wich is found here.
i am trying to create a token/refreshToken so my website will be able to submit data to Google Sheets without asking the end user for permissions and i am struggling with this for few hours now..
I tried many different codes i found on the web + Google's docs and i made some progress but i can't get it to work and i can't figure what i am missing..
At this point i get no error (neither in my logs) but also i don't get any redirect or new window for authorizing the app
<?php
session_start();
require_once('php-google-oauth/Google_Client.php');
include_once('lib/autoload.php');
include_once('php-google-oauth/auth/Google_OAuth2.php');
$CLIENT_ID = 'xxxxxxxxxxxx.apps.googleusercontent.com';
$SECRET = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$REDIRECT = 'http://mywebsite.com';
$APIKEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// $KEY = file_get_contents('php-google-oauth/client_secret.json');
$client = new Google_Client();
$client->setApplicationName("Contacts to Google Sheets");
$client->setClientId($CLIENT_ID);
$client->setClientSecret($SECRET);
$client->setRedirectUri($REDIRECT);
$client->setScopes(array('https://spreadsheets.google.com/feeds'));
$client->setAccessType('offline'); // Gets us our refresh token
// Step 1: The user has not authenticated so we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
}
// Step 2: The user accepted your access now you need to exchange it.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . filter_var($REDIRECT, FILTER_SANITIZE_URL));
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
$token = $client->getAccessToken();
}
echo '<script>console.log("TOKEN: '. $token .'");</script>';
?>
Thanks in advance!
I looked at my code and tried this-
// Step 1: The user has not authenticated so we give them a link to login
if (!$client->getAccessToken() && !isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
echo 'Click here';
}
and now i do get a token back from Google
Using code below I successfully received a token and using this token also get user detail, but when I try to post/insert moment in user wall I see the following error message
Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling POST https:--www.googleapis.com/plus/v1/people/me/moments/vault: (401) Unauthorized' in $_SESSION['access_token_gp']
I got user token when user login using my site in login page I ask for below permission
$client->addScope("email");
$client->addScope("https://www.googleapis.com/auth/plus.stream.write");
$client->addScope("https://www.googleapis.com/auth/plus.login");
If I print_r($tokenInfo); you will see all scope which I ask at login time.
The full code:
session_start();
require_once realpath(dirname(__FILE__) . '/google-api-php-client-master/autoload.php');
$client_id = 'my_client_id';
$client_secret = 'my_secret_key';
$redirect_uri = 'my_redirect_url';
// code to post in google plus start here //
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
if (isset($_SESSION['access_token_gp'])) {
// Verify the token
$token = json_decode($_SESSION['access_token_gp']);
$reqUrl = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token='.$token->access_token;
$req = new Google_Http_Request($reqUrl);
$tokenInfo = get_object_vars(json_decode($client->getAuth()->authenticatedRequest($req)->getResponseBody()));
if($tokenInfo['expires_in'] <= 0){
$client->authenticate($_SESSION['access_token_gp']);
$_SESSION['access_token_gp'] = $client->getAccessToken();
} else {
$client->setAccessToken($_SESSION['access_token_gp']);
}
$plusservicemoment = new Google_Service_Plus_Moment();
$plusservicemoment->setType("http://schemas.google.com/AddActivity");
$plusService = new Google_Service_Plus($client);
$item_scope = new Google_Service_Plus_ItemScope();
$item_scope->setId($tokenInfo['user_id']);
$item_scope->setType("http://schemas.google.com/AddActivity");
$item_scope->setName("The madexme Platform");
$item_scope->setDescription("A page that describes just how madexme is work!");
//$item_scope->setImage("full image path here");
$plusservicemoment->setTarget($item_scope);
$result = $plusService->moments->insert('me','vault',$plusservicemoment);
//print_r($result);
}
// code to post in google plus end here //
Make sure you have the latest client lib from GitHub. There is something wrong with your Oauth2 connection. This code is partially converted from my Google Google Calendar API tutorial. I don't have the power to test it right now. But this should be close. I will test it tonight.
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Plus.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("AIzaSyBBH88dIQPjcl5nIG-n1mmuQ12J7HThDBE");
$client->setClientId('2046123799103-i6cjd1hkjntu5bkdkjj5cdnpcu4iju8p.apps.googleusercontent.com');
$client->setClientSecret('6s4YOx3upyJhtwnetovfK40e');
$client->setRedirectUri('http://localhost/google-api-php-client-samples/Calendar/oauth2Pure.php');
$client->setAccessType('offline'); // Gets us our refreshtoken
$client->setScopes(array(https://www.googleapis.com/auth/plus.login'));
//For loging out.
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
// Step 2: The user accepted your access now you need to exchange it.
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));
}
// Step 1: The user has not authenticated we give them a link to login
if (!isset($_SESSION['token'])) {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
// Step 3: We have access we can now create our service
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
print "<a class='logout' href='".$_SERVER['PHP_SELF']."?logout=1'>LogOut</a><br>";
$service = new Google_Service_Plus($client);
$moment = new Google_Moment();
$moment->setType('http://schemas.google.com/AddActivity');
$itemScope = new Google_ItemScope();
$itemScope->setUrl('https://developers.google.com/+/plugins/snippet/examples/thing');
$moment->setTarget($itemScope);
$plus->moments->insert('me', 'vault', $moment);
?>
Again I hope you understand that this is not going to show up on the users Google+ page / timeline.
I have followed the directions exactly, copied code examples - I cannot get this to respond (write an event on a calendar).
Please help - if there is any help for me. AFter 12 hours of working on this with a huge deadline of tomorrow, I'm about to pull my hair out.
On Google Developer Console, created a project and generated keys required.
The keys below are altered for safety.
None of the echos are showing except for the first one with the order number in it.
My programmer got this code to work, so I know it's OK - it's something set up wrong on the console, but I need a clue:
Full code - like I said, it's been tested and works on another project.
if(isset($_GET['orderid']) )
{
$_SESSION['oid']= $_GET['orderid'];
}
echo $_GET['orderid'];
$client = new Google_Client();
$client->setApplicationName("API Project");
$client->setClientId('9999999999999.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxxx');
$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];
$client->setRedirectUri($scriptUri);
//$client->setDeveloperKey('AIxxxxxxxxxxxxx'); - SERVER APPS
$client->setDeveloperKey('AIxxxxxxxxxxxxxxx'); // - WEB APPS
$cal = new Google_CalendarService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
echo $_GET['code'];
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
echo $_SESSION['token'];
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$calList = $cal->calendarList->listCalendarList();
//print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
// database access is here and like I said, it is tested and working
echo "<center>Event has successfully added to Your Google Calendar...</center>";
unset($_SESSION['oid']);
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Click Here for Google Authorization!</a>";
}
If you just want to add an event on Google Calendar (no other interactions), I think you should use the direct link :
https://www.google.com/calendar/render?action=TEMPLATE&text=Your+event+title&dates=20140325T090000Z/20140325T100000Z&details=Your+event+description&location=Room+12&pli=1&uid&sf=true&output=xml
You just have to customize variables and escape non-URI characters.
** EDIT **
Do you successfully connect the user through OAuth 2?
** EDIT 2 **
Your code is working for me without the DB access :
if ($client->getAccessToken()) {
$calList = $cal->calendarList->listCalendarList();
//print "<h1>Calendar List</h1><pre>" . print_r($calList, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
// DB ACCESS
echo "<center>Event has successfully added to Your Google Calendar...</center>";
unset($_SESSION['oid']);
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Click Here for Google Authorization!</a>";
}
Julian
My goal is to show google analytics datas on the header of my site. Thats all I have until now (its from googleApiPhPClient/examples/analytics:
require_once 'library/GoogleApiPhpClient/apiClient.php';
$client = new apiClient();
$client->setApplicationName("Google Analytics PHP Starter Application");
// Visit https://code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('aaa');
$client->setClientSecret('bbb_gK');
$client->setRedirectUri('ccc');
$client->setDeveloperKey('dd');
require_once ('contrib/apiAnalyticsService.php');
$service = new apiAnalyticsService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
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 ($client->getAccessToken()) {
$props = $service->management_webproperties->listManagementWebproperties("~all");
print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";
$accounts = $service->management_accounts->listManagementAccounts();
print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
$segments = $service->management_segments->listManagementSegments();
print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";
$goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
print "<h1>Segments</h1><pre>" . print_r($goals, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
but this only drops a "connect me" link. Am in the somewhat right way on getting analytic datas anyway?
I've been using this code.google.com/p/gapi-google-analytics-php-interface which only requires the google account user name and password and works pretty well
a sample code of mine where im checking visits $ga->requestReportData($ga_profile_id,array('browser','browserVersion','country'),array('pageviews','visits'),null,"country==USA",$yesterday,$todate);
when you log in to your account, select the profile you already made for your web site . when you will click it, the url would be like google.com/analytics/web/#report/visitors-overview/… so the ga_profile_id would be the one written after "p" in the URL.. i see this way only to get this profile id