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.
Related
I am stucked 3 days ago with Google Calendar API, I am new in Google API.
First of all I want to get events from users calendar.
I went through on the install process a few times, but my code always stop at fetchAccessTokenWithAuthCode function.
Probably I miss something really obvious, but I can't figure out what is wrong.
In web root I created a new folder for testing with 2 basic file from Google install site.
My php files:
index.php:
<?php
require_once 'path/googleapi/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('path/googleapi/credentials.json');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->setRedirectUri('https://site/google/oauth2callback.php');
$client->setAccessType('offline');
$client->setPrompt("consent");
$client->setIncludeGrantedScopes(true);
$auth_url = $client->createAuthUrl();
var_dump($auth_url);
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
var_dump($_SESSION);
} else {
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
?>
oauth2callback.php:
<?php
require_once 'path/googleapi/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfig('path/googleapi/credentials.json');
$client->setRedirectUri('https://site/google/oauth2callback.php');
$client->addScope(Google_Service_Calendar::CALENDAR_READONLY);
$client->setAccessType("offline");
if (! isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else {
var_dump($_GET['code']);
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
echo "<br>token:<br>";
var_dump($token);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'https://site/google/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
I got redirected to Google's site, once I grant permission I am redirected to the oauth2callback.php
In oauth2callback.php I can see the var_dump output for the code, but no further output, which means no response from fetchAccessTokenWithAuthCode function.
Any help is appreciated
I am using the PHP Google_Client to get the youtube playlist data on my web (a server-side Oauth ,without user check )
but get Error: redirect_uri_mismatch and message
The redirect URI in the request,
http://localhost/youtube/oauth2callback.php,
does not match the ones authorized for the OAuth client.
Visit https://console.developers.google.com/apis/credentialsoauthclient/112609190871896620853?project=756606231401
to update the authorized redirect URIs.
here is the http://localhost/youtube/index.php code
<?php
require_once 'vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/youtube');
$client->setAuthConfigFile('youtube-762b39a4f0b5.json');
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
$youtube = new Google_Service_YouTube($client);
$playlists = $youtube->playlists->listPlaylists("snippet,status", array(
'channelId' => 'UCBbOgoYXQdR-LRqrx7hdd6g'
));
echo json_encode($playlists->toSimpleObject());
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/youtube/oauth2callback.php';
var_dump($redirect_uri);
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
here is the http://localhost/youtube/oauth2callback.php
<?php
require_once __DIR__.'/vendor/autoload.php';
session_start();
$client = new Google_Client();
$client->setAuthConfigFile('client_secret.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] .'/youtube/oauth2callback.php');
$client->addScope('https://www.googleapis.com/auth/youtube');
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'] . '/youtube/index.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Any idea?
Looking at the screenshots, you have created a Service Account. Service Accounts use two-legged OAuth, and therefore do not have any user-consent-and-redirect dance.
A Service Account would not have permissions to videos in your personal Gmail account. Maybe that's OK, maybe it isn't. It depends on your use case which you don't describe in your question. If you need your application to act with the same permissions as your Gmail account, you'll need to use a slightly different technique. (described How do I authorise an app (web or installed) without user intervention? (canonical ?) and https://www.youtube.com/watch?v=hfWe1gPCnzc)
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
Thank you everyone for your time.
I've spent all day on this although, wasn't able to find a good example and answer, so I thought it may be relevant for the community.
<?php
session_start();
require_once ('Google/src/Google/autoload.php');
$client = new Google_Client();
$client->setApplicationName("xxxxx");
$client->setClientId('xxxxx');
$client->setClientSecret('xxxxx')
$client->setRedirectUri('xxxxx');
$client->addScope('profile');
$client->addScope('email');
$client->addScope('https://www.googleapis.com/auth/contacts.readonly');
if (isset($_GET['oauth'])) {
// Start auth flow by redirecting to Google's auth server
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
} else if (isset($_GET['code'])) {
// Receive auth code from Google, exchange it for an access token, and redirect to your base URL
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
} else if ($_SESSION['access_token']) {
// You have an access token; use it to call the People API
$client->setAccessToken($_SESSION['access_token']);
$service = new Google_Service_People($client);
$optParams = array('pageSize' => 10);
// TODO: Use service object to request People data
$results = $service->people_connections->listPeopleConnections('people/me', $optParams);
} else {
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/?oauth';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
Upon executing the script I simply get a blank white page, if I comment out $results = $service->people_connections->listPeopleConnections('people/me', $optParams) the script then works.
It looks like it loads the API properly and authenticates with Oauth and the token session variables are set; although when uncommented it is simply a white screen so I think the problem is retrieving data from the Google People API.
I'm trying to download a list of each users contacts (including name & email) to share a link with via email; after clicking a 'Login with Google' button.
Any assistance would be greatly appreciated, thank you for your time!
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.