php - 使用谷歌客户端 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
推荐阅读
- javascript - TypeScript 中的引用发生了什么?
- xsl-fo - 调整块容器内块的垂直位置
- c# - Nuget 包动态 ConnectionString
- html - index.html 尝试从根 URI 解析 css 文件
- regular-language - 是 L = {ww^Ru | w, u ∈ {0,1}+} 正则语言?
- typescript - 声明一个类型,允许其他类型的所有级别的所有部分
- python - django 返回“AnonymousUser”对象没有属性“_meta”错误
- c++ - 长字符串类型未正确保存
- prisma - 如何自定义 prisma graphQL 模式以不自动生成突变?
- android - 在 React Native 中实现通话录音