CakePHP | Get user profile information through Gmail API (2.2.0)

|
| By Webner

Steps to extract user profile information through Gmail API (2.2.0) in CakePHP:

1. Set up developer test account inside google API developer console:

Use https://console.developers.google.com/ link to open developer console.

Add new project inside your developer console and enable the Google+ API. You will get your credentials in a json format file. Download the file and put it inside your web application web root folder.

2. Install gmail api client via Composer.
Run below command to install google api client inside your web application:

php composer.phar require google/apiclient:^2.0

3. Create an action inside your cake3 controller to get login URL to gmail API account:

namespace App\Controller;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Event\Event;
use Google\Auth\ApplicationDefaultCredentials;
use Google\Auth\Cache\MemoryCacheItemPool;
use Google\Auth\CredentialsLoader;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use Google\Auth\OAuth2;
use Google\Auth\Credentials\ServiceAccountCredentials;
use Google\Auth\Credentials\UserRefreshCredentials;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Ring\Client\StreamHandler;
use GuzzleHttp\Psr7;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Log\LoggerInterface;
use Monolog\Logger;
use Monolog\Handler\StreamHandler as MonologStreamHandler;
use Monolog\Handler\SyslogHandler as MonologSyslogHandler;
use Cake\Network\Http\Client;
class GmailAuthenticateController extends AppController {
public function index() {
$client = new \Google_Client ();
//specify the name of your json credentials file here. No need to type each 
//  Api credential key separately. Gmail api will read out the json file and get all    
// Required settings at its own.
	$client->setAuthConfig ( "credentials json file” );
	$client->setAccessType ( "offline" ); // offline access
	$client->setIncludeGrantedScopes ( true ); // incremental auth
	//redirect url will be the same as you have defined inside your api account inside 
	//developer console.
	$client->setRedirectUri (“http://test.com/gmail/redirectAction ); 
	$auth_url = $client->createAuthUrl ();
	$this->set ( "auth_url", $auth_url );

	}
}

Note: auth_url is the url which you have to open in the web browser. This will open the gmail login page from where you can login to gmail account:

index.ctp:		
$url =filter_var($auth_url, FILTER_SANITIZE_URL); ?>
</script>
window.location.href ='<?php  echo $url;?>'
</script>

When you will open the url select gmail account to login. After successful login, it will send response back to the redirect url you have specified inside your developers account settings.

4. Get Profile details inside your redirect action (specified with redirect url ).

When you will get back to your redirect action you will get some parameters. We will get access token from them which is used to further access the api methods:

public function redirectAction() {
	$access_token = $this->request->query ['code']; // access token 
	$client = new \Google_Client ();
	$client->addScope ( "https://www.googleapis.com/auth/userinfo.profile" );
	$client->addScope ( "https://www.googleapis.com/auth/userinfo.email" );
	//here we are passing the 
$client->authenticate($access_token);
	$oauth2Service = new \Google_Service_Oauth2($client);
	//get basic profile details
	$userProfileDetails = $oauth2Service->userinfo_v2_me->get();
	//revoke token to deauthorize the current access token
	$client->revokeToken();					
	} 

Leave a Reply

Your email address will not be published. Required fields are marked *