I am using the Google API Client to access Google Analytics. I want to access the data in offline mode, so I need a refresh token. How do I get a refresh_token?
try using the following code:
<?php
require_once 'apiClient.php';
const REDIRECT_URL = 'INSERT YOUR REDIRECT URL HERE';
const CLIENT_ID = 'INSERT YOUR CLIENT ID HERE';
const CLIENT_SECRET = 'INSERT YOUR CLIENT SECRET';
const ANALYTICS_SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
// Build a new client object to work with authorization.
$client = new apiClient();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URL);
$client->setScopes(array(ANALYTICS_SCOPE));
$client->setAccessType('offline');
$auth = $client->authenticate();
if ($client->getAccessToken()) {
$token = $client->getAccessToken();
$authObj = json_decode($token);
$refreshToken = $authObj->refresh_token;
}
?>
For PHP SDK of Google Client v2:
php composer.phar require google/apiclient:^2.0
You can try the PHP code to refresh accessToken as following:
<?php
require_once __DIR__ . '/vendor/autoload.php';
define('CLIENT_SECRET_PATH', __DIR__ . '/client_secret.json');
define('SCOPES', implode(' ', array(
Google_Service_Analytics::ANALYTICS_READONLY)
));
$client = new Google_Client();
$client->setApplicationName('YOUR APPLICATION NAME');
$client->setScopes(SCOPES);
$client->setAuthConfig(CLIENT_SECRET_PATH);
$client->setAccessType('offline');
// Input AccessToken from such as session or database
$accessToken = json_decode('YOUR CURRENT ACEESS TOKEN');
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
// Get RefreshToken as json which can be reused
$refreshToken = json_encode($client->getAccessToken());
}
Offline access issue
In addition, if you want to keep the existing behavior in your server-side applications, you need to set approval_prompt to force, otherwise you may get NULL returned from getRefreshToken(), which Google document doesn't mention:
$client->setApprovalPrompt('force');
Referring Upcoming changes to OAuth 2.0 endpoint
Related
I need to recover user info after javascript google login.
Authentication work fine and i send googleUser.Ka object to my php where there's this code
$api = new Google_Client();
$api->setApplicationName($this->_configCustomer['google']['api']['application_name']);
$api->setClientId($this->_configCustomer['google']['api']['client_id']); // Set Client ID
$api->setClientSecret($this->_configCustomer['google']['api']['client_secret']); //Set client Secret
$api->setAccessType('online'); // Access method
$api->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'));
//$api->setRedirectUri('http://www.infotuts.com/demo/googlelogin/login.php');
$service = new Google_Service_Plus($api);
$oauth2 = new \Google_Service_Oauth2($api);
$api->setAccessToken(json_encode($_POST));
//ADDED AFTER ERROR
if($api->isAccessTokenExpired()) {
$api->authenticate();
$NewAccessToken = json_decode($api->getAccessToken());
$api->refreshToken($NewAccessToken->refresh_token);
}
//END ADDED AFTER FIRST ERROR
//$api->authenticate($_POST['access_token']);
if ($api->getAccessToken()) {
$data = $service->people->get('me');
$user_data = $oauth2->userinfo->get();
var_dump($user_data);
die();
}
this code generate the error:
The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.
i added code indicate from comment follow this link
OAuth 2.0 access token has expired, and a refresh token is not available
but in the last version of php authenticate method require $code parameter. What is it?
Thanks
i solved in this way
$api = new Google_Client();
$api->setApplicationName($this->_configCustomer['google']['api']['application_name']);
$api->setClientId($this->_configCustomer['google']['api']['client_id']); // Set Client ID
$api->setClientSecret($this->_configCustomer['google']['api']['client_secret']); //Set client Secret
$api->setAccessType('online'); // Access method
$api->setScopes(array('https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.me', 'https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'));
$api->setRedirectUri('postmessage');
$result = $api->verifyIdToken($_POST['id_token']);
i send id_token, obtained from the ajax login, and recovery user info using verifyIdToken method of client library
I am still new to Twilio. I am writing a PHP script which will connect to Twilio and parse some information about calls. I am using the code from this page:
https://www.twilio.com/docs/api/rest/call
Here is my code:
require_once '../twilio-library/Services/Twilio.php';
// Twilio REST API version
$version = '2010-04-01';
// Set our AccountSid and AuthToken
$sid = 'abc132xxxxx';
$token = 'xxxxeeffv';
// Instantiate a new Twilio Rest Client
$client = new Services_Twilio($sid, $token, $version);
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls as $call) {
echo "->".$call->Sid."<- <br/>";
}
The browser just outputs many blanks. No Sid values. What am I doing wrong?
Twilio Developer Evangelist here.
Try doing the following to get call information.
<?php
require_once '../twilio-library/Services/Twilio.php';
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = 'abc132xxxxx';
$token = 'xxxxeeffv';
$client = new Services_Twilio($sid, $token);
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls as $call) {
echo $call->sid;
}
Notice that if you're using the latest version of the library, you don't need to specify a version on your request. Double check that the path ../twilio-library/Services/Twilio.php is correct for you though.
If you're only testing, you could move the file Twilio.php to the same directory where your code is and just import Twilio.php on it.
If you then decide to filter the logs by date, here's how you would do it.
// Loop over the list of calls and echo a property for each one
foreach ($client->account->calls->getIterator(0, 50, array(
"Status" => "completed",
"StartTime>" => "2015-03-01",
"StartTime<" => "2015-05-10"
)) as $call
) {
echo $call->sid;
}
Let me know how it goes.
I can't get an offline access token with this code...
Why ?
$client = new Google_Client();
$client->setApplicationName('MyAppName');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$client->setClientId('MyCientID');
$client->setClientSecret('MyClientSecret');
$client->setRedirectUri('http://mydomain.com/googlecallback');
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setDeveloperKey('MyDeveloperKey');
$plus = new Google_Service_Plus($client);
header('Location: '.$client->createAuthUrl());
This is redirect to the google login page, which ask only for an 1hour access token...
I'm lost in the dark...
Thanks a lot!
EDIT :
here is my login page code :
$client = new Google_Client();
$client->setClientId('qvdsfvqdsf');
$client->setClientSecret('qsdfvqsdf');
$client->setRedirectUri('?a=callback');
$client->setDeveloperKey('qdcQSDCQSD');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new Google_Service_Plus($client);
if($_GET['a'] == 'authorize'){
header('Location: '.$client->createAuthUrl());
}
elseif($_GET['a'] == 'callback' && isset($_GET['code']) && !isset($_GET['error'])){
$client->authenticate($_GET['code']);
if($client->getAccessToken()){
STORE ACCESS TOKEN
}
}
And my API usage :
$client = new Google_Client();
$client->setClientId('qsdfsqd');
$client->setClientSecret('qsdfqsd');
$client->setRedirectUri('qdfq');
$client->setDeveloperKey('sdfvsdf');
$client->setApprovalPrompt('auto');
$client->setAccessType('offline');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new Google_Service_Plus($client);
$client->setAccessToken('STORED ACCESS TOKEN');
$activities = $plus->activities->listActivities('me', 'public', array('maxResults'=>10));
What I am doing wrong ?
You need to have the "http://mydomain.com/googlecallback" URL set as a redirect URI on the application settings page.
The $client->createAuthUrl() method creates the URL to the authentication page. After going to that page and authorizing the application, Google will redirect you back to /googlecallback with a query string param called 'code', which you should pass to the authenticate() method of the client. Only then you'll have access to the token.
Something like this (assuming this is on /googlecallback):
$client = new Google_Client();
$client->setApplicationName('MyAppName');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$client->setClientId('MyCientID');
$client->setClientSecret('MyClientSecret');
$client->setRedirectUri('http://mydomain.com/googlecallback');
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setDeveloperKey('MyDeveloperKey');
if (empty($_GET['code'])) {
header('Location: '.$client->createAuthUrl());
} else {
$client->authenticate($_GET['code']);
$access_token = $client->getAccessToken();
// save the token somewhere so you can use later
// without having to go to the auth page again
}
Finally got the answer :
Using $client->setApprovalPrompt('force'); was blocking the normal Google token refresh process, while $client->setApprovalPrompt('auto'); do it like a charm.
Thanks.
If a user has previously authenticated against the ClientID without requesting offline mode, and you then request offline mode, it wont give you the refresh token.
The user needs to de-authorize themselves from app and then re-authorize once the app will request offline mode.
I am attempting to retrieve the data from our content experiments from google analytics...
I am using the following code, my creds are good, and have been censored for this post...
<?php
require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
session_start();
$client = new Google_Client();
$client->setApplicationName('Hello Analytics API Sample');
// Visit https://cloud.google.com/console to generate your
// client id, client secret, and to register your redirect uri.
$client->setDeveloperKey('xxxxx');
$service = new Google_Service_Analytics($client);
try {
$results = $service->management_experiments->listManagementExperiments('xxxx', 'xxxx', 'xxxx');
} catch (apiServiceException $e) {
print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
echo '<pre>';
print_r($results);
echo '</pre>';
I am using the following example ....
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#list
Any ideas on why I am getting a 401 unauthorized? That a login is required?
The problem is that you haven't Authorized access to your data yet. Since you say its only your own data you want to access i sugest you look into a service account. By setting up a service account in Google apis console it will allow you to access your own data with out needing to login and autenticate the code all the time.
Check the following link. Read though Before you begin make sure you do all that.
https://developers.google.com/analytics/devguides/config/mgmt/v3/mgmtExperimentsGuide#service
Register your application in the Google Developers Console
Authorize access to Google Analytics data.
Create an Analytics service object
You have skiped the first two steps and gone directly to step 3 creating the service object. Once you have done step 1 you can use the following code for step 2.
Here is an example of how to use a service account in php ServiceAccount
That sample project is for the PredictionService not the google analytics service. You need to edit it slightly.
require_once '../../src/Google/Client.php';
require_once '../../src/Google/Service/Analytics.php';
// Set your client id, service account name, and the path to your private key.
// For more information about obtaining these keys, visit:
// https://developers.google.com/console/help/#service_accounts
const CLIENT_ID = 'INSERT_YOUR_CLIENT_ID';
const SERVICE_ACCOUNT_NAME = 'INSERT_YOUR_SERVICE_ACCOUNT_NAME';
// Make sure you keep your key.p12 file in a secure location, and isn't
// readable by others.
const KEY_FILE = '/super/secret/path/to/key.p12';
$client = new Google_Client();
$client->setApplicationName("Google Analytics Sample");
// Load the key in PKCS 12 format (you need to download this from the
// Google API Console when the service account was created.
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME(Email),
array('https://www.googleapis.com/auth/analytics.readonly'),
file_get_contents(KEY_FILE))
);
$client->setClientId(CLIENT_ID);
$service = new Google_Service_Analytics($client);
Now you have $service that you can use with the rest of your calls. Note: I didnt have time to test that code let me know if it doesnt work and i will give you a hand in fixing it.
I'm trying to get Youtube username via google plus api. I use php Services from Plus ang YT api and I'm using symfony 2. Obtaining access token works ok, and i'm not going to put it here.
There is also no problem with google plus service, after authorization i'm getting all the information that i need. In YT case, i'm getting error :
insufficientPermissions error
So i check my access token scope in here:
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=ACCESS_TOKEN
and scope of my Access token is only for Google Plus, i'm not able to force the google Api php clinet to make the YT scope aviable too.
Any ideas?
Here is my code :
require_once '../src/google_api_php_client/src/Google_Client.php';
require_once '../src/google_api_php_client/src/contrib/Google_PlusService.php';
require_once '../src/google_api_php_client/src/contrib/Google_YouTubeService.php';
$client = new Google_Client();
$client->setScopes('https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/plus');
$youtube = new Google_YouTubeService($client);
if(!empty($allR['code'])){
$client->setClientId('clientIDxxx');
$client->setClientSecret('SecretXXX');
$client->setRedirectUri('postmessage');
$client->authenticate($allR['code']);
$token = json_decode($client->getAccessToken());
}
First of all, make sure you enabled YouTube Data API v3 rom your devconsole.
Then instead of setting scopes, try setting client id and secret from devconsole.
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// YouTube object used to make all Data API requests.
$youtube = new Google_YoutubeService($client);
$plus = new $youtube = new Google_PlusService($client);