Saving Google Drive access Tokens for future calls - php

I have a PHP set of scripts using Google's Drive API and PHP examples, but I do not seem to be able to cache authorization requests...
<?php
echo 'This is a new request... setting parameters';
$drive_fileid=$_GET['drive_fileid'];
$drive_userid=$_GET['drive_userid'];
$drive_permission=$_GET['drive_permission'];
$_SESSION['drive_fileid']=$drive_fileid;
$_SESSION['drive_userid']=$drive_userid;
$_SESSION['drive_permission']=$drive_permission;
if($_SESSION['drive_fileid']==''){
echo 'Invalid drive file id. Aborting...';
exit;
} else $drive_fileid=$_SESSION['drive_fileid'];
if($_SESSION['drive_userid']==''){
echo 'Invalid drive user id. Aborting...';
exit;
} else $drive_userid=$_SESSION['drive_userid'];
if($_SESSION['drive_permission']==''){
echo 'Invalid drive permission. Aborting...';
exit;
} else $drive_permission=$_SESSION['drive_permission'];
// Now, if we have been through all this before, lets grab stored tokens...
// These never seem to work.
$getFormSQL="SELECT * from `users` where email='".$email."'";
$getFormData=mysql_query($getFormSQL) or die("Died trying to get auth token from the database with this user");
$formRow = mysql_fetch_array($getFormData);
$oauthToken=$formRow['driveoauth'];
$oauthAccessToken=$formRow['driveoauthaccess'];
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_DriveService.php';
$client = new Google_Client();
$client->setClientId('myappid.apps.googleusercontent.com');
$client->setClientSecret('myclientsecret');
$client->setRedirectUri('https://www.mywebsite.net/driveapi/oauth2callback');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
// Since we have no token, we redirect the user to the Google Auth page...
if($oauthToken=='')header( 'Location: '.$authUrl ) ;
$authCode = trim($oauthToken);
// Try authenticate access token
try {
$client->setAccessToken($oauthAccessToken);
$authed=1;
} catch (Exception $e) {
echo '<P>Couldnt authenticate access token';
$authed=0;
}
// If that didn't work, lets generate a new one
if($authed==0){
try {
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
} catch (Exception $e) {
header( 'Location: '.$authUrl ) ;
}
echo 'Got an access token: '.$accessToken;
// Save access token
$accessData=json_decode($accessToken,true);
echo '<P>Extracted and saved: '.$accessData['access_token'].'<P>';
$updateQuery ="UPDATE `users` ";
$updateQuery.=" set ";
$updateQuery.="driveoauthaccess='".$accessData['access_token']."'";
$updateQuery.=" where email='".$email."'";
mysql_query($updateQuery) or die("Unable to update database! ".mysql_error());
}
echo '<P><B>Existing permissions on the file/folder:</B><BR>';
$existingpermissions= $service->permissions->listPermissions($drive_fileid);
$existingpermissionarray=$existingpermissions['items'];
?>
Why am I not able to reuse the tokens I generate?

Related

stevenmaguire keycloak plugin returns $token variable how to use this token to in yii2 project for single sign on

index.php() //plugin
`if (!isset($_GET['code']) || !isset($_SESSION['oauth2state'])) {
// If we don't have an authorization code then get one
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
exit;
//Check given state against previously stored one to mitigate CSRF attack
}
elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state, make sure HTTP sessions are enabled.');
}
else {
// Try to get an access token (using the authorization coe grant)
try {
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// $token = $provider->getAccessToken('refresh_token', ['refresh_token' => $token->getRefreshToken()]);
// echo $token->getRefreshToken();
// print_r($token);
} catch (Exception $e) {
// echo 'tttttttttttttttttt';
exit('Failed to get access token: ' . $e->getMessage());
}
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the user's details
$user = $provider->getResourceOwner($token);
// print_r($user);
// Use these details to create a new profile
// printf('Hello %s!', $user->getName());
} catch (Exception $e) {
exit('Failed to get resource owner: ' . $e->getMessage());
}
// Use this to interact with an API on the users behalf
// echo $token->getToken();
}`
using this plugins finally i have getting token that stored user information but problem in where i am adding this tokent in my yii2 project for authentication of user and how the plugins skip the login page of our yii2 projects and directly enter in website without showing login page of our project....

The session of the Facebook Log Account of my website still exists

I use Facebook SDK 5 with an index.php and a profile.php(only for presentation the data). I use them for log in in my website with facebook account, but after the first time that someone logs in from my computer to his fb account I don't have the option to log in again. I automatically log in with his account. How can I delete the "past user data"? I've tried deleting the session but nothing happened.
session_start();
unset($_SESSION['facebook_access_token']);
unset($accesstoken);
if (isset($accesstoken)){
echo hi;
try
{
$fbuid = $fb->getUser();
$me = $fb->api('/me');
}
catch(FacebookApiException $e){}
}
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\facebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user to the profile page if it has "code" GET variable
if (isset($_GET['code'])) {
echo hi3;
header('Location: profile.php');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$requestPicture = $fb->get('/me/picture?redirect=false&height=200'); //getting user picture
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphUser();
$fbid = $profile->getProperty('id'); // To Get Facebook ID
$fbfullname = $profile->getProperty('name'); // To Get Facebook full name
$fbemail = $profile->getProperty('email'); // To Get Facebook email
$fbpic = "<img src='".$picture['url']."' class='img-rounded'/>";
# save the user nformation in session variable
$_SESSION['fb_id'] = $fbid.'</br>';
$_SESSION['fb_name'] = $fbfullname.'</br>';
$_SESSION['fb_email'] = $fbemail.'</br>';
$_SESSION['fb_pic'] = $fbpic.'</br>';
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
} else {
// replace your website URL same as added in the developers.Facebook.com/apps e.g. if you used http instead of https and you used
$loginUrl = $helper->getLoginUrl('http://newpage.photoclub-tey.com.cy/please/', $permissions);
echo 'Log in with Facebook!';
}
unset($_SESSION);
unset($_SESSION['facebook_access_token']);
$accessToken->revokeToken();
session_destroy();
?>

Facebook login PHP: URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings

I'm using Parse Server to log in with Facebook on my website, but of course, I have all the code for Facebook PHP SDK to handle login, and it was working fine until a few days ago.
'
This is the error I get while trying to login:
URL Blocked: This redirect failed because the redirect URI is not
whitelisted in the app’s Client OAuth Settings.
Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.
My Facebook Login settings:
This is my fb-callback.php script:
<?php
require_once 'fb-autoload.php';
include 'Configs.php';
// include 'fbconfig.php';
$fb = new Facebook\Facebook([
'app_id' => $_GLOBALS["FACEBOOK_APP_ID"],
'app_secret' => $_GLOBALS["FACEBOOK_APP_SECRET"],
'default_graph_version' => 'v2.3',
]);
$helper = $fb->getRedirectLoginHelper();
if (isset($_GET['state'])) {
$helper->getPersistentDataHandler()->set('state', $_GET['state']);
}
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
// echo '<h3>Access Token:</h3>';
// var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
// echo '<h3>METADATA:</h3>';
// var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($_GLOBALS["FACEBOOK_APP_ID"]); // Replace {app-id} with your app id
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
exit;
}
//echo '<h3>Long-lived</h3>';
//var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
// header('Location: login.php');
// CHECK IF SESSION IS OK, GET GRAPH OBJECT AND GO BACK TO login.php
if (isset($_SESSION)) {
$response = $fb->get('/me?fields=id,name', $accessToken);
$node = $response->getGraphNode();
// Get ID, Name and Email of Facebook user
$fbid = $node->getField('id'); // To Get Facebook ID
$fbfullname = $node->getField('name'); // To Get Facebook full name
$femail = $node->getField('email'); // To Get Facebook email ID
// $token = $session->getToken(); // Get Access Token
$token = $_SESSION['fb_access_token'];
// ---- Session Variables -----
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
$_SESSION['TOKEN'] = $token;
// ---- GO TO fb-login.php ----
header("Location: fb-login-confirm.php");
} else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
I don't know if I have to edit/add something else, as I said above, my FB login was working smoothly until a few days ago.
The issue was pretty simple, my URL was missing www in the Valid OAuth redirect URIs field:
https://www.example.com/woopy/fb-callback.php

Facebook PHP SDK v5 OAuth Login error when posting to a page as a page

I'm using the code below on my website to try and post a message on a Facebook page that I manage. I'm using the Facebook PHP SDK v5. Whenever I run the code I get directed to Facebook with an error window that says,
"URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs."
However, if I go to the Graph API Explorer and request a User Access Token, then hard code the access token into the script it works just fine. I added Facebook Login to the products tab on my app setting, since that's the only place you can add in the "Valid OAuth redirect URIs". I'm pretty sure the problem is coming from the "Valid OAuth redirect URIs" field in the setting area. I'm not sure what to put in that field or if that is even the problem at all. Currently, I've tried putting the following in the "Valid OAuth redirect URIs" field with no luck;
just my domain i.e. www.my-domain.com
the full path the the calling script i.e. www.my-domain.com/calling-script.php
the full path to a blank page on my server i.e. www.my-domain.com/blank.html
None are working. This is my first go at trying to use the Facebook PHP SDK so I'm sure I'm doing it all wrong... Wondering if anyone is able to give me some guidance on this?
UPDATE:
See answer posted below with fix. My original post was not very clear regarding my intentions. My goal was to successfully post a message to a Facebook Page as the Page, not as an individual user. Hope this helps someone down the road.
Here are my app settings:
Here is the PHP script I am using:
session_start();
$path = "path-to-Facebook-autoloader-on-my-server";
include_once $path;
$fb = new Facebook\Facebook([
'app_id' => 'app-id-from-app-settings',
'app_secret' => 'app-secret-number-from-app-settings',
'default_graph_version' => 'v2.7',
]);
/////////////////////////////////////////////////////////////////////////
// If I uncomment the below line the script works fine, but the token expires often
// and I do not want to have to keep updating it
// $_SESSION['facebook_access_token'] = "access-token-obtained-from-Graph-API-Explorer";
/////////////////////////////////////////////////////////////////////////
$helper = $fb->getCanvasHelper();
$permissions = ['email', 'publish_actions']; // optional
try {
if(isset($_SESSION['facebook_access_token'])){
$accessToken = $_SESSION['facebook_access_token'];
}else{
$accessToken = $helper->getAccessToken();
}
}catch(Facebook\Exceptions\FacebookResponseException $e){
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}catch(Facebook\Exceptions\FacebookSDKException $e){
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
if(isset($accessToken)){
if(isset($_SESSION['facebook_access_token'])){
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}else{
$_SESSION['facebook_access_token'] = (string)$accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string)$longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try{
$request = $fb->get('/me');
}catch(Facebook\Exceptions\FacebookResponseException $e){
// When Graph returns an error
if($e->getCode() == 190){
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
}catch(Facebook\Exceptions\FacebookSDKException $e){
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
try{
// message must come from the user-end
$data = ['message' => 'test message...'];
$request = $fb->post('/me/feed', $data);
$response = $request->getGraphNode();
}catch(Facebook\Exceptions\FacebookResponseException $e){
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
}catch(Facebook\Exceptions\FacebookSDKException $e){
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
echo $response['id'];
}else{
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/austintestingapp/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
i checked your script. all looks fine except one thing. can u try after changing
$helper = $fb->getCanvasHelper();
to
$helper = $fb->getRedirectLoginHelper();
and see what error it throws if any?
also u can refer to the shared gist. do let us know your error.
https://gist.github.com/gunnrryy/c2c828fc2a77124cc1bed57af5e216df
So I ended up figuring it out. I played around with the script I originally posted and finally got it to work...sort of. No matter how I ran the script messages were always being sent to the page I manage as a notification. They would not show up on the wall. The end goal I was looking for was to post on to a page that I manage as the page, not as myself. Just in case anyone else comes across this the code below works perfect. Also, it does not require you to submit privileges for approval with Facebook.
The answer to my original question in regards to the "Valid OAuth redirect URIs" field. I ended up putting the path to the calling script in that field and it worked fine.
session_start();
$path = "server-path-to-Facebook-autoloader.php";
$permissions = ['manage_pages', 'publish_pages'];
$callback = "full-path-to-the-calling-script(this-script).php";
include_once $path;
$fb = new Facebook\Facebook([
'app_id' => 'app-id-number-here',
'app_secret' => 'app-secret-here',
'default_graph_version' => 'v2.7',
]);
$helper = $fb->getRedirectLoginHelper();
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$accessToken = $helper->getAccessToken();
}
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$res['myresponse'] = 'Error: Graph returned a session error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$res['myresponse'] = 'Error: Facebook SDK returned a session error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
}
if (isset($accessToken)) {
if (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
// getting short-lived access token
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// getting basic info about user
try {
$profile_request = $fb->get('/me');
$profile = $profile_request->getGraphNode();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
$res['myresponse'] = 'Error: Graph returned a profile request error: ' . $e->getMessage();
echo $res['myresponse'];
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
$res['myresponse'] = 'Error: Facebook SDK returned a profile request error: ' . $e->getMessage();
echo $res['myresponse'];
exit;
}
// post on behalf of page
$pages = $fb->get('/me/accounts');
$pages = $pages->getGraphEdge()->asArray();
foreach ($pages as $key) {
if ($key['name'] == 'name-of-page-to-post-to') {
$post = $fb->post('/' . $key['id'] . '/feed', array('message' => 'this is an automated test message from Affordable HomeCare...'), $key['access_token']);
$post = $post->getGraphNode()->asArray();
if($post['id'] <> ''){
$res['myresponse'] = "Successfully Posted to Facebook";
}else{
$res['myresponse'] = "Error: Unable to verify post ID";
}
echo $res['myresponse'];
}
}
} else {
$loginUrl = $helper->getLoginUrl($callback, $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}

Google Analytics PHP API - Error (403) Access Not Configured

I have been Googling this for going on hours now. I have followed the Hello Analytics tutorial.
The application runs fine until the user has granted permission from the Google 'consent screen' at which point i receive the following error:
There wan a general error : Error calling GET My url
(403) Access Not Configured. Please use Google Developers Console to
activate the API for your project.
I have checked in the developer console and Analytics API is enabled and, after reading other posts on this, have added Google+ and Drive access.
NOTE: I am running this application locally and redirecting the redirecting back to 127.0.0.1.
I have added my code below for reference although I think the issue is to do with my google console account and / or running this application locally.
Appreciate any help with this guys. Please let me know if any further information is required.
==================================================================================
// --------------------- Google libraries
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_AnalyticsService.php';
session_start();
// --------------------- Application credentials
$client = new Google_Client();
$client->setApplicationName('Interim Testing Tool');
$client->setClientId('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxxxxxxxxxxxxxxxxxxxx');
$client->setRedirectUri('http://127.0.0.1');
$client->setDeveloperKey('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
$client->setScopes(array('https://www.googleapis.com/auth/analytics.readonly'));
// Returns objects from the Analytics Service instead of associative arrays.
$client->setUseObjects(true);
// --------------------- Client access checks
// Handle authorization flow from the server
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));
}
// Retrieve and use stored credentials if set
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken()) {
// CLient not logged in create a connect button
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
$analytics = new Google_AnalyticsService($client);
runMainDemo($analytics);
}
//-------------------------------------------------------------- Run main demo
function runMainDemo($analytics) {
try {
// Get the user's first view (profile) ID.
$profileId = getFirstProfileId($analytics);
if (isset($profileId)) {
// Query the Core Reporting API.
$results = getResults($analytics, $profileId);
// Output the results.
printResults($results);
}
} catch (apiServiceException $e) {
// Error from the API.
print 'There was an API error : ' . $e->getCode() . ' : ' . $e->getMessage();
} catch (Exception $e) {
print 'There wan a general error : ' . $e->getMessage();
}
}
// ------------------------------------------------------------------ Get first profile id
function getFirstprofileId($analytics) {
$accounts = $analytics->management_accounts->listManagementAccounts();
if (count($accounts->getItems()) > 0) {
$items = $accounts->getItems();
$firstAccountId = $items[0]->getId();
$webproperties = $analytics->management_webproperties->listManagementWebproperties($firstAccountId);
if (count($webproperties->getItems()) > 0) {
$items = $webproperties->getItems();
$firstWebpropertyId = $items[0]->getId();
$profiles = $analytics->management_profiles->listManagementProfiles($firstAccountId, $firstWebpropertyId);
if (count($profiles->getItems()) > 0) {
$items = $profiles->getItems();
return $items[0]->getId();
} else {
throw new Exception('No views (profiles) found for this user.');
}
} else {
throw new Exception('No webproperties found for this user.');
}
} else {
throw new Exception('No accounts found for this user.');
}
}

Categories