Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

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 marketing and web development at Northwest Nazarene University, where I manage site design, development, and a variety of online resources.

Cube

Laravel Newsletter

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

Laravel Forge logo

Laravel Forge

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

Laravel Forge
Tinkerwell logo

Tinkerwell

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

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
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
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

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

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article
Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3 image

Herd Executable Support and Pest 3 Mutation Testing in PhpStorm 2024.3

Read article
Hide and safeguard emails from bots with the Muddle Laravel package image

Hide and safeguard emails from bots with the Muddle Laravel package

Read article
Dynamic Cache, Database, and Mail Builders in Laravel 11.31 image

Dynamic Cache, Database, and Mail Builders in Laravel 11.31

Read article
PHPStan 2.0 is Here image

PHPStan 2.0 is Here

Read article
Run multiple CLI commands locally at once with Solo for Laravel image

Run multiple CLI commands locally at once with Solo for Laravel

Read article