@samirapadidar solution with league/oauth2-client package:
-- create a Google project (https://console.developers.google.com/)
-- enable APIs and OAuth consent screen in this Google project with redirect URI http://localhost:8000/auth/google/callback
-- get Client ID and Secret of this Google project
-- install and configure league/oauth2-client Package:
composer require league/oauth2-client
-- create a configuration file config/google_oauth_config.php and fill it with the following details, replacing placeholders with your actual values:
return [
'google' => [
'client_id' => 'YOUR_CLIENT_ID',
'client_secret' => 'YOUR_CLIENT_SECRET',
'redirect_uri' => 'YOUR_REDIRECT_URI',
],
];
-- implement login and registration flow:
require 'vendor/autoload.php';
require 'config/google_oauth_config.php '; // Include your configuration file
// Create a Google provider object
$provider = new League\OAuth2\Client\Provider\Google([
'clientId' => $config['google']['client_id'],
'clientSecret' => $config['google']['client_secret'],
'redirectUri' => $config['google']['redirect_uri'],
]);
// Handle login request
if (!isset($_GET['code'])) {
// Redirect to Google login page
$authorizationUrl = $provider->getAuthorizationUrl([
'access_type' => 'offline', // Request refresh token for persistent logins
'prompt' => 'select_account' // Allow user to choose Google account
]);
header('Location: ' . $authorizationUrl);
exit;
}
// Handle login callback
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// Use the access token to fetch user information
$user = $provider->getResourceOwner($token);
// Process user information for login or registration
// ... (You'll need to implement your own logic here)
echo 'Welcome, ' . $user->getEmail();
``