I got a problem with Gmail API service account, I would like to get my personal email from Gmail API without ask for verifying Gmail account and password. Exactly it could be interested to get them from my back-end code.
I have tried to implement this function but it was not worked.
public function list_email()
{
$this->load->library('google');
$client = new Google_Client();
$service = new Google_Service_Gmail($client);
$client->setApplicationName('airxpress-message-api');
$client_email = '867003685660-dk6896nclmfdql86cudt65q2c06f8ooa#developer.gserviceaccount.com';
$private_key = file_get_contents(base_url().G_API.'p12/airxpress-message-api-45eb6393e620.p12');
$scopes = array('https://mail.google.com/');
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$credentials->sub = 'notifications-vd#gmail.com';
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired())
{
$client->getAuth()->refreshTokenWithAssertion();
}
$messages = array();
try
{
$opt_param['labelIds'] = 'INBOX';
$opt_param['q'] = 'subject:"reservation request"';
$messagesResponse = $service->users_messages->listUsersMessages('me', $opt_param);
if ($messagesResponse->getMessages())
{
$messages = array_merge($messages, $messagesResponse->getMessages());
}
}
catch (Exception $e)
{
print 'An error occurred: ' . $e->getMessage();
}
print_r($messages);
}
I met this message 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." }''
So, I have gotten the reference from :
https://developers.google.com/api-client-library/php/auth/service-accounts
Could anyone tell me how to solve it?
Related
I am working on google drive api by using PHP. I am facing an error while using this drive api. I am using google api client library "google/apiclient ^2.0". I am trying to user login with google authentication and view all files available in drive for this purpose, i am using this library but it's showing error:
Notice: Undefined property: Google_Client::$files in
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php on line 31
Fatal error: Uncaught Error: Call to a member function listFiles() on
null in /Applications/XAMPP/xamppfiles/htdocs/google_app/index.php:31
Stack trace: #0
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php(55):
retrieveAllFiles(Object(Google_Client)) #1 {main} thrown in
/Applications/XAMPP/xamppfiles/htdocs/google_app/index.php on line 31
include_once 'vendor/autoload.php';
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
$client = new Google_Client();
$client->setAuthConfig('client_secrets.json');
$client->setAccessType("offline"); // offline access
//$client->setIncludeGrantedScopes(true); // incremental auth
$client->addScope(Google_Service_Drive::DRIVE_METADATA_READONLY);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
}
$service = new Google_service_Device();
echo retrieveAllFiles($service );
Actually i am trying to retrieve all files in my google drive with my file id and after that set status auto publish of specific files. Please help me to get rid of this error.
Thanks in advance.
"Daily limit for unauthenticated Use Exceeded"
Means that you are making a request without properly authenticating your script. there is probably something up with your fetchAccessTokenWithAuthCode.
You might consider something long these lines
function getOauth2Client() {
try {
$client = buildClient();
// Set the refresh token on the client.
if (isset($_SESSION['refresh_token']) && $_SESSION['refresh_token']) {
$client->refreshToken($_SESSION['refresh_token']);
}
// If the user has already authorized this app then get an access token
// else redirect to ask the user to authorize access to Google Analytics.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
// Set the access token on the client.
$client->setAccessToken($_SESSION['access_token']);
// Refresh the access token if it's expired.
if ($client->isAccessTokenExpired()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$client->setAccessToken($client->getAccessToken());
$_SESSION['access_token'] = $client->getAccessToken();
}
return $client;
} else {
// We do not have access request access.
header('Location: ' . filter_var( $client->getRedirectUri(), FILTER_SANITIZE_URL));
}
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Code ripped from my sample project oauth2php
Undefined property Google_Client
Means you havent properly declared the google client
Uncaught Error: Call to a member function listFiles() on null in
what happens if you remove $parameters and just call $service->files->listFiles();
I am doing a very basic test of Gmail API using PHP. I am using the code supplied by Google (after a successful authorization via OAuth followed by a successful -- code 200 -- test run on the API workbench. My error is:
PHP Fatal error: Call to a member function listUsersMessages() on null
The line that fails:
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
The full Code:
$userId = 'my gmail id';
$service = 'my api client id, for example,12356686375';
$messages = listMessages($service,$userId);
/**
* Get list of Messages in user's mailbox.
*
* #param Google_Service_Gmail $service Authorized Gmail API instance.
* #param string $userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* #return array Array of Messages.
*/
function listMessages($service, $userId) {
$pageToken = NULL;
$messages = array();
$opt_param = array();
do {
try {
if ($pageToken) {
$opt_param['pageToken'] = $pageToken;
}
$messagesResponse = $service->users_messages->listUsersMessages($userId, $opt_param);
if ($messagesResponse->getMessages()) {
$messages = array_merge($messages, $messagesResponse->getMessages());
$pageToken = $messagesResponse->getNextPageToken();
}
} catch (Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
} while ($pageToken);
foreach ($messages as $message) {
print 'Message with ID: ' . $message->getId() . '<br/>';
}
return $messages;
}
As mentioned by #Morfinismo, $service variable should have the Gmail service initialized and not the client id.
It should be:
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Gmail($client);
You may follow this quickstart.
I a trying to get the latest emails from my GMAIL inbox via the GMAIL REST API v2 and using a service account key (a solution for server to server communication). However, I get the following error:
{ "error": "invalid_scope", "error_description": "Empty or missing scope not allowed." }
Below is my PHP code. I have used composer to install the google API PHP client.
Has anyone encountered and solved this issue?
<?php
require_once 'vendor/autoload.php';
$scopes = array('https://www.googleapis.com/auth/gmail.readonly');
$client = new Google_Client();
$client->setAuthConfig('serviceaccount-xxxxxxxxx.json');
try{
$service = new Google_Service_Gmail($client);
$opt_param['maxResults'] = 5; // Return Only 5 Messages
$opt_param['labelIds'] = 'INBOX'; // Only show messages in Inbox
$messages = $service->users_messages->listUsersMessages('me',$opt_param);
$list = $messages->getMessages();
var_dump($list);
} catch (Exception $e) {
print($e->getMessage());
}
?>
I try to use Google API PHP client to make my application use its Google Drive account in offline way, because I dont want my application to redirect every time to google for getting authorisation.
So when I connect for the first time and recieve credentials with access_token and refresh_token I backup it and try to use it every time.
Problem is that it works till expiration and than , when API client tries to refresh acces token I'm keep getting this error:
Error refreshing the OAuth2 token, message: '{ "error" : "invalid_request", "error_description" : "Client must specify either client_id or client_assertion, not both" }
My stored credentials are in json form:
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"XXX,"created":1406537500}
My code (taken from Google tutorials with some changes):
function exchangeCode($authorizationCode) {
try {
$client = new Google_Client();
$client->setClientId(self::$clientId);
$client->setClientSecret(self::$clientSacred);
$client->setRedirectUri(self::getRedirectURI());
$_GET['code'] = $authorizationCode;
return $client->authenticate();
} catch (Google_AuthException $e) {
echo 'An Google_AuthException occurred: ' . $e->getMessage();
throw new CodeExchangeException(null);
}
}
function getCredentials($authorizationCode, $state='') {
$emailAddress = '';
try {
$credentials = self::exchangeCode($authorizationCode);
$credentialsArray = json_decode($credentials, true);
if (isset($credentialsArray['refresh_token'])) {
self::storeCredentials($credentials);
return $credentials;
} else {
$credentials = self::getStoredCredentials();
$credentialsArray = json_decode($credentials, true);
if ($credentials != null &&
isset($credentialsArray['refresh_token'])) {
return $credentials;
}
}
} catch (CodeExchangeException $e) {
print 'An CodeExchangeException occurred during code exchange.';
$e->setAuthorizationUrl(self::getAuthorizationUrl($emailAddress, $state));
throw $e;
} catch (NoUserIdException $e) {
print 'No e-mail address could be retrieved.';
}
$authorizationUrl = self::getAuthorizationUrl($emailAddress, $state);
throw new NoRefreshTokenException($authorizationUrl);
}
function buildService($credentials) {
$apiClient = new Google_Client();
$apiClient->setUseObjects(true);
$apiClient->setAccessToken($credentials);
return new Google_DriveService($apiClient);
}
function test()
{
$credentials = self::getStoredCredentials();
if ( empty($credentials) )
{
if (!isset($_GET["code"]))
{
header("location:".self::getAuthorizationUrl("xxx#gmail.com", ''));
die();
}
$credentials = self::getCredentials($_GET["code"]);
echo "NEW: ".$credentials;
}
else
{
echo "STORED: ".$credentials;
}
$service = self::buildService($credentials);
}
The error happends in buildService method when its client object tries to refresh based on credentials passed.
I'm making a simple request using the following code sample below.
It seems I'm not the only one getting this error, and I haven't been able to find any solutions. It seems self explanatory, but how is it solved?
This is the exact error I'm getting:
Error calling GET https://www.googleapis.com/storage/v1beta1/b/eggs: (403) Access Not Configured
And The Code:
require_once 'google/src/Google_Client.php';
require_once 'google/src/contrib/Google_StorageService.php';
define("CLIENT_ID", 'hidden');
define("SERVICE_ACCOUNT_NAME", 'hidden');
define("KEY_FILE", 'hidden.p12');
define("PROJECT_ID", hidden);
$client = new Google_Client();
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/devstorage.full_control'),
$key)
);
$client->setClientId(CLIENT_ID);
$storageService = new Google_StorageService($client);
try
{
$bucket = $storageService->buckets->get('hidden');
}
catch (exception $e)
{
print $e->getMessage();
}