Skip to content

Instantly share code, notes, and snippets.

@owenandrews
Created March 29, 2018 05:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save owenandrews/2a35337905122f98a1500242f1f92b79 to your computer and use it in GitHub Desktop.
Save owenandrews/2a35337905122f98a1500242f1f92b79 to your computer and use it in GitHub Desktop.
Bare Bones Google OAuth
<?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