Geoff Garbers

Husband. Programmer. Tinkerer.

G Suite OAuth Quick Start with PHP

Sep 12, 2017

I recently had a need to integrate G Suite OAuth with a small project I was working on (requiring server-side interaction - so the JavaScript-based version wasn’t considered).

After following the PHP Quickstart tutorial, I noticed that it was designed to run through the PHP CLI. I needed it to run over HTTP.

Using this Quickstart tutorial, the code below provides the minimum requirement code that should be enough to get you up and running with G Suite OAuth. Before being able to use the code below, you would have had to follow steps 1 & 2 of the PHP Quickstart provided above.

// Include composer autoloader.
require __DIR__ . '/vendor/autoload.php';

// Set the path to the credentials.
$client = new Google_Client();
$client->setApplicationName('Name of your Google application');
$client->setAccessType('offline');

// These scopes allow the retrieval of the logged in user's profile.
$client->setScopes([Google_Service_Oauth2::PLUS_ME, Google_Service_Oauth2::USERINFO_PROFILE, Google_Service_Oauth2::USERINFO_EMAIL]);

// The path to the secrets JSON file that is downloaded in step 1 of the Quickstart.
$client->setAuthConfig(__DIR__ . '/secret.json');

// No code. Must go to Google.
if (!isset($_GET['code'])) {
    $authUrl = $client->createAuthUrl();
    header("Location: {$authUrl}");
    die();
}

// We have gone to Google, and are back.
$accessToken = $client->fetchAccessTokenWithAuthCode($_GET['code']);

// Something went wrong with exchanging the code for an access token.
if (isset($accessToken['error'])) {
    echo "Oops. Something went wrong.\n\n";
    echo sprintf("Full error description: %s\n", $accessToken['error_description']);
    die();
}

// Set the client access token.
$client->setAccessToken($accessToken);

// Fetch the user's profile.
$userProfile = (new Google_Service_OAuth2($client))->userinfo_v2_me->get();

// Access the user's details.
echo $userProfile->email;