![](/img/trans.png)
[英]how to create a PHP REST API Client to get the user logged in on the server?
[英]Get logged in user with google client api php
我有一個應用程序設置並供用戶在他們的日歷中插入事件。 我需要驗證他們是否使用正確的谷歌帳戶登錄。 (工作郵箱)。 我已經在網上搜索了幾個小時但沒有運氣。 我嘗試了幾種不同的方法,但都沒有運氣:/我希望有人可以指導我或幫助我使其工作。 謝謝! 這是我所擁有的
$client = new Google_Client();
$client->setApplicationName("Intakes Calendar");
$client->setClientId('xxxxxxxx.apps.googleusercontent.com');
$client->setClientSecret('xxxxx');
$client->setRedirectUri('xxx');
$client->setDeveloperKey('xxx');
$client->setScopes(array('https://www.googleapis.com/auth/calendar'));
$client->addScope('https://www.googleapis.com/auth/userinfo.email');
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
//echo "<br>Getting access";
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()){
if($client->isAccessTokenExpired()) {
$authUrl = $client->createAuthUrl();
$button = '<a class="btn btn-success btn-sm" href="'.$authUrl.'">SIGN IN</a>';
$msg = '<DIV class="col-md-6 col-md-offset-3 alert alert-warning">You are not signed in with your work email account for remote sessions.' . $button . '</DIV>';
}else{
//if logged in check for user email
if($_SESSION['USER_EMAIL'] == 'GOOGLE LOGGED IN EMAIL?')
$msg = ' <DIV class="col-md-6 col-md-offset-3 alert alert-warning">You are connected and ready for remote sessions.</DIV>';
else
$msg = ' <DIV class="col-md-6 col-md-offset-3 alert alert-warning">Please log in with your work email.</DIV>';
}
}else{
$authUrl = $client->createAuthUrl();
$button = '<a class="btn btn-success btn-sm" href="'.$authUrl.'">SIGN IN</a>';
$msg = '<DIV class="col-md-6 col-md-offset-3 alert alert-warning">You are not signed in with your work email account for remote sessions.' . $button . '</DIV>';
}
終於想通了!!!
首先,您必須為 gmail 添加范圍
$client->addScope('https://www.googleapis.com/auth/gmail.readonly');
然后啟動 gmail 服務和用戶個人資料電子郵件地址
$gmailService = new Google_Service_Gmail($client);
$users = $gmailService->users->getProfile('me');
echo $users['emailAddress']; //this is the logged in user's email address
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.