我想知道是否可以使用Google+ api获取“userId”值,以显示指向某个特定用户个人资料的链接。为了更好地解释,我有一个PHP应用程序,并且有一个面板,我可以在其中查看数据库中的现有用户。因此,在详细说明特定用户时,我想显示一个Google+徽章,该徽章将链接到该用户的Google+个人资料。我没有“userId”,但仍然可以访问他的电子邮件地址。有什么建议吗?
答案 0 :(得分:1)
您无法点击将电子邮件地址转换为Google+ userId的终端。
但是,您可以使用REST API来确定当前登录用户的Google+ userId。这将要求用户通过OAuth授予您访问Google+身份的权限。为此,请使用people get端点作为userId。您可以在API Explorer上对此进行尝试,以观察用户使用OAuth对话框的体验。
以下是从PHP starter project中提取的一些代码,其中说明了获取当前用户的userId所需的一切:
if (ini_get('register_globals') === "1") {
die("register_globals must be turned off before using the starter application");
}
require_once 'google-api-php-client/src/apiClient.php';
require_once 'google-api-php-client/src/contrib/apiPlusService.php';
session_start();
$client = new apiClient();
$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('insert_your_oauth2_client_id');
$client->setClientSecret('insert_your_oauth2_client_secret');
$client->setRedirectUri('insert_your_oauth2_redirect_uri');
$client->setDeveloperKey('insert_your_developer_key');
$client->setScopes(array('https://www.googleapis.com/auth/plus.me'));
$plus = new apiPlusService($client);
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$me = $plus->people->get('me');
// Do stuff with the id
echo $me['id'];
// The access token may have been updated lazily.
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}