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();
}
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 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?
I want to copy Google Doc spreadsheet file.This code I am using
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
return $service->files->copy($originFileId, $copiedFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('myclientid');
$client->setClientSecret('myclient secret');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
copyFile($service,'my schema id','Copy Of Schema');
I am not able to get $service instance. SO I searched and get the above way to do but now it is giving 401 login required error.
Please help me
You need to check for sufficient authorization from the user
you need to generate authorization URL:
$authUrl = $client->createAuthUrl();
Redirect user to the authUrl
Make user paste the authorization code:
$authCode = trim(fgets(STDIN));
Authenticate
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
Once above it done, you have now authenticated the user with OAuth to access drive.
Reference: Click here
This is my code:
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'Google/Client.php';
require_once 'Google/Service/AdExchangeSeller.php';
$scriptUri = "http://example.com/some_seller_api.php";
$client_id = 'XXXXXX.apps.googleusercontent.com';
$service_account_name = 'XXXXXXXXX#developer.gserviceaccount.com';
$key_file_location = '/XXXXX/privatekey.p12';
$client = new Google_Client();
$client->setApplicationName("Example_app");
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
$service_account_name,
array('https://www.googleapis.com/auth/adexchange.seller.readonly'),
$key
);
$client->setAssertionCredentials($cred);
if($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$_SESSION['service_token'] = $client->getAccessToken();
$service = new Google_Service_AdExchangeSeller($client);
$acc = $service->adclients->listAdclients();
I do everything like in official manual and example from https://github.com/google/google-api-php-client/blob/master/examples/service-account.php
And i've got an error:
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "access_denied", "error_description" : "Requested client not authorized." }''
What am I doing wrong?
It appears that you haven't authorized your application with the target service. One of the OAuth2 steps is that your application (the one that's going to be accessing the service) needs to be "registered" (or authorized) with the target service. This is the way you will register what's the callback URL, etc.
Per your code, you are accessing the Ad Exchange Seller REST API. Open the following link and follow the step by step guide in order to fix the issue you are having:
https://developers.google.com/ad-exchange/seller-rest/getting_started#auth
Here is my redirect.php, i always get
'HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request. '
php code:
require_once 'Services/Soundcloud.php';
// create client object with app credentials
$client = new Services_Soundcloud('xxxxxxxxxxxxxxxxxxxxxxx');
$client->setAccessToken($_GET['code']);
// make an authenticated call
$current_user = json_decode($client->get('me'));
print $current_user->username;
Any idea?
thanks
You need to set clientID, clientSecret and redirectURI arguments when initializing new Services_Soundcloud.
Your code should look like this:
index.php
<?php
// create client object with app credentials
include('Services/Soundcloud.php');
$client = new Services_Soundcloud('....', '....', 'http://my.redirect.com/url.php');
$authorizeUrl = $client->getAuthorizeUrl();
?>
Connect with SoundCloud
And the redirect url:
<?php
require_once('Services/Soundcloud.php');
// create client object with app credentials
$client = new Services_Soundcloud('.....', '.....', 'http://my.redirect.com/url.php');
try {
$accessToken = $client->accessToken($_GET['code']);
try {
$me = json_decode($client->get('me'), true);
var_dump($me);
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
var_dump($e->getMessage());
exit();
}
} catch (Services_Soundcloud_Invalid_Http_Response_Code_Exception $e) {
var_dump($e->getMessage());
exit();
}
?>
You can get the clientId and clientSecret from the developers page
Also you can checkout the documentation for proper examples in PHP, Python, Ruby and JS
You can check the code above on this link:
soundcloud.itnews-bg.com/