Apologies if I am missing something obvious in this question...
I have an index.php file where I initialise a Google Client, set the scopes, create a service and start pulling data from the Google Tenancy. This works fine.
<?php
require_once 'vendor/autoload.php';
const CLIENT_ID = MY CLIENT ID;
const CLIENT_SECRET = MY SECRET;
const REDIRECT_URI = REDIRECT URI;
session_start();
$client = new Google_Client();
$client->setApplicationName("My Application");
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setScopes('admin scopes');
$adminservice = new Google_Service_Directory($client);
My issue is, I want to get a user's ID from the AdminDirectory API and then pass it to a new page, user.php, with the GET tag id.
So, for example:
<?php
$id = $adminservice->users->get(EMAIL)->id;
?>
<a href = 'user.php?id=<?php echo $id; ?>'>Click Here</a>
How do I transfer my $client variable over to this new user.php page?
I have tried putting the client in $_SESSION['client'] and then extracting it on the new page. I have also tried reinitialising the entire client. Neither seem to work.
Thanks
You have to import the class on the user.php page:
require_once 'vendor/autoload.php';
Next, store the object in the session:
$_SESSION['googleclient'] = $client;
Now to get it on the other page do:
$client = $_SESSION['client'];
If you need anymore help look at this: move object from 1 page to another?
Related
I implemented Google OAuth2 for user login on my website.
It works but after 1 hour token expires and login fails.
I read on the web that I need to get the Refresh Token (for Facebook Login I used a Long Lived Token), but code I tried doesn't work.
Here the code:
//LOGIN CALLBACK FROM GOOGLE
$gClient = new Google_Client();
$gClient->setApplicationName(SITE_TITLE);
$gClient->setClientId(get_option('google_api_id')->value);
$gClient->setClientSecret(get_option('google_api_secret')->value);
$gClient->addScope('profile');
$gClient->addScope('email');
$gClient->setRedirectUri(SITE_URL."/login/google/google-callback.php");
if(isset($_GET['code'])) {
$gClient->setAccessType('offline');
$token = $gClient->fetchAccessTokenWithAuthCode($_GET['code']);
$gClient->setAccessToken($token['access_token']);
$_SESSION['google_access_token'] = $token['access_token'];
}
if($gClient->getAccessToken()) {
// Get user profile data from google
$google_oauthV2 = new Google_Service_Oauth2($gClient);
$gpUserProfile = $google_oauthV2->userinfo->get();
}
...
This first snippet works fine.
In this second snipped, when user change page, I verify if login is still active:
$gClient = new Google_Client();
$gClient->setApplicationName(SITE_TITLE);
$gClient->setClientId(get_option('google_api_id')->value);
$gClient->setClientSecret(get_option('google_api_secret')->value);
$gClient->addScope('profile');
$gClient->addScope('email');
$gClient->setAccessType('offline');
$gClient->setAccessToken($_SESSION['google_access_token']);
if($gClient->getAccessToken()) {
if ($gClient->isAccessTokenExpired()) {
$gClient->fetchAccessTokenWithRefreshToken($gClient->getRefreshToken());
}
$google_oauthV2 = new Google_Service_Oauth2($gClient);
$gpUserProfile = $google_oauthV2->userinfo->get();
...
}
This second snipped doesn't work, because method fetchAccessTokenWithRefreshToken($gClient->getRefreshToken()) fails because $gClient->getRefreshToken() is NULL.
I debugged the callback and I saw that $token = $gClient->fetchAccessTokenWithAuthCode returns an array without "refresh_token" field.
Can anyone help me?
Thanks
Bye
I have next code for google auth
use Google\Spreadsheet\DefaultServiceRequest;
use Google\Spreadsheet\ServiceRequestFactory;
require './vendor/autoload.php';
$application_name = '*****';
$client_secret = '**********';
$client_id = '**********.apps.googleusercontent.com';
$scope = array('https://spreadsheets.google.com/feeds');
$key = file_get_contents(__DIR__.'/the_key.txt');
$client = new Google_Client();
$client->setApplicationName($application_name);
$client->setClientId($client_id);
$client->setAccessType('offline');
$client->setAccessToken($key);
$client->setScopes($scope);
$client->setApprovalPrompt('force');
$client->setClientSecret($client_secret);
if ($client->getAccessToken()) {
if($client->isAccessTokenExpired()) {
$newToken = json_encode($client->getAccessToken());
$token = $client->getAccessToken();
$client->refreshToken($token['refresh_token']);
json_encode($client->getAccessToken()));
}
$key = json_decode(file_get_contents(__DIR__.'/the_key.txt'));
First time fillin file via oauthcallback via browser, and it works ok, i got refresh token and all works ok.
But when token expires as you see in code i request new via refresh_token, but in result i didn't get new refresh_token.
Also i forced acces type to offline, and approval prompt to force in Client.php of google-oauth-client(because even if i set it via paramaters it didn't worked).
My script must be executed via cron. So i can't each time receive token manually. Can you help me with this?
I had a problem with updating user cover pic using php(zend framework) and Oauth.
I have added to my composer.json the following lines:
"require" : {
"google/auth": "0.7",
"google/apiclient" : "^2.0.0#RC"
}
After that I made composer-install + composer-update using and oppp I get the library inside my vendor.
I have configured my application inside google developing console, following the official tutorial by google :D
Now inside my controller I could easily request google web service using this method :
public function googleplusAction()
{
Zend_Loader::loadFile("HttpPost.class.php");
$client_id = "id_here";
$client_secret = "secret_here";
$application_name = "application_name_here";
$redirect_uri = "redirection_uri_here";
$oauth2_server_url = 'https://accounts.google.com/o/oauth2/auth';
$query_params = array(
'response_type' => 'code',
// The app needs to use Google API in the background
'client_id' => $client_id,
'redirect_uri' => $redirect_uri,
'scope' => 'https://www.googleapis.com/auth/userinfo.profile'
);
$forward_url = $oauth2_server_url . '?' . http_build_query($query_params);
header('Location: ' . $forward_url);
}
After that I get redirected to my redirection URI , and in the bar address I get a new variable 'code'.
Until now, I hope everything is fine , coming to the most important part , the controller of the redirection URI page , using the 'code' variable that I have talked about it before I tried to get an access token, but I was failed.
This is the method that should set a new cover picture on google plus :
$client_id = "client-id";
$client_secret = "g+-secret";
$application_name = "my-app-name";
$redirect_uri = "my-uri-on-g+";
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$service = new Google_Service_Oauth2($client);
$client->addScope(Google_Service_Oauth2::USERINFO_PROFILE);
$client->authenticate($_GET['code']); // I have the right code, and I am being authenticated
$plus = new Google_Service_Plus($client);
$person = $plus->people->get('me');
var_dump($person);
$pic = $this->session->image['generatedAbs'];
$gimg = new Google_Service_Plus_PersonCover();
$source = new Google_Service_Plus_PersonCoverCoverPhoto();
$source ->setUrl("$photo-that-i-wanted-to-put-on-g+");
$gimg->setCoverPhoto($source);
$person->setCover($gimg);}
So my questions are :
How can I change my google plus cover picture to a new png or JPEG picture that I have already in my project ?
inside the G+ library I found this method :
Google_Service_Plus_PersonCoverCoverPhoto();
inside a class called
Google_Service_Plus_PersonCover();
But how can I use it ?
I think that methods Google_Service_Plus_PersonCoverCoverPhoto() and Google_Service_Plus_PersonCover() are used by the client library to set it when the information is retrieved. It is not meant for you to be able to update the users cover on Google+, if that does work it will only update the class object which really there is no point in doing (IMO).
var_dump($person->Cover);
If you check the Plus.People documentation you will notice there are no update or patch methods. This is because its not possible to update a users information programmatically at this time.
Answer: Your inability to update the users cover picture has nothing to do with Oauth it has to do with the fact that this is not allowed by the API. Unfortunately it looks like you have done a lot of work for nothing this is why it is good to always consult the documentation before you begin you would have seen that it was not possible, and could have avoided a lot of unnecessary stress on yourself.
So this is what's on the top of the PHP file:
<?php
// Start the session
session_start();
?>
<?php
// Get the PHP helper library from twilio.com/docs/php/install
require_once('/path/to/twilio-php/Services/Twilio.php'); // Loads the library
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXX";
$token = "XXXXXXXXXXXXXXXXXX";
$client = new Services_Twilio($sid, $token);
$client->account->messages->sendMessage("+1234567890", "+0987654321", "Please?! I love you <3, Twilio Test");
?>
<?php
// Start the session
session_destroy();
?>
Then I have the <html> beneath.
The Issue I'm having is that the page just loads a white blank page and when I check the Twilio Log to see if any SMS are logged.
But the page loads just fine without the middle PHP (the part that's supposed to send the SMS through Twilio)
The Log is completely empty and shows no record of any outgoing SMS.
Any help would be appreciated!
Where are you getting sendMessage from? According to Docs this is how it is done
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "AC8ed2351ef2156d21a66faf913443188c";
$token = "{{ auth_token }}";
$client = new Services_Twilio($sid, $token);
$sms = $client->account->sms_messages->create("+14158141829", "+14159352345", "Jenny please?! I love you <3", array());
echo $sms->sid;
I am having trouble working with Google API on multiple pages. Example from Google works fine but all the code is on one page.
I have two pages. First page, where user click on login button and second page, where I use google api to pull user information.
First Page:
<?php
########## Google Settings.. Client ID, Client Secret from https://cloud.google.com/console #############
$google_client_id = 'myid';
$google_client_secret = 'mysecret';
$google_redirect_url = 'http://www.myWebsite.com/secondPage.php'; //path to your script
$google_developer_key = 'mydeveloperkey';
//include google api files
require_once '../includes/Google/autoload.php';
//start session
session_start();
$client = new Google_Client();
$client->setClientId($google_client_id);
$client->setClientSecret($google_client_secret);
$client->setRedirectUri($google_redirect_url);
$client->addScope("https://www.googleapis.com/auth/drive");
$client->addScope("https://www.googleapis.com/auth/calendar");
$client->addScope("https://www.googleapis.com/auth/gmail.compose");
$client->addScope("https://www.googleapis.com/auth/plus.me");
$drive_service = new Google_Service_Drive($client);
$calendar_service = new Google_Service_Calendar($client);
$gmail_service = new Google_Service_Gmail($client);
/************************************************
If we're logging out we just need to clear our
local access token in this case
************************************************/
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
// Authenticating the aunthentication URL. and starting session
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['secondPage.php'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
/************************************************
If we have an access token, we can make redirect to secondPage.php, else we generate an authentication URL.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
header("Location: http://www.myWebsite.com/secondPage.php");
die();
} else {
$authUrl = $client->createAuthUrl();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<img src="images/google-login-button.png" alt="Click to login">
</body>
</html>
secondPage.php:
<?php ob_start() ?>
<?php
//include google api files
require_once '../includes/Google/autoload.php';
//start session
session_start();
$client = new Google_Client();
/************************************************
If we have an access token, we can make
requests, else we redirect to firstPage.php.
************************************************/
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else {
header("Location: http://www.myWebsite.com/firstPage.php");
die();
}
// Rest is HTML
For some reason if statement on secondPage.php is resulting into false and else statement is redirecting it back to firstPage.php.
I am very new to programming altogether, I am pretty sure I am doing something which does not make sense. Let me know if I should add more information. When answering question please try to cover following questions:
Do I have to create separate Google_client object on every page.
Can I create Google_client object by setting access_token from session variable.
How should I divide the code so that on the firstPage.php, only have a login button and all other pages can use access_token to use google services.
there will be other pages where I will be using googleapi other than firstPage.php and secondPage.php.
1. Redirect properly
I do have some doubts about that line:
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['secondPage.php'];
It's because I'm pretty sure, that you have nothing set behind $_SERVER['secondPage.php'] variable. You should fix this to redirect to secondPage.php, and afterwards no more code in first page is required.
2. Set up accont in secondPage.php
In your first script you have such lines:
$client = new Google_Client();
$client->setClientId($google_client_id);
$client->setClientSecret($google_client_secret);
$client->setRedirectUri($google_redirect_url);
And you have ommited them in secondPage.php. That's probably reason why your second script does not work, because your script does not know with what account it is working. You have to configure you script all again there in second script, same way you did in first one. Also for now I would cut-off ob_start(), it may harden debugging.
I prefer you to read that example on google repository once again, carefully. It's pretty self explanatory and it just requires you to read it again and again, as long as you will have that strange little feeling... I can assure you, that you can do it easy and clean in three files: first one for ::authenticate() and set $_SESSION, second for the ::setAccessToken() and all rest, and third one with all $client class set up used by previous both.