Code review at scale is broken. Here’s how Augment Code is fixing it.

Using the Google API with Socialite

Published on by

Using the Google API with Socialite image

When I start a project that requires users to log in using their Google accounts, I immediately turned to Laravel Socialite. Socialite is one of Laravel’s official packages, but it is clear it only handles user authentication, making its use not as dynamic as I had hoped it would be. While I needed users to log in, I also needed to get a list of their Google Contacts. In this post, I’ll show you how I was able to query a list of contacts from Google’s People API and keep using Socialite.

As you progress through this post, it is assumed you have Laravel and Laravel Socialite installed. If you haven’t done that, please refer to the Socialite documentation on GitHub.

Create an Application in the Google API Console

Because our app will be a using Google for authentication and as a data resource, you must create an app in the Google API Console. Look for the “Create Project” link in the submenu at the top of the page to get started. Once you have an app created in the Google API Console, you’ll need to create or locate three pieces of authentication information: a Google server key, a client ID, and an app secret. Your app secret will be provided when you create your app in the Google API Console. The server key and client ID can both be found under the “Credentials” link in the sidebar of the Google API Console. If you don’t see the server key or client ID listed on the Credentials page, you’ll need to create them using the blue “Create Credentials” button.

Once you have all three pieces of authentication information, add them, along with your app redirect URL, to your Laravel .env file.

GOOGLE_SERVER_KEY=AIzaSyC_g8Uj5GGAqnPZaZAmlVMkUj0DXOVw0Z8
GOOGLE_CLIENT_ID=53500906325-ocfb3qbl0inpb249gnuir4988kn3ef52.apps.googleusercontent.com
GOOGLE_APP_SECRET=YnceM3Bdn6JpboaFgc27B3Im
GOOGLE_REDIRECT=http://localhost:8000/login/google/callback

Install the Google API PHP Client

The next requirement for this project is to add the Google API PHP Client to your Laravel project. Just use Composer to install the Google API PHP Client.

composer require google/apiclient:^2.0

After running this command, reference the Google API PHP Client in your auth/LoginController.php file. You’ll also want to reference any Google Service you want to use from the Google API PHP Client. In this example, we’re going to use Google’s People API to query a list of a Google user’s contacts. To do so, you’ll need to reference Google_Service_People in your auth/LoginController.php file as well.

<?php
 
namespace App\Http\Controllers\Auth;
 
use Socialite;
use Google_Client;
use Google_Service_People;

Declare API Scopes

As part of the Socialite installation process, you added two methods to your auth /LoginController.php file: redirectToProvider() and handleProviderCallback(). Make sure you declare your API scopes in the redirectToProvider() method. In this example, we’ll be querying a Google user’s contacts using the API, so pass Google_Service_People::CONTACTS_READONLY to the scopes method on the Socialite object.

public function redirectToProvider()
{
return Socialite::driver('google')
->scopes(['openid', 'profile', 'email', Google_Service_People::CONTACTS_READONLY])
->redirect();
}

Enable the API Endpoint

Anytime you want to use a scope in the Google API, you need to enable the corresponding API service in the Google API Console. Return to the Google API Console and click “Library” in the side menu. The Google People API does not show in the list of popular API endpoints, so you’ll need to search for it using the provided search bar. Enable Google’s People API for your app.

Use the Socialite Token for the Google API PHP Client

Laravel Socialite and the Google API PHP Client have small differences in their data structure requirements. The token stored and provided by Socialite doesn’t match the data type the Google API PHP Client expects. Socialite provides an object, but the Google client expects a JSON array.

In the handleProviderCallback() method in your auth/LoginController.php, you’ll need to create the array for the Google_Client using the token, refreshToken, and expiresIn properties of the Socialite object, as seen below in the $google_client_token variable (array). You can then JSON encode that array for use with the Google_Client::setAccessToken method.

public function handleProviderCallback(Request $request)
{
$user = Socialite::driver('google')->user();
 
// Set token for the Google API PHP Client
$google_client_token = [
'access_token' => $user->token,
'refresh_token' => $user->refreshToken,
'expires_in' => $user->expiresIn
];
 
$client = new Google_Client();
$client->setApplicationName("Laravel");
$client->setDeveloperKey(env('GOOGLE_SERVER_KEY'));
$client->setAccessToken(json_encode($google_client_token));
}

After you’ve set the access token for the Google_Client library, you can query data from the API’s endpoints you’ve enabled and added to the scope.

public function handleProviderCallback(Request $request)
{
$user = Socialite::driver('google')->user();
 
// Set token for the Google API PHP Client
$google_client_token = [
'access_token' => $user->token,
'refresh_token' => $user->refreshToken,
'expires_in' => $user->expiresIn
];
 
$client = new Google_Client();
$client->setApplicationName("Laravel");
$client->setDeveloperKey(env('GOOGLE_SERVER_KEY'));
$client->setAccessToken(json_encode($google_client_token));
 
$service = new Google_Service_People($client);
 
$optParams = array('requestMask.includeField' => 'person.phone_numbers,person.names,person.email_addresses');
$results = $service->people_connections->listPeopleConnections('people/me',$optParams);
 
dd($results);
}

Important Note About Google’s People API

Google’s People API documentation seems to suggest that email addresses come back as part of a default query, but that doesn’t seem to be true. To resolve this, you need to add requestMask.includeField as a parameter in the request.

Refresh Tokens

Socialite should handle a token refresh (if it is provided by the service) if an access token expires. If the token has expired, you’ll make a new request using Socialite, then pass the new access token to the Google API PHP Client in the same way demonstrated above.

Try It Out

Assuming you’re using php artisan serve to serve your site, you can visit http://localhost:8000/login/google on your development server to try it out! You should be prompted to log into your Google Account and let your Google Application access your account information and contact list. After clicking “Allow,” you should see a list of contacts from your Google account in the dd() output.

Where Next?

The code above is a basic example. You’ll want to store the Socialite access token in your DB or in a session variable as part of a practical application for users. That will get you closer to implementing this feature in an advanced way.

Zac Vineyard photo

I'm a Boise area web developer who's passionate about design, code, and the tools of my craft. Day-to-day I work with PHP, JavaScript, and CSS. I'm currently the director of enrollment marketing technology at Miami University (OH).

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Detecting and Fixing Race Conditions in Laravel Applications image

Detecting and Fixing Race Conditions in Laravel Applications

Read article
LaraCopilot: Generate Laravel MVPs From a Single Prompt With AI image

LaraCopilot: Generate Laravel MVPs From a Single Prompt With AI

Read article
Model::withoutRelation() in Laravel 12.54.0 image

Model::withoutRelation() in Laravel 12.54.0

Read article
Tyro Checkpoint: Instant SQLite Snapshots for Laravel Local Development image

Tyro Checkpoint: Instant SQLite Snapshots for Laravel Local Development

Read article
The Laravel Community Mobile App Helps You Discover Events and Connect With Developers image

The Laravel Community Mobile App Helps You Discover Events and Connect With Developers

Read article
A PHP Package for Concurrent Website Crawling image

A PHP Package for Concurrent Website Crawling

Read article