English version steps
- First click on the video link below and follow this video to configure what you need on Google Cloud Console. You can stop watching at 5:31. Video link: https://www.youtube.com/watch?v=xH6hAW3EqLk
- PHP implementation requires downloading a google-api-php-client. click on this link below to download. Where my version is PHP 7.4, you can also choose other versions. Link: https://github.com/googleapis/google-api-php-client/releases
- After downloading and unzipping, put the whole folder into your project root directory. Your project needs a folder called google-api-php-client–PHP7.4 (7.4 is the version)
- Then, you can start doing it. You can follow this PHP code at the code section at the end of this article to implement an example of a user logging in with a Google account and adjust it yourself to fit your needs.
中文步骤
- 首先点击以下视频链接,跟着这个视频在Google Cloud Console上配置好所需的东西。你可以在第5:31停止观看。视频链接:https://www.youtube.com/watch?v=xH6hAW3EqLk
- PHP实现需要下载一个google-api-php-client。点击以下这个链接进行下载。其中我的版本是PHP7.4,你也可以选择其它版本。链接:https://github.com/googleapis/google-api-php-client/releases
- 下载完解压缩后,把整个文件夹放到你的项目根目录里。你的项目里需要有个文件夹叫google-api-php-client–PHP7.4 (7.4为版本)
- 然后,就可以开始做了。可以根据在文章最后的Code部分的PHP代码实现用户用Google账户登录的例子,自行调整以符合自己的需求。
Code Section (PHP代码部分)
<?php
session_start();
require_once 'google-api-php-client--PHP7.4/vendor/autoload.php';
$loginButton = '';
$gClient = new Google\Client();
$gClient->setClientId('Your Client ID');
$gClient->setClientSecret('Your Client Secret');
$gClient->setApplicationName("Your app name");
$gClient->setRedirectUri('http://assignmentmanagerxxxxx.xxxxxxx.xxxxxx.elasticbeanstalk.com/login.php');
$gClient->setAccessType('offline');
$gClient->setApprovalPrompt('force');
$gClient->addScope('profile');
$gClient->addScope('email');
if (isset($_GET['code'])) {
$token = $gClient->fetchAccessTokenWithAuthCode($_GET['code']);
$_SESSION["access_token"] = $token;
$gClient->setAccessToken($token);
$oAuth = new Google\Service\Oauth2($gClient);
$userData = $oAuth->userinfo->get();
$_SESSION["currentUserId"] = $userData->id;
$_SESSION["currentUserEmail"] = $userData->email;
$_SESSION["user_name"] = $userData->givenName;
if (isset($_SESSION["currentUserId"])) {
header('Location:manager.php');
exit();
}
} else {
$loginButton = '<a class="googleLogin" href="' . $gClient->createAuthUrl() . '">Login with Google</a>';
}
?>