How to get all Gmail Contacts with Laravel 5

profile picture

How to get all Gmail Contacts with Laravel 5

Hi folks !

New quick tutorial today on how to retrieve your user's google contacts with Google API in Laravel 5.

Ok, to explain a bit how I did it, I first need to set everything in context. If you want to skip and get into it right now, just scroll to the first step.

With Laravel 5 comes a new package named Socialite. This package will help you deal with Oauth providers and it will be far easier for you to install a Social Network Login into your application. I highly recommend to use Socialite if you want to include a Facebook/Google/Github/Twitter connect to your project.

The only problem is that Socialite doesn't allow you to make custom requests to the provider's API. So in our case, if you want to retrieve the Google's contacts from your user, well it's not possible with Socialite (unless you amend the package yourself, which I don't recommend at all).

After realizing that Socialite is not adequate here, you will need to search a package that is. With Laravel 4, the most common one was artdarek/oauth-4-laravel, but unfortunately, it is not yet compatible with Laravel 5.

Sigh.

Wait ! A cool guy has actually forked the package to make it compatible with L5. How cool is that ?! :D

The initial package of artdarek should indeed be updated with oriceon's pull request. But in the meanwhile, let's use oriceon/oauth-5-laravel, which works like a charm.

Ready to dig in ? Here we are !

Step 1 : install the package

Well this is a pretty common task, that is explained in details in the package's readme. Simply add "oriceon/oauth-5-laravel": "dev-master" to your composer.json file and then run composer update in your terminal.

Don't forget to update your config/app.php with the following lines:

'providers' => [
    'Artdarek\OAuth\OAuthServiceProvider',
]
'aliases' => [
    'OAuth' => 'Artdarek\OAuth\Facade\OAuth',
]

You can now run php artisan vendor:publish to generate a configuration file, which will store your API keys.

In config/oauth-5-laravel.php, you can now add those lines just below the Facebook example:

'Facebook' => [
    'client_id'     => '',
    'client_secret' => '',
    'scope'         => [],
],

'Google' => [
    'client_id'     => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_SECRET_ID'),
    'scope'         => ['userinfo_email', 'userinfo_profile', 'https://www.google.com/m8/feeds/'],
],

This example assume that you store your API keys into your .env file.

Step 2 : Setting a new route

Here you can basically do it your own way, of course. But if you need an example, here's one:

Route::get('contact/import/google', ['as'=>'google.import', 'uses'=>'[email protected]']);

Be careful with the URI, as you need to match it with your google app configuration.

Step 3 : Create the method in your controller

Let's now add a new method inside our controller (here ContactController, to keep up with our example).

public function importGoogleContact()
{
    // get data from request
    $code = Request::get('code');

    // get google service
    $googleService = \OAuth::consumer('Google');

    // check if code is valid

    // if code is provided get user data and sign in
    if ( ! is_null($code)) {
        // This was a callback request from google, get the token
        $token = $googleService->requestAccessToken($code);

        // Send a request with it
        $result = json_decode($googleService->request('https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=400'), true);

        // Going through the array to clear it and create a new clean array with only the email addresses
        $emails = []; // initialize the new array
        foreach ($result['feed']['entry'] as $contact) {
            if (isset($contact['gd$email'])) { // Sometimes, a contact doesn't have email address
                $emails[] = $contact['gd$email'][0]['address'];
            }
        }
        
        return $emails;

    }
    
    // if not ask for permission first
    else {
        // get googleService authorization
        $url = $googleService->getAuthorizationUri();

        // return to google login url
        return redirect((string)$url);
    }
}

You can now have fun with your clean $emails array!

Yes, it needed to be cleaned up, as the actual response from google is a very detailed array of objects, that you have to carefully run through if you only need to retrieve the email addresses.

Also note that I added a **max-result **parameter to the request, because the default value of this parameter is 25. And if you want to get all the email addresses, well you obviously need to increase this number.

If you want to analyze the request result in details, simply returns the $result array.

2019 My Dynamic Production SPRL All rights Reserved.