[英]“Login with Google” in PHP - Google+ API shutdown migration - how to migrate away from plus.people.get?
I got a warning email from Google reminding me of Google+'s EOL which is supposed to break my current "Login with Google", but I am unsure what exactly should I change. 我收到了来自Google的警告电子邮件,使我想起了Google+的EOL,这应该会破坏我当前的“使用Google登录”,但是我不确定应该如何更改。
Let me show you my (simplified) login code: 让我告诉您我的(简化的)登录代码:
google-login.php 谷歌-的login.php
new class {
public function __construct() {
$state = mt_rand();
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl(); // $url = https://accounts.google.com/o/oauth2/auth?response_type=code&access_type=online&client_id=CLIENT_ID.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Fread2me.online%2Fmembers%2Fgoogle-callback.php&state=1588245f23f2a&scope=profile%20email&approval_prompt=auto
header ("location: $url");
}
};
google-callback.php 谷歌,callback.php
new class {
private $newUser = false;
public function __construct() {
if (!isset($_GET['state']) || $_GET['state'] != $_SESSION['state'])
die('State mismatch.');
$client = new Google_Client();
$client->setApplicationName(Config::Google['app_name']);
$client->setClientId(Config::Google['id']);
$client->setClientSecret(Config::Google['secret']);
$client->setRedirectUri(sprintf('https://%s/members/google-callback.php', $_SERVER['HTTP_HOST']));
$client->setScopes(['profile', 'email']);
$plus = new Google_Service_Plus($client);
if (isset($_GET['code'])) {
$client->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (!$client->getAccessToken() || $client->isAccessTokenExpired()) {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$url = $client->createAuthUrl();
header ("location: $url");
}
try {
$me = $plus->people->get('me');
} catch (Google_Exception $e) {
\Rollbar::report_message($e->getMessage());
print_r($e->getMessage());
return;
}
$accessToken = $client->getAccessToken()['access_token'];
$email = $me->getEmails()[0]->getValue();
$name = $me->getDisplayName();
$avatar = $me->getImage()->getUrl();
$id = $me->getId();
if ($this->isEmailInSystem($email) === false) {
$this->newUser = true;
$this->addUser($email, $name, 'google', $accessToken, $id, $avatar);
}
header ("location: " . '/');
}
};
Now, I'm going through at what seems to be the up-to-date Sign In guide for PHP , but I am not sure what to change - any ideas? 现在,我正在查看似乎是最新的PHP登录指南 ,但是我不确定要更改什么-有什么想法吗?
Thanks 谢谢
The best migration is to move from the Plus API to the People API , which provides access to the user's profile in a similar (tho not quite identical) way. 最好的迁移方法是从Plus API迁移到People API ,后者以相似(不太完全相同)的方式提供对用户个人资料的访问。
You would replace the creation of the $plus
object with a new Goolge_Service_PeopleService
object. 您将用新的
Goolge_Service_PeopleService
对象替换$plus
对象的创建。 Something like 就像是
$people = new Google_Service_PeopleService( $client );
Getting the profile is more involved since you need to specify which fields from the profile you want to get. 获取配置文件涉及更多,因为您需要指定要从配置文件中获取哪些字段。 But you might do it something like
但是你可能会像
$profile = $people->people->get(
'people/me',
array('personFields' => 'names,emailAddresses,photos')
);
The first parameter needs to be "people/me" to specify that you're requesting the authorized user's profile. 第一个参数必须为“ people / me”,以指定您正在请求授权用户的个人资料。
The second is an array of query parameters. 第二个是查询参数数组。 You need to specify the "personFields" that you want from the list of what is available (scroll down on this page till you see the description of the available fields) and specify this as a comma separated list in a string.
您需要从可用列表中指定所需的“ personFields”(向下滚动此页面,直到看到可用字段的描述),并将其指定为字符串中的逗号分隔列表。 In my example above, I illustrate getting the name, email addresses, and photos.
在上面的示例中,我说明了获取名称,电子邮件地址和照片。 But consult the list and experiment.
但是请参考清单并进行实验。
The exact fields you get from the result in $profile
will be different than those you got from $plus
, but they should match the fields you requested. 从
$profile
的结果中获取的确切字段将与从$plus
中获得的字段不同,但它们应与您请求的字段匹配。 Check the values and exactly how they're structured. 检查值以及它们的结构。
Make sure Google People API is enable in your google console I used google-api-php-client Library. 确保我在使用google-api-php-client库的Google控制台中启用了Google People API 。
Once you have an access token here is code to get the person object using people API 获得访问令牌后,这里是使用people API获取person对象的代码
$accessToken = 'REPLACE_WITH_ACCESS_TOKEN';
$clientId = 'REPLACE_WITH_CLIENT_ID';
$clientSecret = 'REPLACE_WITH_CLIENT_SECRET';
$developerKey = 'REPLACE_WITH_DEVELOPER_KEY';
$client = new Google_Client();
$client->setApplicationName("Application Name");
$client->setClientId($clientId . '.apps.googleusercontent.com');
$client->setClientSecret($clientSecret);
$client->setDeveloperKey($developerKey);
$client->setScopes(['https://www.googleapis.com/auth/userinfo.email','https://www.googleapis.com/auth/userinfo.profile']);
$client->setAccessToken($accessToken);
$guzzleClient = new \GuzzleHttp\Client(array( 'curl' => array( CURLOPT_SSL_VERIFYPEER => false, ), ));
$client->setHttpClient($guzzleClient);
$people = new Google_Service_PeopleService( $client );
if ($client->getAccessToken()) {
try {
$me = $people->people->get(
'people/me',
array('personFields' => 'emailAddresses,names,photos')
);
$id = preg_replace('/[^0-9]/', '', $me->getResourceName());
$email = $me->getEmailAddresses()[0]->value;
$name = $me->getNames()[0]->displayName;
$avtar = $me->getPhotos()[0]->getUrl();
} catch (Google_Exception $e) {
// error
echo $e->getMessage();
}
}
I also disabled Google+ API to make sure the application is not using it anymore anywhere. 我还禁用了Google+ API ,以确保应用程序不再在任何地方使用它。
With latest version of Google API PHP Client you can fetch profile details from Google_Client
object itself. 使用最新版本的Google API PHP客户端,您可以从
Google_Client
对象本身获取配置文件详细信息。
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$attributes = $client->verifyIdToken($token['id_token'], GOOGLE_CLIENT_ID);
print_r($attributes);
Obviously, the lines 显然,线条
$plus = new Google_Service_Plus($client);
and 和
$me = $plus->people->get('me');
You need to use google email API, see https://developers.google.com/gmail/api/quickstart/php , so the first line will be 您需要使用google email API,请参阅https://developers.google.com/gmail/api/quickstart/php ,因此第一行是
$service = new Google_Service_Gmail($client);
and second ... hmmm ... not sure there WILL be any avatar after removing of google plus ... 第二个...嗯...不确定删除谷歌加后会不会有任何化身...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.