Using the Google API with Socialite
Published on by Zac Vineyard
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_g8Uj5GGAqnPZaZAmlVMkUj0DXOVw0Z8GOOGLE_CLIENT_ID=53500906325-ocfb3qbl0inpb249gnuir4988kn3ef52.apps.googleusercontent.comGOOGLE_APP_SECRET=YnceM3Bdn6JpboaFgc27B3ImGOOGLE_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.
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.