Created
March 29, 2018 05:10
-
-
Save owenandrews/2a35337905122f98a1500242f1f92b79 to your computer and use it in GitHub Desktop.
Bare Bones Google OAuth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// composer require google/apiclient:^2.0 | |
require_once __DIR__.'/vendor/autoload.php'; | |
const CLIENT_ID = ''; | |
const CLIENT_SECRET = ''; | |
const APPLICATION_NAME = ""; | |
const REDIRECT_URI = "http://localhost:8080/"; | |
// Create API Client | |
$client = new Google_Client(); | |
$client->setApplicationName(APPLICATION_NAME); | |
$client->setClientId(CLIENT_ID); | |
$client->setClientSecret(CLIENT_SECRET); | |
$client->setRedirectUri(REDIRECT_URI); | |
$client->addScope("https://www.googleapis.com/auth/userinfo.profile"); | |
$client->addScope("https://www.googleapis.com/auth/userinfo.email"); | |
$oauth = new Google_Service_Oauth2($client); | |
// Get code from login flow and set access token | |
if (isset($_GET['code'])) { | |
$client->authenticate($_GET['code']); | |
$client->setAccessToken($client->getAccessToken()); | |
} | |
if ($client->getAccessToken()) { | |
$userData = $oauth->userinfo->get(); | |
if(!empty($userData)) { | |
header('Content-Type: application/json'); | |
echo(json_encode($userData, JSON_PRETTY_PRINT)); | |
$client->revokeToken(); | |
} | |
} else { | |
$authUrl = $client->createAuthUrl(); | |
echo('<a href="'.$authUrl.'">Login</a>'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment