I am trying to use Google's OAuth2 API. In their generic documentation, they mention a call called UserInfo: http://code.google.com/apis/accounts/docs/OAuth2Login.html#userinfocall , which would allow me to retrieve user ids, email, name and other basic stuff.
However I cannot find it in their PHP client library: https://code.google.com/p/google-api-php-client/
Where is it?
The Google OAuth2 API has changed - here is how you fetch user information nowadays:
<?php
require_once('google-api-php-client-1.1.7/src/Google/autoload.php');
const TITLE = 'My amazing app';
const REDIRECT = 'https://example.com/myapp/';
session_start();
$client = new Google_Client();
$client->setApplicationName(TITLE);
$client->setClientId('REPLACE_ME.apps.googleusercontent.com');
$client->setClientSecret('REPLACE_ME');
$client->setRedirectUri(REDIRECT);
$client->setScopes(array(Google_Service_Plus::PLUS_ME));
$plus = new Google_Service_Plus($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
error_log('The session state did not match.');
exit(1);
}
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . REDIRECT);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
try {
$me = $plus->people->get('me');
$body = '<PRE>' . print_r($me, TRUE) . '</PRE>';
} catch (Google_Exception $e) {
error_log($e);
$body = htmlspecialchars($e->getMessage());
}
# the access token may have been updated lazily
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$body = sprintf('<P>Login</P>',
$client->createAuthUrl());
}
?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE><?= TITLE ?></TITLE>
</HEAD>
<BODY>
<?= $body ?>
<P>Logout</P>
</BODY>
</HTML>
Do not forget to -
Get web client id and secret at Google API console
Authorize the https://example.com/myapp/ at the same place
You can find official examples at Youtube GitHub.
The PHP client was updated: https://code.google.com/p/google-api-php-client/issues/detail?id=43
I have posted a solution that works for me, a patch to the Google PHP client library to retrieve UserInfo, in this similar question: How to identify a Google OAuth2 user?
Related
This question already has answers here:
How to obtain a feed of comments entered through the 'chat' box during a YouTube live broadcast?
(3 answers)
Closed 6 years ago.
Since this is a question about the new YouTube API that has just been released it is not a duplicate.
I am trying to fetch the chat messages from the YouTube API 3. I have tried everything I can and I am stuck.
I need the liveChatId to be able to fetch them but I don't know how to retrieve that value. The API says that you get it from liveBroadcast snippet.liveChatId, but with the code I've attached in this post there is no value in the liveChatId field. It is just empty. How do I properly retrieve the liveChatId?
<?php
session_start();
// Call set_include_path() as needed to point to your client library.
require_once 'Google/autoload.php';
require_once 'Google/Client.php';
require_once 'Google/Service/YouTube.php';
$OAUTH2_CLIENT_ID = 'MY-CLIENT-ID';
$OAUTH2_CLIENT_SECRET = 'MY-CLIENT-SECRET';
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'],
FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
// Define an object that will be used to make all API requests.
$youtube = new Google_Service_YouTube($client);
$_SESSION['state'] = $_GET['state'];
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
// Check to ensure that the access token was successfully acquired.
if ($client->getAccessToken()) {
try {
// Execute an API request that lists broadcasts owned by the user who
// authorized the request.
$broadcastsResponse = $youtube->liveBroadcasts->listLiveBroadcasts(
'id,snippet',
array(
'mine' => 'true',
));
var_dump($broadcastsResponse['items']);
$htmlBody .= "<h3>Live Broadcasts</h3><ul>";
foreach ($broadcastsResponse['items'] as $broadcastItem) {
$htmlBody .= $broadcastItem['snippet']['title'] ."<br />Chat ID: ". $broadcastItem['liveChatId'] ."<br />ID: ". $broadcastItem['id'];
}
$htmlBody .= '</ul>';
} catch (Google_Service_Exception $e) {
$htmlBody .= sprintf('<p>A service error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$htmlBody .= sprintf('<p>An client error occurred: <code>%s</code></p>',
htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
// If the user hasn't authorized the app, initiate the OAuth flow
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$htmlBody = <<<END
<h3>Authorization Required</h3>
<p>You need to authorize access before proceeding.<p>
END;
}
?>
<!doctype html>
<html>
<head>
<title>My Live Streams</title>
</head>
<body>
<?=$htmlBody?>
</body>
</html>
Where am I lost?
Your comment has exposed the problem. YouTube currently doesn't support mixing live calls with "Stream Now" and creating Events via the API. Complete live events using either one flow or the other, not interchanging both.
I am trying to retrieve all my contacts using Google Contact API. For this I used Oauth2.0 authentication and Google Contact API for PHP.
But i am getting this error:
"Fatal error: Class 'Google_Http_Request' not found in"
could not get the reason why. I even used Google_HttpRequest but error remains the same but this time it is for "Google_HttpRequest".
Code used is as follows, can some one help because for this this there no help is available on internet
<?php
//require_once 'C:/xampp/htdocs/google-api-php-client-master/src/Google/Client.php';
require_once 'C:/xampp/htdocs/google-api-php-client-master/vendor/autoload.php';// or wherever autoload.php is located
session_start();
//Declare your Google Client ID, Google Client secret and Google redirect uri in php variables
$google_client_id = 'xxx-yyy.apps.googleusercontent.com';
$google_client_secret = 'xxxx';
$google_redirect_uri = 'https://localhost:4433/xxx.php';
$client = new Google_Client();
$client -> setApplicationName('My application name');
$client -> setClientid($google_client_id);
$client -> setClientSecret($google_client_secret);
$client -> setRedirectUri($google_redirect_uri);
$client -> setAccessType('online');
$client->setApplicationName('Google Contacts PHP Sample');
$client->setScopes("http://www.google.com/m8/feeds/");
///if (isset($_GET['code'])) {
/// $client->authenticate($_GET['code']);
/// $auth_code = $_GET["code"];
/// $_SESSION['google_code'] = $auth_code;
/// header('Location: ' . $google_redirect_uri);
///}
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));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
//$req = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/default/full", 'GET', null, null);
$req = new Google_Http_Request("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
// The contacts api only returns XML responses.
$response = json_encode(simplexml_load_string($val->getResponseBody()));
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
$auth = $client->createAuthUrl();
}
if (isset($auth)) {
print "<a class=login href='$auth'>Connect Me!</a>";
} else {
print "<a class=logout href='?logout'>Logout</a>";
}
You are trying to mix things that cant be mixed.
The current Google php client library which you are using only supports discovery service APIs. Which are the new APIs that return Json.
The google contacts API is an older Gdata api which returns XML. the two do not speak the same language. I haven't tried it but the old GData client library can be found here.
I'm want to get google+ posts via PHP, but google requires my login via browser.
It's possible provide the account's authentication via PHP, allowing me to get the posts without login every time I want to get the posts?
The code is:
<?php
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console?api=plus to generate your
// client id, client secret, and to register your redirect uri.
$client->setClientId('clientid');
$client->setClientSecret('clientsecret');
$client->setRedirectUri('http://localhost/OLA/google+/simple.php/b.html');
$client->setDeveloperKey('apikey');
$plus = new Google_PlusService($client);
if (isset($_GET['logout'])) {
unset($_SESSION['token']);
}
if (isset($_GET['code'])) { // login stuff <-------
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die("The session state did not match.");
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
//$me = $plus->people->get('me');
//print "Your Profile: <pre>" . print_r($me, true) . "</pre>";
$params = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $params);
//print "Your Activities: <pre>" . print_r($activities, true) . "</pre>";
$params = array(
'orderBy' => 'recent',
'maxResults' => '20'//20
);
$q = "tag";
$results = $plus->activities->search($q, $params);
//code ....
// The access token may have been updated lazily.
$_SESSION['token'] = $client->getAccessToken();
} else {
// This is the part that logs me in via browser <------
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
Yep, just call as you would and use the simple API access key - you can retrieve public information, but you will have to supply to long numeric ID for the user you're retrieving posts for rather than using the string 'me'. Take a look at the latest version of the library as well: https://github.com/google/google-api-php-client as well. You need to setup your client as you were doing, with an API key from a project which has the Google+ enabled on https://developers.google.com/console
$client = new Google_Client();
$client->setApplicationName("Post Fetcher");
$client->setDeveloperKey('PUT_YOUR_API_KEY_HERE_OR_IT_WONT_WORK');
$plus = new Google_Service_Plus($client);
$activities = $this->plus->activities
->listActivities("118051310819094153327", "public");
Working on Sign in with Google, using PHP Lib v2, Oauth 2.0.
After long time spending on it finally I configured, it worked once fine but after that it is not working. On the clicking of sign in link, it will take user for authentication to Google. Working fine till then authentication done.
At the time of callback with GET variables:
?code=something&authuser=0&prompt=consent&session_state=something
It is generating following error:
Fatal error: Uncaught exception 'Google_AuthException' with message
'Error fetching OAuth2 access token, message: 'invalid_client'' in
C:\xampp\htdocs\test\google-api-php-client\src\auth\Google_OAuth2.php:115
Stack trace: #0
C:\xampp\htdocs\test\google-api-php-client\src\Google_Client.php(127):
Google_OAuth2->authenticate(Array, 4/xUGSPbXR0LNzW...') #1
C:\xampp\htdocs\test\google-api-php-client\index.php(40):
Google_Client->authenticate('4/xUGSPbXR0LNzW...') #2 {main} thrown in
C:\xampp\htdocs\test\google-api-php-client\src\auth\Google_OAuth2.php
on line 115
Using following code (it will help you to understand):
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_PlusService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
$plus = new Google_PlusService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
$url = filter_var($me['url'], FILTER_VALIDATE_URL);
$img = filter_var($me['image']['url'], FILTER_VALIDATE_URL);
$name = filter_var($me['displayName'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$personMarkup = "<a rel='me' href='$url'>$name</a><div><img src='$img'></div>";
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$activityMarkup = '';
foreach($activities['items'] as $activity) {
$url = filter_var($activity['url'], FILTER_VALIDATE_URL);
$title = filter_var($activity['title'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$content = filter_var($activity['object']['content'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$activityMarkup .= "<div class='activity'><a href='$url'>$title</a><div>$content</div></div>";
}
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='style.css' />
<body>
<header><h1>Google+ Sample App</h1></header>
<div class="box">
<?php if(isset($personMarkup)): ?>
<div class="me"><?php print $personMarkup ?></div>
<?php endif ?>
<?php if(isset($activityMarkup)): ?>
<div class="activities">Your Activities: <?php print $activityMarkup ?></div>
<?php endif ?>
<?php
if(isset($authUrl)) {
print "<a class='login' id='g_pop' href='$authUrl'>Connect Me!</a>";
} else {
print_r($me);
print "<a class='logout' href='?logout'>Logout</a>";
}
?>
</div>
</body>
</html>
Get source files from here: Google APIs Client Library for PHP
Already done:
Client ID: OK
Client secret: OK
Redirect URIs: OK
Google+ API: ON
Note:
Working on localhost.
Had same issue. Fixed it by deleting the extra space from the client secret. When you copy it from google api console you get an extra space.
Double check that your google app credentials (client id, client secret, API key) are valid and passed to client correctly.
I am trying to use Google Oauth API to get userinfo.
It works perfectly for Google Plus API but I am trying to create a backup in case the user doesn't have google plus account.
The authentication process is correct and I even get the $userinfo object but how exactly do I access the properties. I tried $userinfo->get() but it only return the id of the user.
Am I doing something wrong? Here is the code that I am using...
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_Oauth2Service.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("Google+ PHP Starter Application");
// Visit https://code.google.com/apis/console to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId('*********************');
$client->setClientSecret('**************');
$client->setRedirectUri('***************');
$client->setDeveloperKey('**************');
$plus = new Google_Oauth2Service($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken())
{
$userinfo = $plus->userinfo;
print_r($userinfo->get());
} else
{
$authUrl = $client->createAuthUrl();
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel='stylesheet' href='style.css' />
</head>
<body>
<header><h1>Google+ Sample App</h1></header>
<div class="box">
<?php if(isset($personMarkup)): ?>
<div class="me"><?php print $personMarkup ?></div>
<?php endif ?>
<?php
if(isset($authUrl)) {
print "<a class='login' href='$authUrl'>Connect Me!</a>";
} else {
print "<a class='logout' href='?logout'>Logout</a>";
}
?>
</div>
</body>
</html>
Thanks...
**EDIT***
Was missing Scopes--Added
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
works now...
Was missing scopes
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile'));
Works like a charm now!
I'm not sure if it helps, but since the Google API PHP Client was updated, I get userinfo in this way:
$oauth = new Google_Service_Oauth2($googleClient);
var_dump($oauth->userinfo->get());
The Google API PHP client library has changed - here is how you fetch user information:
<?php
require_once('google-api-php-client-1.1.7/src/Google/autoload.php');
const TITLE = 'My amazing app';
const REDIRECT = 'https://example.com/myapp/';
session_start();
$client = new Google_Client();
$client->setApplicationName(TITLE);
$client->setClientId('REPLACE_ME.apps.googleusercontent.com');
$client->setClientSecret('REPLACE_ME');
$client->setRedirectUri(REDIRECT);
$client->setScopes(array(Google_Service_Plus::PLUS_ME));
$plus = new Google_Service_Plus($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
error_log('The session state did not match.');
exit(1);
}
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . REDIRECT);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken() && !$client->isAccessTokenExpired()) {
try {
$me = $plus->people->get('me');
$body = '<PRE>' . print_r($me, TRUE) . '</PRE>';
} catch (Google_Exception $e) {
error_log($e);
$body = htmlspecialchars($e->getMessage());
}
# the access token may have been updated lazily
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$body = sprintf('<P>Login</P>',
$client->createAuthUrl());
}
?>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE><?= TITLE ?></TITLE>
</HEAD>
<BODY>
<?= $body ?>
<P>Logout</P>
</BODY>
</HTML>
Do not forget to -
Get web client id and secret at Google API console
Authorize the https://example.com/myapp/ at the same place
You can find official examples at Youtube GitHub.
UPDATE 2017:
You can add the fields to be retrieved with:
const FIELDS = 'id,name,image';
$me = $plus->people->get('me', array('fields' => FIELDS));