Получите информацию о пользователе от API OAuth PHP от Google

Я хотел бы получить информацию о пользователе, такую ​​как имя, фамилия, адрес электронной почты, изображение и т. Д.

После входа на сайт с помощью учетной записи Google я использовал следующий код 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> с <?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.
    2. Авторизовать https://example.com/myapp/ в одном месте

    Вы можете найти больше примеров на Youtube GitHub .

    попробуй это:

     if ($ result = $ mysqli-> query ("SELECT COUNT (g_id) как usercount FROM social_users WHERE g_id = $ user_id")) {
         $ usercount = $ result-> fetch_object () -> usercount;
         $ Result-> близко ();
         if ($ usercount> 0) {
             // имеет такого пользователя
         }
     }