Google Cal API - Script to Check Events - php

I want to build a script that will check a Authenticated User's Google Calendar via the Google Calendar PHP Client. I was able to build a simple page that lets a user Auth and give permission to the Calendar Events. I receive a token and then grab a 15 upcoming events via:
$googleCal = new Google_Service_Calendar($googleClient);
$results = $googleCal->events->listEvents($calendarId, $optParams);
But what I'm struggling with is how to save this so I can have a script check this everyday to see if there were new events added. I think what I have is close just struggling to get over the finish line.
Thanks!
--
Update, I'm trying to use the refresh token, here is my code:
public function checkRedirectCode()
{
if(isset($_GET['code']))
{
$this->client->authenticate($_GET['code']);
// $this->setToken($this->client->getRefreshToken());
$this->setToken($this->client->getAccessToken());
$this->storeUser($this->getPayload());
return true;
}
return false;
}
public function setToken($token)
{
$_SESSION['access_token'] = $token;
$this->client->setAccessToken($token);
}
I have been able to echo the refresh token so I know I'm getting a proper refresh token but I'm getting errors whenever I use the commented out string. Any ideas?

To enable your script to be called beyond the lifetime of the original access token (which only last an hour), you will need to retrieve and store the refresh token during the initial authorisation, and then use this to generate a new access token each time your script runs.
Access tokens have limited lifetimes. If your application needs access
to a Google API beyond the lifetime of a single access token, it can
obtain a refresh token. A refresh token allows your application to
obtain new access tokens.
https://developers.google.com/identity/protocols/OAuth2#basicsteps (4. Refresh the access token, if necessary.)
After the user has authenticated your app, they are returned to your redirect URI with the code query-string.
The following is an example of authenticating and getting the refresh token (this uses Analytics, but should be the same for other services):
$client = new Google_Client();
$client->setClientId('xxx');
$client->setClientSecret('xxx');
$client->setRedirectUri('xxx');
//authenticate with the code returned from google
$authenticate = $client->authenticate($_GET['code']);
//get the refresh token
$refreshToken = $client->getRefreshToken();
//store refresh token in database...
Then, when you run your daily script, use the refresh token (retrieved from your database) to generate a new access token:
$client = new Google_Client();
$client->setClientId('xxx');
$client->setClientSecret('yyy');
$client->addScope(Google_Service_Analytics::ANALYTICS_READONLY);
$client->refreshToken($user->refresh_token);
$newToken = $client->getAccessToken();
$client->setAccessToken($newToken);

Related

how to get refresh token for login with google api?

First of all, i am an absolute beginner in google apis. I followed this tutorial along with many other tutorials on the web -> https://www.webslesson.info/2019/09/how-to-make-login-with-google-account-using-php.html
and it is successfully working. But i cant refresh the page after login because i dont have a refresh token.
My config.php-
<?php
session_start();
require_once 'vendor/autoload.php';
$google_client = new Google_Client();
$google_client->setClientId('client id here');
$google_client->setClientSecret('client screct here');
$google_client->setRedirectUri('http://localhost/realestate/index.php');
$google_client->addScope('email');
$google_client->addScope('profile');
$google_client->setAccessType('offline');
$google_client->setApprovalPrompt('force');
?>
My index file-
<?php
//Include Configuration File
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 = 'Login With Google';
}
?>
I asked a question somewhat related to this question but that was not working. So I asked again here, sorry for that.
So,how can i setup refresh token ?
You actually do have a refresh token. THe issue or rather google thinks you do.
When you add this to your code
$google_client->setAccessType('offline');
It tells google that you would like to access the users data when the user is not online.
However the problem you are having is that with some languages the PHP for example, Google sends the refresh token to you the first time the user authenticates and then they assume that you have stored it on your server someplace so that you can use it the next time. If you log the user in again you often will not be granted a new refresh token because again they think you have one.
How to fix this is to have the user revoke your access revoke. Then the next time they visit your site they should be prompted to login this time you should have a refresh token. Remember to store it someplace so that you have it next time.
Also when you refresh the access token remember to check that the refresh token is there and if its different then the one you have then store the new one
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
}
Update for the frustrated. user447951
If you are not seeing a refresh token even after adding offline it is because this client library does not return to you a refresh token after every call, authorization request or refresh of the access token. (yes some of the google client libraries do, this one does not)
It doesn't because It is assumed when the user authorized the application the first time that the developer stored it, so the next time you authorize the user you will not get a new refresh token back. Nor will you get one when you refresh the access token.
You need to go to either the users google account and revoke access for the third party app then request authorizing of the user again. or use the revoke endpoint to revoke the users access. When the user is prompted again to request authorizing then a new refresh token will be returned. This time save it.
NO it is not enough to just remove the credentials that you have stored in your system and use force prompt. There must be nothing in the users account to state they had previously granted this application access.
use the revoke end point to revoke the users access to the app
Go to the users account under third party pass with access and revoke it.

How do I set the refresh token for Youtube API in php

I got a refresh token using OAuth playground, but I am not sure what to do with it. Using the php sample code to upload a video, I added this line of code
$client->refreshToken($refreshToken);
Is this all I need to do?
Few more steps are required once you have the OAuth2 refresh token:
Define the path to credentials file obtain from Google's dev console (also called "client-secret") and set it for $client:
$credentialsFilePath = "client_secret_file.json";
$client->setAuthConfig($credentialsFilePath);
Add the required scope (see here) which should match the scope defined when you received the refresh token (after first user's consent), this is a scope example for Gmail:
$client->addScope('https://mail.google.com/');
Set your refresh token (gets a new token and sets it to the $client):
$refreshToken = "1/Je...................";
$client->refreshToken($refreshToken);
Get your access token (which I like to store in session):
$_SESSION['access_token'] = $client->getAccessToken();
Start calling the API:
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// API calls
}
Full code for Gmail requests using OAuth2 with a refresh token:
https://eval.in/776863

How do I refresh OAuth token?

I am using Google Drive API and authenticating using OAuth token using PHP program. For my test program I went to OAuth url manually and created a token. Then, I used it in the program and saved it to the file. From next time onwards the token is loaded from file and the program is able to access Google Drive. However, since the token would only be valid for 1 hr, after that I get the error since the token it retrieves from the file won't be valid anymore. I am not clear on how I can refresh the token so that its not required to manually obtain a new token.
Following is my code -
$client = new Google_Client();
$client->setClientId( CLIENT_ID );
$client->setClientSecret( CLIENT_SECRET );
$client->setRedirectUri( REDIRECT_URIS );
$client->setScopes($SCOPES);
$client->setAccessType('offline');
$client->setAuthConfigFile(CLIENT_SECRET_PATH);
If the cred file exist, I pull the token from that file else I would be fetching it. For now, the first time token I am setting manually -
if (file_exists(CREDENTIALS_PATH)) {
$accessToken = file_get_contents(CREDENTIALS_PATH);
} else {
$authCode = 'My Auth Code';
$accessToken = $client->authenticate($authCode);
}
file_put_contents(CREDENTIALS_PATH, $accessToken);
$client->setAccessToken($accessToken);
Now, if the token is expired I need to refresh the token automatically.
if ($client->isAccessTokenExpired()) {
//This is where I am running in trouble.
}
How do I achieve it? The target is to perform OAuth authentication and execute Google Drive API without any manual intervention.
Thank you for the help!
Looks like I found the answer.
I used the OAuth url for the first time access to include the parameter prompt=consent. So this generated the refresh-token that was saved in the file. After that, following addition to code did the trick -
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents(CREDENTIALS_PATH, $client->getAccessToken());
}
After this the token is no longer expiring after an hour.

Google PHP SDK - not getting refresh token

I am trying to get a refresh token for the Google API's, using the PHP SDK. I am authenticating the user with Javascript, retrieving a code, and exchanging it for an access_token server side, but this doesn't grant me an access token. What am I doing wrong? Here is the code I use:
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->addScope('https://www.googleapis.com/auth/plus.me');
$client->addScope('https://www.google.com/m8/feeds');
$client->setRedirectUri('postmessage');
$client->setAccessType('offline');
if (isset($_REQUEST['code'])) {
$client->authenticate($_REQUEST['code']);
if ($client->getAccessToken()) {
$_SESSION['access_token'] = $client->getAccessToken();
$token_data = $client->verifyIdToken()->getAttributes();
$result['data']=$token_data;
$result['access_token']=json_decode($_SESSION['access_token']);
}
}
debug($result); //my own function, var_dumps the content of an array
Here is the result of the array:
$result['access_token'] contains:
access_token: TOKEN
created: 1434380576
expires_in: 3594
id_token: IDTOKEN
token_type:"Bearer"
If I am not mistaken the first access token should also contain the refresh token, what am I doing wrong?
First check the settings in the developer console of Google to see if your RedirectUri is the same and that the API is activated (although if you already got that .json, then I assume it is.
You have to go through the Google Auth Prompt Screen at least 1 time to get a refresh token in your .json, and if your RedirectUri is taking you nowhere, you won't be able to get your refresh token or even the access validated.
You can also try a service account if you're doing small file transactions and don't need a user validation for the process of your script. Good Luck.
The problem was that I had to specify that I want offline access in the authentication process, the client side... The Google API's are horribly documented!!!

Google Analytics API blank screen when querying accounts?

I am novice to Google Analytics Api. I just started working on a small project where I want to pull data from the API and display it on each user’s Dashboard, using one single Google Analytics Account. I tried to follow the tutorial provided by google and made adjustments where required due to update to the library.
I am working on a codeigniter based platform and I was able to create a Google Client Object and also to make use of a refresh token which is saved in the database. I use the refresh token in order to have the data available on the dashboard without having to manually login every time.
The access token is there every time when I am logged in, and I can use it to set the client access token and create a Google Service Analytics object ($service = new Google_Service_Analytics($client);). I am printing the service and I can see the client id, client secret, etc and the access token being passed to it; but other like Google_Service_Analytics_DataGa_Resource Object are empty ( I do not know if they should be like that or not at this particular step ?).
When I am trying to request the user accounts
$accounts = $analytics->management_accounts->listManagementAccounts();,
I get a blank screen and my view is not being rendered.
I could not find such a problem being encountered before, so I am a bit confused why is happening. I do not get any error messages or anything that might point me to the cause of it or the right direction.
Note: I did managed to make it work using the same credentials trough JavaScript, but in this case it is not what I am looking for. I was able to retrieve data, display data in charts,etc using JS. I am new to making posts, so if anything is required from my part in order for you to have a better idea of what is going on, please do let me know.
I would greatly appreciate it I could get any indication to why that might be happening, or anything that would put me on the right path.
Codeigniter controller Class as follows
// Step 1 - Load PHP Client Libraries
require_once APPPATH.'libraries/Google/Client.php';
require_once APPPATH.'libraries/Google/Analytics.php';
class GoogleTest extends CI_Controller {
public function index(){
$this->load->helper(array('url','form'));
$this->load->model('googleapi_model'); //used to get the refresh token
// Step 2 - Start a session to persist credentials
session_start();
// Step 3 - Create and configure a new client object
$client = new Google_Client();
$client->setApplicationName("API Project");
// Insert client id, api key, client secret, project scope and redirect uri
$client->setDeveloperKey("***************");
$client->setClientId('********************');
$client->setClientSecret('******************');
$client->setRedirectUri('****************');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Check if refresh token exists, it is used to login users automatically & it is being generated only once when you login the first time from the created
// google analytics app, this will take precedence to Step 4 or 6 below ;
if(count($this->googleapi_model->getGoogleRefreshToken()) > 0){
$db_refresh_token = $this->googleapi_model->getGoogleRefreshToken();
$client->refreshToken($db_refresh_token[0]->refreshtoken);
$_SESSION['token'] = $client->getAccessToken();
}else{
if ($client->getAccessToken()) {
$token = $client->getAccessToken();
$authObj = json_decode($token);
$refreshToken = $authObj->refresh_token;
if(isset($refreshToken) && $refreshToken != null){
$this->googleapi_model->insertGoogleRefreshToken($refreshToken);
}
}
}
//Step 4 - Handle authorization flow from the server
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 5 - Retrieve and use stored credentials
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Stept 6 - Either prompt the user to login or run the demo
if(!$client->getAccessToken()){
$authUrl = $client->createAuthUrl();
$this->data['auth'] = $authUrl;
}else{ //Create analytics service object
echo 'authenticated';
$analytics = new Google_Service_Analytics($client);
//TILL HERE MY CODE WORKS FINE, NO ERRORS, VIEW BEING RENDERED
$accounts = $analytics ->management_accountSummaries->listManagementAccountSummaries();
// $accounts = $analytics->management_accounts->listManagementAccounts();
echo '<pre>';
print_r($analytics);
echo '</pre>';
}
$this->data['content'] = '/public/dashboard/google_test';
$this->load->view('template/template', $this->data);
}
Make sure you're logged into the google account that API app is in.
And that you have clicked 'connect'.
Then run the script.
Also turn on error reporting (including notices)

Categories