本文整理汇总了PHP中Google_Client::getAccessToken方法的典型用法代码示例。如果您正苦于以下问题:PHP Google_Client::getAccessToken方法的具体用法?PHP Google_Client::getAccessToken怎么用?PHP Google_Client::getAccessToken使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Google_Client
的用法示例。
在下文中一共展示了Google_Client::getAccessToken方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: google
function google()
{
$client = new Google_Client();
$client->setApplicationName("snmmaurya");
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->setApprovalPrompt(APPROVAL_PROMPT);
$client->setAccessType(ACCESS_TYPE);
$oauth2 = new Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['error'])) {
echo '<script type="text/javascript">window.close();</script>';
exit;
}
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get();
$_SESSION['User'] = $user;
$_SESSION['token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
header('Location: ' . $authUrl);
}
}
示例2: getGoogleApiClient
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
private function getGoogleApiClient()
{
$client = new Google_Client();
$client->setApplicationName($this->CFG['GOOGLE_API_APPLICATION_NAME']);
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAuthConfigFile($this->CFG['GOOGLE_API_CLIENT_SECRET_PATH']);
$client->setAccessType('offline');
// Load previously authorized credentials from a file.
$credentialsPath = $this->CFG['GOOGLE_API_CREDENTIALS_PATH'];
if (file_exists($credentialsPath)) {
$accessToken = file_get_contents($credentialsPath);
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->authenticate($authCode);
// Store the credentials to disk.
if (!file_exists(dirname($credentialsPath))) {
mkdir(dirname($credentialsPath), 0700, true);
}
file_put_contents($credentialsPath, $accessToken);
printf("Credentials saved to %s\n", $credentialsPath);
}
$client->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->refreshToken($client->getRefreshToken());
file_put_contents($credentialsPath, $client->getAccessToken());
}
return $client;
}
示例3: signin
public function signin()
{
$client = new \Google_Client();
$client->setClientId(Config::get('ntentan:social.google.client_id'));
$client->setClientSecret(Config::get('ntentan:social.google.client_secret'));
$client->setRedirectUri(Config::get('ntentan:social.google.redirect_uri'));
$client->addScope(array('profile', 'email'));
$oauth2 = new \Google_Service_Oauth2($client);
if (isset($_REQUEST['logout'])) {
Session::set('access_token', '');
$client->revokeToken();
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
Session::set('access_token', $client->getAccessToken());
Redirect::path(\ntentan\Router::getRoute());
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->isAccessTokenExpired()) {
$authUrl = $client->createAuthUrl();
header('Location: ' . filter_var($authUrl, FILTER_SANITIZE_URL));
}
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get();
$_SESSION['token'] = $client->getAccessToken();
return array('firstname' => $user['given_name'], 'lastname' => $user['family_name'], 'key' => "google_{$user['id']}", 'avatar' => $user['picture'], 'email' => $user['email'], 'email_confirmed' => $user['verified_email']);
} else {
header("Location: {$client->createAuthUrl()}");
die;
}
return false;
}
示例4: login
/**
* @param $code
* @return string
*/
public function login($code)
{
$this->client->authenticate($code);
$token = $this->client->getAccessToken();
\Session::put('token', $token);
return $token;
}
示例5: googlecallback
public function googlecallback()
{
$ret = null;
//$google_redirect_url = site_url('user/signup');
$google_redirect_url = 'http://localhost/punu/punu/index.php/user/signup';
$client = new Google_Client();
$client->setClientId($this->google_client_id);
$client->setClientSecret($this->google_client_secret);
$client->setDeveloperKey($this->google_api_key);
$client->setRedirectUri($google_redirect_url);
$client->addScope($this->google_scope);
// Send Client Request
$objOAuthService = new Google_Service_Oauth2($client);
// Add Access Token to Session
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['google_access_token'] = $client->getAccessToken();
//header('Location: ' . filter_var($this->google_redirect_url, FILTER_SANITIZE_URL));
}
// Set Access Token to make Request
if (isset($_SESSION['google_access_token']) && $_SESSION['google_access_token']) {
$client->setAccessToken($_SESSION['google_access_token']);
}
// Get User Data from Google and store them in $data
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
//$_SESSION['userData'] = $userData;
$_SESSION['google_access_token'] = $client->getAccessToken();
$ret = $userData;
}
return $ret;
}
示例6: onNextendYoutube
function onNextendYoutube(&$google, &$youtube)
{
$config = new NextendData();
$config->loadJson(NextendSmartSliderStorage::get(self::$_group));
if (!class_exists('Google_Client')) {
require_once dirname(__FILE__) . '/googleclient/Google_Client.php';
}
if (!class_exists('Google_YouTubeService')) {
require_once dirname(__FILE__) . '/googleclient/contrib/Google_YouTubeService.php';
}
$google = new Google_Client();
$google->setClientId($config->get('apikey', ''));
$google->setClientSecret($config->get('apisecret', ''));
$token = $config->get('token', null);
if ($token) {
$google->setAccessToken($token);
}
$youtube = new Google_YouTubeService($google);
if ($google->isAccessTokenExpired()) {
$token = json_decode($google->getAccessToken(), true);
if (isset($token['refresh_token'])) {
$google->refreshToken($token['refresh_token']);
$config->set('token', $google->getAccessToken());
NextendSmartSliderStorage::set(self::$_group, $config->toJSON());
}
}
}
示例7: bdn_is_user_auth2
function bdn_is_user_auth2()
{
global $driveService;
$current_user_id = get_current_user_id();
$client = new Google_Client();
$client->setRedirectUri(home_url('/'));
$driveService = new Google_DriveService($client);
$oauth2 = new Google_Oauth2Service($client);
if (!isset($_GET['code']) && (!is_user_logged_in() || ($access_token = get_user_meta($current_user_id, '_google_access_token', true)) && $client->setAccessToken($access_token) && !$client->getAccessToken())) {
header('Location: ' . $client->createAuthUrl());
exit;
}
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$user = $oauth2->userinfo->get();
$new_user = get_user_by('email', $user['email']);
if (!$current_user_id) {
wp_set_current_user($new_user->ID, $new_user->user_login);
wp_set_auth_cookie($new_user->ID);
do_action('wp_login', $new_user->user_login);
} elseif ($new_user->ID == $current_user_id) {
update_user_meta($new_user->ID, '_google_access_token', $client->getAccessToken());
} else {
die('Sorry, please use your BDN account');
}
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
return $driveService;
}
示例8: index
public function index()
{
// include_once APPPATH . 'libraries/Facebook/facebook.php';
// $facebook = new Facebook([
// 'appId' => '852953064822534',
// 'secret' => '29888930212d679180731cc5232732c8'
// ]);
// $user = $facebook->getUser();
include_once APPPATH . 'libraries/Google/autoload.php';
$client_id = GOOGLE_CLIENT_ID;
$client_secret = GOOGLE_CLIENT_SECRET;
$redirect_uri = GOOGLE_REDIRECT_URL;
// Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("PHP Google OAuth Login Example");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
// Send Client Request
$objOAuthService = new Google_Service_Oauth2($client);
// Add Access Token to Session
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$this->session->set_userdata(array('access_token' => $client->getAccessToken()));
// header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// Set Access Token to make Request
if ($this->session->userdata('access_token') != null) {
$client->setAccessToken($this->session->userdata('access_token'));
}
// Get User Data from Google and store them in $data
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
$data['userData'] = $userData;
$this->session->set_userdata(array('access_token' => $client->getAccessToken()));
$ret = $this->User_model->addUser($data['userData']);
if ($ret == 'SUSPENDED') {
$unset = array('access_token');
$this->session->unset_userdata($unset);
$newdata = array('error' => "<font color='red'>Your account has been suspended</font>");
$this->session->set_flashdata($newdata);
redirect('signin');
} else {
if ($ret == 'FAIL') {
$newdata = array('error' => "<font color='red'>Something is issue with login</font>");
$this->session->set_flashdata($newdata);
redirect('signin');
}
}
redirect('dashboard');
} else {
$authUrl = $client->createAuthUrl();
$data['authUrl'] = $authUrl;
// $data['fbLoginUrl'] = $fbLoginUrl;
loadView('signIn', $data);
}
}
示例9: refreshToken
public function refreshToken($accessToken)
{
$this->_googleClient->setAccessToken($accessToken);
// Refresh the token if it's expired.
if ($this->_googleClient->isAccessTokenExpired()) {
$this->_googleClient->refreshToken($this->_googleClient->getRefreshToken());
}
return $this->_googleClient->getAccessToken();
}
示例10: index
public function index()
{
if ($this->input->get("error") && $this->input->get("error") == 'access_denied') {
redirect("login");
}
// Include the google api php libraries
include_once APPPATH . "libraries/google-api-php-client/Google_Client.php";
include_once APPPATH . "libraries/google-api-php-client/contrib/Google_Oauth2Service.php";
// Google Project API Credentials
$clientId = '438313202103-5ts2epm0c9b8mlj4ddf4lkis3l2qmkq0.apps.googleusercontent.com';
$clientSecret = 'KIW-gQpaglq1dwa3gBAerJdP';
$redirectUrl = 'http://99rightdeals.com/gmail_signup';
// Google Client Configuration
$gClient = new Google_Client();
$gClient->setApplicationName('99rightdeals');
$gClient->setClientId($clientId);
$gClient->setClientSecret($clientSecret);
$gClient->setRedirectUri($redirectUrl);
$google_oauthV2 = new Google_Oauth2Service($gClient);
if (isset($_REQUEST['code'])) {
$gClient->authenticate();
$this->session->set_userdata('token', $gClient->getAccessToken());
redirect($redirectUrl);
}
$token = $this->session->userdata('token');
if (!empty($token)) {
$gClient->setAccessToken($token);
}
if ($gClient->getAccessToken()) {
$userProfile = $google_oauthV2->userinfo->get();
// Preparing data for database insertion
$userData['oauth_provider'] = 'google';
$userData['oauth_uid'] = $userProfile['id'];
$userData['first_name'] = $userProfile['given_name'];
$userData['last_name'] = $userProfile['family_name'];
$userData['email'] = $userProfile['email'];
$userData['locale'] = $userProfile['locale'];
//$userData['profile_url'] = $userProfile['link'];
//$userData['picture_url'] = $userProfile['picture'];
}
$already = $this->signup_model->onloadgmail_already($userData['oauth_uid']);
if ($already == 1) {
redirect('/');
}
$data = array("title" => "Classifieds", "content" => "gmailsignup", 'gmail_data' => $userData);
if ($this->input->post("submit")) {
$already = $this->signup_model->gmail_already();
if ($already == 1) {
redirect('/');
} else {
$this->signup_model->gmail_create();
redirect('/');
}
}
$this->load->view("classified_layout/inner_template", $data);
}
示例11: index
public function index()
{
$this->load->helper('url');
//For load css from config file
$ci =& get_instance();
$header_js = $ci->config->item('css');
// Include two files from google-php-client library in controller
require_once APPPATH . "libraries/google-api-php-client-master/src/Google/autoload.php";
require_once APPPATH . "libraries/google-api-php-client-master/src/Google/Client.php";
require_once APPPATH . "libraries/google-api-php-client-master/src/Google/Service/Oauth2.php";
// Store values in variables from project created in Google Developer Console
$client_id = '180391628117-hf4di0a3l0aaq10c6h933n97p4e1lb2m.apps.googleusercontent.com';
$client_secret = 'Eg_i_sihLL5E5FMGTnyKSVXK';
$redirect_uri = 'http://citest.local.com/index.php/login';
$simple_api_key = 'AIzaSyCSS5nGOzy7OcuSvSMwblVRRPZ9_TFIDnM';
// Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("PHP Google OAuth Login Example");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($simple_api_key);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
// Send Client Request
$objOAuthService = new Google_Service_Oauth2($client);
// Add Access Token to Session
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// Set Access Token to make Request
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
// Get User Data from Google and store them in $data
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
//Save google login user data in database
$saveData = array('name' => $userData['name'], 'email' => $userData['email'], 'gender' => $userData['gender']);
$this->user_model->saveUserData($saveData);
$data['userData'] = $userData;
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
$data['authUrl'] = $authUrl;
}
//Load css file added in config file
$str = '';
foreach ($header_js as $key => $val) {
$str .= '<link rel="stylesheet" href="' . base_url() . 'css/' . $val . '" type="text/css" />' . "\n";
}
$data['css'] = $str;
// Load view and send values stored in $data
$this->load->view('google_authentication', $data);
}
示例12: index
public function index()
{
// パスが通っていなければ設定
$path = 'http://192.168.99.21/app/Vendor/google-api-php-client/src';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
App::import('Vendor', 'Google_Client', array('file' => 'google-api-php-client/src/Google/Client.php'));
App::import('Vendor', 'Google_Service', array('file' => 'google-api-php-client/src/Google/Service.php'));
App::import('Vendor', 'Google_Service_Model', array('file' => 'google-api-php-client/src/Google/Model.php'));
App::import('Vendor', 'Google_Service_Collection', array('file' => 'google-api-php-client/src/Google/Collection.php'));
App::import('Vendor', 'Google_Service_Resource', array('file' => 'google-api-php-client/src/Google/Service/Resource.php'));
App::import('Vendor', 'Google_Service_Analytics', array('file' => 'google-api-php-client/src/Google/Service/Analytics.php'));
// Google Developers Consoleで作成されたクライアントID
define('CLIENT_ID', '3274760987-rec90linuevn0ahdi5ck5212gg54m3ur.apps.googleusercontent.com');
// Google Developers Consoleで作成されたクライアントシークレット
define('CLIENT_SECRET', 'F_aDjo5IqA2Zn4Dz7gA4sgAm');
// Google Developers Consoleで作成されたリダイレクトURI
define('REDIRECT_URI', 'http://' . $_SERVER['HTTP_HOST'] . '/analytics');
$client = new Google_Client();
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri(REDIRECT_URI);
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$analytics = new Google_Service_Analytics($client);
// 認証後codeを受け取ったらセッション保存
if (isset($this->request->query['code'])) {
$client->authenticate($this->request->query['code']);
$this->Session->write('token', $client->getAccessToken());
$this->redirect('http://' . $_SERVER['HTTP_HOST'] . '/analytics');
}
if ($this->Session->check('token')) {
$client->setAccessToken($this->Session->read('token'));
}
if ($client->getAccessToken()) {
$start_date = date('Y-m-d', strtotime('- 10 day'));
$end_date = date('Y-m-d');
// GoogleAnalyticsの「アナリティクス設定」>「ビュー」>「ビュー設定」の「ビューID」
$view = '106133184';
// データ取得
$data = array();
$dimensions = 'ga:date';
$metrics = 'ga:visits';
$sort = 'ga:date';
$optParams = array('dimensions' => $dimensions, 'sort' => $sort);
$results = $analytics->data_ga->get('ga:' . $view, $start_date, $end_date, $metrics, $optParams);
if (isset($results['rows']) && !empty($results['rows'])) {
$data['Sample']['date'] = $results['rows'][0][0];
$data['Sample']['visits'] = $results['rows'][0][1];
}
pr($data);
} else {
$auth_url = $client->createAuthUrl();
echo '<a href="' . $auth_url . '">認証</a>';
}
exit;
}
示例13: GoogleUser
public function GoogleUser()
{
$client = new \Google_Client();
$client->setApplicationName(\SKT_GOOGLEOAUTH2_SETAPPLICATIONNAME);
// Visit https://code.google.com/apis/console?api=plus to generate your
// oauth2_client_id, oauth2_client_secret, and to register your oauth2_redirect_uri.
$client->setClientId(\SKT_GOOGLEOAUTH2_SETCLIENTID);
$client->setClientSecret(\SKT_GOOGLEOAUTH2_SETCLIENTSECRET);
$client->setRedirectUri(\SKT_GOOGLEOAUTH2_SETREDIRECTURI);
$client->setDeveloperKey(\SKT_GOOGLEOAUTH2_SETDEVELOPERKEY);
$oauth2 = new \Google_Oauth2Service($client);
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$redirect = \SITE_SERVER;
\CmsDev\Header\refresh::refreshNow(\filter_var($redirect, FILTER_SANITIZE_URL));
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout']) or \THIS_URL_REAL === 'UserLogout') {
unset($_SESSION['token']);
$client->revokeToken();
}
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get();
// These fields are currently filtered through the PHP sanitize filters.
// See http://www.php.net/manual/en/filter.filters.sanitize.php
$this->family_name = filter_var($user['family_name'], \FILTER_SANITIZE_STRING);
$this->name = filter_var($user['name'], \FILTER_SANITIZE_STRING);
$this->locale = filter_var($user['locale'], \FILTER_SANITIZE_STRING);
$this->gender = filter_var($user['gender'], \FILTER_SANITIZE_STRING);
$this->email = filter_var($user['email'], \FILTER_SANITIZE_EMAIL);
$this->link = filter_var($user['link'], \FILTER_SANITIZE_URL);
$this->given_name = filter_var($user['given_name'], \FILTER_SANITIZE_STRING);
$this->id = filter_var($user['id'], \FILTER_SANITIZE_STRING);
$this->verified_email = filter_var($user['verified_email'], \FILTER_SANITIZE_STRING);
if (isset($user['picture']) && $user['picture'] != '') {
$this->picture = filter_var($user['picture'], \FILTER_VALIDATE_URL);
} else {
$this->picture = \SKT_ACCESS_AVATAR;
}
$this->ClientAuth = 'Google';
$_SESSION['token'] = $client->getAccessToken();
$this->createAuthUrl = $client->createAuthUrl();
$this->Info = array('family_name' => HtmlSpecialChars($this->family_name), 'name' => HtmlSpecialChars($this->name), 'locale' => $this->locale, 'gender' => $this->gender, 'email' => $this->email, 'link' => $this->link, 'given_name' => HtmlSpecialChars($this->given_name), 'id' => $this->id, 'verified_email' => $this->verified_email, 'picture' => $this->picture, 'ClientAuth' => $this->ClientAuth, 'createAuthUrl' => $this->createAuthUrl);
\CmsDev\Security\UserRegister::checkAction($this->Info);
return true;
} else {
$this->createAuthUrl = $client->createAuthUrl();
new \CmsDev\Url\refer();
return false;
}
}
示例14: render
/**
* Render method
* @return var $output
*/
public function render()
{
session_start();
$OAUTH2_CLIENT_ID = $this->arguments['clientid'];
$OAUTH2_CLIENT_SECRET = $this->arguments['clientsecret'];
$client = new Google_Client();
$client->setClientId($OAUTH2_CLIENT_ID);
$client->setClientSecret($OAUTH2_CLIENT_SECRET);
$redirect = filter_var('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'], FILTER_SANITIZE_URL);
$client->setRedirectUri($redirect);
$youtube = new Google_YoutubeService($client);
if (isset($_GET['code'])) {
if (strval($_SESSION['state']) !== strval($_GET['state'])) {
die('The session state did not match.');
}
$client->authenticate();
$_SESSION['token'] = $client->getAccessToken();
header('Location: ' . $redirect);
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if ($client->getAccessToken()) {
try {
$channelsResponse = $youtube->channels->listChannels('contentDetails', array('mine' => 'true'));
$output = '';
foreach ($channelsResponse['items'] as $channel) {
$uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads'];
$playlistItemsResponse = $youtube->playlistItems->listPlaylistItems('snippet', array('playlistId' => $uploadsListId, 'maxResults' => 50));
$output .= "<h3>Videos in list {$uploadsListId}</h3><ul>";
foreach ($playlistItemsResponse['items'] as $playlistItem) {
$output .= sprintf('<li>%s (%s)</li>', $playlistItem['snippet']['title'], $playlistItem['snippet']['resourceId']['videoId']);
}
$output .= '</ul>';
}
} catch (Google_ServiceException $e) {
$output .= sprintf('<p>A service error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
} catch (Google_Exception $e) {
$output .= sprintf('<p>An client error occurred: <code>%s</code></p>', htmlspecialchars($e->getMessage()));
}
$_SESSION['token'] = $client->getAccessToken();
} else {
$state = mt_rand();
$client->setState($state);
$_SESSION['state'] = $state;
$authUrl = $client->createAuthUrl();
$output = '<h3>Authorization Required</h3><p>You need to <a href="' . $authUrl . '">authorize access</a> before proceeding.<p>';
}
return $output;
}
示例15: index
/**
* Default function to load all the google api settings from config file
* @return type
*/
public function index()
{
$client_id = $this->config->item('google_client_id');
$client_secret = $this->config->item('google_client_secret');
$redirect_uri = $this->config->item('google_redirect_uri');
$api_key = $this->config->item('google_api_key');
$hosted_domain = $this->config->item('google_allow_domain');
// Create Client Request to access Google API
$client = new Google_Client();
$client->setApplicationName("PHP Google OAuth Login Example");
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->setDeveloperKey($api_key);
$client->setHostedDomain($hosted_domain);
$client->addScope("https://www.googleapis.com/auth/userinfo.email");
// Send Client Request
$objOAuthService = new Google_Service_Oauth2($client);
// Add Access Token to Session
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
// Set Access Token to make Request
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
}
// Get User Data from Google and store them in $data
if ($client->getAccessToken()) {
$userData = $objOAuthService->userinfo->get();
$data['userData'] = $userData;
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
$data['authUrl'] = $authUrl;
}
if (isset($authUrl)) {
$this->load->view('login', $data);
} else {
$this->load->model('authentication');
//add the google data in database if not exists
$this->authentication->addGoogleCredentials($userData);
$user_email = $this->session->userdata('user_email');
$this->authentication->checkUserRole($user_email);
$forward_to = $this->session->userdata('user_role');
//redirect to page as per the role
redirect($forward_to . '/landing');
}
}