gpt4 book ai didi

php - 从 Google OAuth PHP API 获取用户信息

转载 作者:行者123 更新时间:2023-12-05 08:10:12 43 4
gpt4 key购买 nike

我想获取用户信息,如姓名、姓氏、电子邮件地址、图像等。

通过谷歌账户登录网站后,我使用了以下PHP代码:

<?php

########## Google Settings.. Client ID, Client Secret #############
// I fill these fieds with my keys
$google_client_id = '............';
$google_client_secret = '...............';
$google_redirect_url = '.......................';
$google_developer_key = '............';

########## MySql details (Replace with yours) #############
// I filled these fields with my data
$db_username = "*******"; //Database Username
$db_password = "*******"; //Database Password
$hostname = "*******"; //Mysql Hostname
$db_name = '**********'; //Database Name
###################################################################

//include google api files
require_once 'src/Google_Client.php';
require_once 'src/contrib/Google_Oauth2Service.php';

//start session
session_start();

$gClient = new Google_Client();
$gClient->setApplicationName('Login to techsa.ir');
$gClient->setClientId($google_client_id);
$gClient->setClientSecret($google_client_secret);
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey($google_developer_key);

$google_oauthV2 = new Google_Oauth2Service($gClient);

//If user wish to log out, we just unset Session variable
if (isset($_REQUEST['reset']))
{
unset($_SESSION['token']);
$gClient->revokeToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
}


if (isset($_GET['code']))
{
$gClient->authenticate($_GET['code']);
$_SESSION['token'] = $gClient->getAccessToken();
header('Location: ' . filter_var($google_redirect_url, FILTER_SANITIZE_URL));
return;
}


if (isset($_SESSION['token']))
{
$gClient->setAccessToken($_SESSION['token']);
}


if ($gClient->getAccessToken())
{
//Get user details if user is logged in
$user = $google_oauthV2->userinfo->get();
$user_id = $user['id'];
$user_name = filter_var($user['name'], FILTER_SANITIZE_SPECIAL_CHARS);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL);
$profile_url = filter_var($user['link'], FILTER_VALIDATE_URL);
$profile_image_url = filter_var($user['picture'], FILTER_VALIDATE_URL);
$personMarkup = "$email<div><img src='$profile_image_url?sz=50'></div>";
$_SESSION['token'] = $gClient->getAccessToken();
}
else
{
//get google login url
$authUrl = $gClient->createAuthUrl();
}

//HTML page start
echo '<html xmlns="http://www.w3.org/1999/xhtml">';
echo '<head>';
echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
echo '<title>Login with Google</title>';
echo '</head>';
echo '<body>';
echo '<h1>Login with Google</h1>';

if(isset($authUrl)) //user is not logged in, show login button
{
echo '<a class="login" href="'.$authUrl.'"><img src="images/google-login-button.png" /></a>';
}
else // user logged in
{
/* connect to mysql */
$connecDB = mysql_connect($hostname, $db_username, $db_password)or die("Unable to connect to MySQL");
mysql_select_db($db_name,$connecDB);

//compare user id in our database
$result = mysql_query("SELECT COUNT(g_id) FROM social_users WHERE g_id=$user_id");
if($result === false) {
die(mysql_error()); //result is false show db error and exit.
}

$UserCount = mysql_fetch_array($result);

if($UserCount[0]) //user id exist in database
{
echo 'Welcome back '.$user_name.'!';
}else{ //user is new
echo 'Hello! '.$user_name.', Thanks for Registering!';
@mysql_query("INSERT INTO social_users (g_id, g_name, g_email, g_link, g_image, created_date) VALUES ($user_id, '$user_name','$email','$profile_url','$profile_image_url', now())");
}


echo '<br /><a href="'.$profile_url.'" target="_blank"><img src="'.$profile_image_url.'?sz=50" /></a>';
echo '<br /><a class="logout" href="?reset=1">Logout</a>';

//list all user details
echo '<pre>';
print_r($user);
echo '</pre>';
}

echo '</body></html>';
?>

我的数据库中有一个名为 social_users 的表。用户授予权限,但表是空的。

最佳答案

您的情况不需要 $google_developer_key

以下是现在如何使用 google-api-php-client 获取用户信息图书馆:

<?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><A HREF="%s">Login</A></P>',
$client->createAuthUrl());
}

?>

<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE><?= TITLE ?></TITLE>
</HEAD>
<BODY>
<?= $body ?>
<P><A HREF="<?= REDIRECT ?>?logout">Logout</A></P>
</BODY>
</HTML>

不要忘记-

  1. Google API console 获取 Web 客户端 ID 和密码
  2. 在同一个地方授权https://example.com/myapp/

您可以在 Youtube GitHub 找到更多示例.

关于php - 从 Google OAuth PHP API 获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23034056/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com