Get User Organizations with Google Plus API - php

I am trying to get the organizations from a user with Google+ API or Google+ Domains API. I am following the steps on the official documentation and the logic I'm using is this one:
<?php session_start();
require_once 'vendor/autoload.php'; //INCLUDE PHP CLIENT LIBRARY
$scopes = array(
"https://www.googleapis.com/auth/plus.profiles.read",
"https://www.googleapis.com/auth/plus.me"
);
// Create client object and set its configuraitons
$client = new Google_Client();
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/');
$client->setAuthConfig("creds.json");
$client->addScope($scopes);
if( isset($_SESSION["access_token"]) ) {
$client->setAccessToken($_SESSION["access_token"]);
$service = new Google_Service_PlusDomains($client);
$me = $service->people->get('me');
var_dump($me);
echo "<br><br>*********************************************<br><br>";
$orgs = $me->getOrganizations(); // (THIS IS EMPTY!!!) ????
var_dump($orgs);
} else {
if( !isset($_GET["code"]) ){
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
} else {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
}
?>
This perfectly works for G-Suite account I had before the transition of Google+ to Google+ Domains. When I use this same script on a newer G Suite account, it won't work. I have tried with $service = new Google_Service_Plus($client); and the result is the same thing. Any idea why it won't work with newer G Suite accounts? Is anybody else having the same issue?

Ok. I found the root cause of my problem. It happens that the User Resource and the People Resource are two different resources. Both of them have the "organization" attribute but the information of the user resource will not appear in your Google Plus profile and in order to populate the "organization" attribute of the people resource, the user is required to manually update the information from the "about me" page in Google Plus. At the moment, seems there is no way to programmatically update the information of the People Resource but users have to do it manually.

Related

Using PHP google client to get YouTube playlist (server-side oauth)

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)

Google oauth authorization code expired?

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.

PHP - Google Sheets API OAuth2- can't get token

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

PHP Google People API - Simple email request failing

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!

Google Analytics Data Export API V3

I am trying to get to grips with interacting with the GA API v3 using php. Being quite new to php, I am struggling somewhat. Does anyone here have any experience with using the api with php (v3)?
http://code.google.com/intl/nl/apis/analytics/docs/index.html
Google does supply a small sample script but it's effectively useless (with my limited skills) as it returns an api key but doesn't tell you where it needs to go or why you need it.
If anyone has any knowledge I would be very grateful if you could show me how.
You need to make sure you register you API with Google from their API console. Make sure you turn on Google Analytics, and create a project.
After make sure you download the full api from Google Code.
You want to go into simple.php located in the Analytics folder (under examples) and uncomment lines 11-14, and replace with information from Google API Console:
$client->setClientId('xxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxxx');
$client->setRedirectUri('http://www.xxxx.com/xxx/examples/analytics/simple.php');
$client->setDeveloperKey('xxxxxxxxxxx');
This will let you connect and you will see the basic data. For more details and a great tutorial you can see it here.
Your total page should look like this:
<?php
require_once '../../src/apiClient.php';
require_once '../../src/contrib/apiAnalyticsService.php';
session_start();
$client = new apiClient();
$client->setApplicationName("Google Analytics PHP Starter Application");
// Visit https://code.google.com/apis/console?api=analytics to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('addyourshere');
$client->setClientSecret('addyourshere');
$client->setRedirectUri('addyourshere');
$client->setDeveloperKey('addyourshere');
$service = new apiAnalyticsService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
$props = $service->management_webproperties->listManagementWebproperties("~all");
print "<h1>Web Properties</h1><pre>" . print_r($props, true) . "</pre>";
$accounts = $service->management_accounts->listManagementAccounts();
print "<h1>Accounts</h1><pre>" . print_r($accounts, true) . "</pre>";
$segments = $service->management_segments->listManagementSegments();
print "<h1>Segments</h1><pre>" . print_r($segments, true) . "</pre>";
$goals = $service->management_goals->listManagementGoals("~all", "~all", "~all");
print "<h1>Segments</h1><pre>" . print_r($goals, true) . "</pre>";
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}

Categories