I'm currently working with Google_Client api and want to fetch User Name, Phone, Email and User address.
I set-up these scopes:
'https://www.googleapis.com/auth/plus.login',
'https://www.googleapis.com/auth/user.birthday.read',
'https://www.googleapis.com/auth/user.addresses.read',
'https://www.googleapis.com/auth/user.emails.read',
'https://www.googleapis.com/auth/user.phonenumbers.read'
And when I click on the login with google it asks the correct permissions, and then I fetch the access token with the code provided by Google.
After getting the token I request for people_service and profile data like this:
$token = $this->client->fetchAccessTokenWithAuthCode($_GET['code']);
$people_service = new \Google_Service_PeopleService($this->client);
$profile = $people_service->people->get(
'people/me',
array('personFields' => 'addresses,birthdays,emailAddresses,phoneNumbers')
);
It returns a Google_Service_PeopleService_Person object.
But when I try to use method on it like getPhoneNumbers() it returns a Call to undefined method Google_Service_PeopleService_Person::getNames() error.
What is the problem and what can I do?
You do not show how exactly are you setting the scope, and the error might be related to that.
Doing this, I get the correct results:
$scopes = [
Google_Service_PeopleService::USER_ADDRESSES_READ,
Google_Service_PeopleService::USER_BIRTHDAY_READ,
Google_Service_PeopleService::PLUS_LOGIN,
Google_Service_PeopleService::USER_EMAILS_READ,
Google_Service_PeopleService::USER_PHONENUMBERS_READ,
];
$client = new Google_Client();
$client->setApplicationName('People API PHP Quickstart');
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// set the scope
$client->setScopes($scopes);
/* ... actual authentication. */
$service = new Google_Service_PeopleService( $client );
$optParams = [
'personFields' => 'names,emailAddresses,addresses,phoneNumbers',
];
$me = $service->people->get( 'people/me', $optParams );
print_r( $me->getNames() );
print_r( $me->getEmailAddresses() );
print_r( $me->getBirthdays() );
print_r( $me->getPhoneNumbers() );
Related
I currently modify my php script using namespace. I've done with the scripts but there are problem with Google API package
// create Client Request to access Google API
$client = new \Google_Client(); => THIS ONE WORKS
$client->setClientId($clientID);
$client->setClientSecret($clientSecret);
$client->setRedirectUri($redirectUri);
$client->addScope("email");
$client->addScope("profile");
$accessToken = $key;
// Get $id_token via HTTPS POST.
try{
$arrToken = $client->setAccessToken($accessToken);
// get profile info
$google_oauth = new \Google_Service_Oauth2($client); => IT DOESNT
$google_account_info = $google_oauth->userinfo->get();
$checkEmail = $google_account_info->email;
$name = $google_account_info->name;
$googleId = $google_account_info->id;
}
Here is the error
Undefined type 'Google_Service_Oauth2' intelephense(1009)
If I do not use namespace, it has no problem. This one really weird.
I am creating google client instance and authenticating it once and fetching required data. Afterwards if I want to use that same instance of Google client for some other service , how can I achieve it ?
webmasterMain route is my redirect uri registered in google webmaster .
public function webmasterMain(Request $request)
{
$requestData = $request->all();
if ($request->isMethod('POST') || isset($requestData['code'])) {
$google_redirect_url = env('APP_URL') . '/user/webmasterMain';
$gClient = new \Google_Client();
$gClient->setAccessType("offline");// to get refresh token after expiration of access token
$gClient->setIncludeGrantedScopes(true); // incremental auth
$gClient->setApplicationName(config('services.google.app_name'));
$gClient->setClientId(config('services.google.client_id'));
$gClient->setClientSecret(config('services.google.client_secret'));
$gClient->setRedirectUri($google_redirect_url);
$gClient->setDeveloperKey(config('services.google.api_key'));
$gClient->setScopes(array(
'https://www.googleapis.com/auth/plus.me',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/webmasters.readonly',
'https://www.googleapis.com/auth/webmasters',
));
$google_oauthV2 = new \Google_Service_Oauth2($gClient);
if ($request->get('code')) {
$gClient->authenticate($request->get('code'));
$request->session()->put('token', $gClient->getAccessToken());
}
if ($request->session()->get('token')) {
$gClient->setAccessToken($request->session()->get('token'));
}
if ($gClient->getAccessToken()) {
$inst = new Google_Service_Webmasters($gClient);
$res = $inst->sites->listSites();
$sites = $res->getSiteEntry();
$siteUrl = [];
foreach ($sites as $key => $site) {
$siteUrl = array_add($siteUrl, $key, ['site_name'=>$site['siteUrl'], 'site_permission_level' => $site['permissionLevel']]);
}
$sites = (((array)$siteUrl));
return view('User::webmasterMain')->with(['data' => $sites]);
} else {
//For Guest user, get google login url
$authUrl = $gClient->createAuthUrl();
return redirect()->to($authUrl);
}
}
return view('User::webmasterMain');
}
Now suppose I want to get the authenticated $gClient for service like Google_Service_Webmasters_SearchAnalyticsQueryRequest , then how can I make $client = $gClient for this next request ?
public function query(Request $request){
//suppose $client is the same instance which was previously authenticated and stored in $gClient
$website = "http://example.com/";
$searchAnalytics = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest();
$searchAnalytics->setStartDate('2017-03-01');
$searchAnalytics->setEndDate('2017-03-31');
$searchAnalytics->setDimensions(['page']);
$searchAnalytics->setSearchType('web');
`$results = $client->searchanalytics->query($website, $searchAnalytics);`
return $results->getRows();
I got the answer , no need to save the instance or do anything but, follow this :
Create a Google Client Object.
At first time authenticating save the accessToken from google client object by getAccessToken().
Use the same access token and set Access token in this google client.
now you can use this google client object for any service.
First time authenticating:
$gClient = new \Google_Client();
//after authenticating
$request->session()->put('token', $gClient->getAccessToken());
Now we can use this access token in any google service call:
$gClient = new \Google_Client();
if ($request->session()->get('token')) {
$gClient->setAccessToken($request->session()->get('token'));
}
$client = new Google_Service_Webmasters($gClient);
I have a Wordpress site (running PHP) that needs to display its own analytics data to visitors using the google-api. I want to create the charts in Javascript, so I need to fetch an auth token from the PHP code and then pass that to the Javascript code. I can't figure out how to get the auth token.
So far, I have code similar to this working using my service account:
https://github.com/google/google-api-php-client/blob/master/examples/service-account.php
My code:
$client = new Google_Client();
$client->setAuthConfig($credentialsFilePath);
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$client->setApplicationName("GoogleAnalytics");
$analytics = new Google_Service_Analytics($client);
$ga = $analytics->data_ga;
$start = date('Y-m-d', strtotime('-7 days'));
$end = date('Y-m-d');
$views = $ga->get('ga:'.$myAnalyticsId,
$start,
$end,
'ga:pageviews,ga:sessions,ga:newUsers',
array(
'dimensions' => 'ga:date',
'sort' => 'ga:date'
));
This all works, and I'm able to connect to Google_Service_Analytics and fetch analytics data. However, I can't figure out how to fetch a service access token using my credentials, that I can hand off to the Javascript code so I can use the Google Analytics API from Javascript.
This doesn't work:
$token = $client->getAccessToken();
Token just ends up being null. What do I need to do to fetch a token?
Here is the working code for me.
The service account has a different type of process for generating access token.
It is not following oauth client api.
//include_once 'vendor/autoload.php';
$credentialsFilePath = 'test.json';
$client = new Google_Client();
$client->setAuthConfig($credentialsFilePath);
$client->addScope('https://www.googleapis.com/auth/analytics.readonly');
$client->setApplicationName("GoogleAnalytics");
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
print_r($token);
$accessToken = $token['access_token'];
Figured this out:
$client->refreshTokenWithAssertion();
$token = $client->getAccessToken();
$accessToken = $token['access_token'];
First answer still works in 2021 (Thanks!), but a used function is deprecated (still available though)
This worked for me
public function getToken() {
$client = new Client(); // use Google\Client;
$client->setAuthConfig('securejsonfile.json');
$client->addScope('https://www.googleapis.com/auth/cloud-platform');
$client->setApplicationName('appname');
$client->fetchAccessTokenWithAssertion();
return $client->getAccessToken(); //array
}
I want to show my google drive into website. Which means if anybody use my website can see google drive files and folder without login. Here is some code which i am trying to implement.
include_once 'google-api-php-client/src/Google/autoload.php';
$scopes = array( 'https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/drive.appdata',
'https://www.googleapis.com/auth/drive.file','https://www.googleapis.com/auth/drive.metadata','https://www.googleapis.com/auth/drive.metadata.readonly','https://www.googleapis.com/auth/drive.photos.readonly','https://www.googleapis.com/auth/drive.readonly');
/**
* Create AssertionCredentails object for use with Google_Client
*/
$creds = new Google_Auth_AssertionCredentials(
$serviceAccountName,
$scopes,
file_get_contents($keyFile)
);
$creds->sub = $delegatedAdmin;
/**
* Create Google_Client for making API calls with
*/
$client = new Google_Client();
$client->setApplicationName($appName);
$client->setClientId($clientId);
$client->setAssertionCredentials($creds);
/**
* Get an instance of the Directory object for making Directory API related calls
*/
$service = new Google_Service_Drive($client);
$optParams = array(
'pageSize' => 10,
'fields' => "nextPageToken, files(id, name)"
);
$results = $service->files->listFiles($optParams);
print_r($results); exit;
/**
Can anybody tel me how to achieve this. I am getting this error
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "unauthorized_client", "error_description" : "Unauthorized client or scope in request." }
You need to add
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
after
$client->setAssertionCredentials($creds);
I am getting the following error when attempting to access my Google Analytics data: exception 'Google_Service_Exception' with message 'Error calling GET ...my query...': (401) login required
I'm not sure how to fix this, and I've already spent hours trying to set this up with no success.
Here's my code:
$client = new \Google_Client();
$client->setApplicationName("My App");
$client->setDeveloperKey('my API key');
$analytics = new \Google_Service_Analytics($client);
$OBJresult = $analytics->data_ga->get(
'ga:myprofileid' .,
'2012-01-01',
date("Y-m-d"),
'ga:visits',
array(
'filters' => 'ga:pagePath==/home',
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'sort' => '-ga:pageviews'
)
);
If you are only accessing your own data then you should go with a service account. If you want to be able to login and see other peoples data then you should use Oauth2.
service account Example:
<?php
require_once 'Google/autoload.php';
session_start();
/************************************************
The following 3 values an befound in the setting
for the application you created on Google
Developers console. Developers console.
The Key file should be placed in a location
that is not accessable from the web. outside of
web root. web root.
In order to access your GA account you must
Add the Email address as a user at the
ACCOUNT Level in the GA admin.
************************************************/
$client_id = '[Your client id]';
$Email_address = '[YOur Service account email address Address]';
$key_file_location = '[Locatkon of key file]';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$key = file_get_contents($key_file_location);
// seproate additional scopes with a comma
$scopes ="https://www.googleapis.com/auth/analytics.readonly";
$cred = new Google_Auth_AssertionCredentials($Email_address,
array($scopes),
$key);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$service = new Google_Service_Analytics($client);
//Adding Dimensions
$params = array('dimensions' => 'ga:userType');
// requesting the data
$data = $service->data_ga->get("ga:89798036", "2014-12-14", "2014-12-14", "ga:users,ga:sessions", $params );
?>
<html>
Results for date: 2014-12-14<br>
<table border="1">
<tr>
<?php
//Printing column headers
foreach($data->getColumnHeaders() as $header){
print "<td><b>".$header['name']."</b></td>";
}
?>
</tr>
<?php
//printing each row.
foreach ($data->getRows() as $row) {
print "<tr><td>".$row[0]."</td><td>".$row[1]."</td><td>".$row[2]."</td></tr>";
}
?>
<tr><td colspan="2">Rows Returned <?php print $data->getTotalResults();?> </td></tr>
</table>
</html>
Helpful Links:
Code ripped from Service account tutorial
Google Analytics oauth2 tutorial
Google's new official tutorial Hello Analytics php
The code shown does not authenticate anywhere.
I am not an expert on this API, but according to this link you are missing some of the following options.
$client = new Google_Client();
$client->setAccessType('online'); // default: offline
$client->setApplicationName('My Application name');
$client->setClientId('INSERT HERE');
$client->setClientSecret('INSERT HERE');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('INSERT HERE'); // API key
The accepted answer didn't work for my service account. What worked instead:
Create a service account at IAM & Admin panel. Make sure to get the key file in JSON format.
Download that key file to a location reachable from your script (but not reachable from the Web!)
Run the following code:
$service_url = "https://www.googleapis.com/auth/analytics.readonly";
$client = new Google_Client();
$client->setAuthConfigFile($key_file_location); // path to your json key file
$client->addScope($service_url); // URL to the service you're planning to use
// Run your queries here
DalmTo's answer did the trick for me, but if you don't want to hardcode $client_id and such you can simplify it a bit:
public function __construct() {
$this->client = new Google_Client();
$credentials = $this->client->loadServiceAccountJson(__DIR__.'/../../google-service-account.json', [Google_Service_Calendar::CALENDAR]);
$this->client->setAssertionCredentials($credentials);
if($this->getAuth()->isAccessTokenExpired()) {
$this->getAuth()->refreshTokenWithAssertion($credentials);
}
}
/**
* #return \Google_Auth_OAuth2
*/
public function getAuth() {
return $this->client->getAuth();
}
Where google-service-account.json is the key file they give you when you create your service account. It looks like this:
{
"type": "service_account",
"project_id": "xxxxxxxxxx",
"private_key_id": "xxxxxxxxxxxxxxxxxxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nxxxxxxxxxxxxxxx\n-----END PRIVATE KEY-----\n",
"client_email": "xxxxxxxxxx#xxxxxxx.iam.gserviceaccount.com",
"client_id": "xxxxxxxxxxxxxxx",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/xxxxxxxx.iam.gserviceaccount.com"
}