Google Analytic API insufficientPermissions 403 error - php

I use Google Analytics Managment API Account User Links: list
I'm trying to get the account user list...
try {
$accountUserlinks = $analytics->management_accountUserLinks->listManagementAccountUserLinks('123456');
}
catch (apiServiceException $e) {
print 'There was an Analytics API service error ' . $e->getCode() . ':' . $e->getMessage();
} catch (apiException $e) {
print 'There was a general API error ' . $e->getCode() . ':' . $e->getMessage();
}
I get the following error
{"error":{"errors":
[{"domain":"global","reason":"insufficientPermissions","message":"
Insufficient Permission"}],"code":403,"message":"Insufficient Permission"}}
In the Google Analytics I set all permissions
Edit Collaborate Read & Analyze Manage Users
For example:
$analytics->management_goals ->listManagementGoals - work
$analytics->management_accountUserLinks>listManagementAccountUserLinks - get 403 insufficientPermissions error
How to fix it?
AnalyticsServiceProvider
class AnalyticsServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application events.
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/analytics.php' =>
config_path('analytics.php'),
]);
}
/**
* Register the service provider.
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/analytics.php',
'analytics');
$this->app->bind(AnalyticsClient::class, function () {
$analyticsConfig = config('analytics');
return
AnalyticsClientFactory::createForConfig($analyticsConfig);
});
$this->app->bind(Analytics::class, function () {
$analyticsConfig = config('analytics');
$this->guardAgainstInvalidConfiguration($analyticsConfig);
$client = app(AnalyticsClient::class);
return new Analytics($client, $analyticsConfig['view_id']);
});
$this->app->alias(Analytics::class, 'laravel-analytics');
}
protected function guardAgainstInvalidConfiguration(array
$analyticsConfig = null)
{
if (empty($analyticsConfig['view_id'])) {
throw InvalidConfiguration::viewIdNotSpecified();
}
if
(is_array($analyticsConfig['service_account_credentials_json'])) {
return;
}
if (!
file_exists($analyticsConfig['service_account_credentials_json']))
{
throw InvalidConfiguration::credentialsJsonDoesNotExist
($analyticsConfig['service_account_credentials_json']);
}
}
}
analytics.php
return [
/*
* The view id of which you want to display data.
*/
'view_id' => env('ANALYTICS_VIEW_ID'),
/*
* Path to the client secret json file. Take a look at the README
of this package
* to learn how to get this file. You can also pass the credentials
as an array
* instead of a file path.
*/
'service_account_credentials_json' =>
storage_path('app/analytics/service-account-credentials.json'),
/*
* The amount of minutes the Google API responses will be cached.
* If you set this to zero, the responses won't be cached at all.
*/
'cache_lifetime_in_minutes' => 60 * 24,
/*
* Here you may configure the "store" that the underlying
Google_Client will
* use to store it's data. You may also add extra parameters that
will
* be passed on setCacheConfig (see docs for google-api-php-
client).
*
* Optional parameters: "lifetime", "prefix"
*/
'cache' => [
'store' => 'file',
],
];
service-account-credentials
{
"type": "service_account",
"project_id": "buyers-analytic",
"private_key_id": "*****",
"private_key": "-----BEGIN PRIVATE KEY-----\*******",
"client_email": "buyeranalytic#buyers-
analytic.iam.gserviceaccount.com",
"client_id": "***********",
"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/***.iam.gservi
ceaccount.com"
}

"error":{
"errors":[
{
"domain":"global",
"reason":"insufficientPermissions",
"message":" Insufficient Permission"
}
],
"code":403,
"message":"Insufficient Permission"
}
Means exactly that you do not have permission to do what it is you are trying to do.
Account User Links: list requires the following scopes
https://www.googleapis.com/auth/analytics.manage.users
https://www.googleapis.com/auth/analytics.manage.users.readonly
Goals.list requires the following scopes.
https://www.googleapis.com/auth/analytics
https://www.googleapis.com/auth/analytics.edit
https://www.googleapis.com/auth/analytics.readonly
You need to fix your authentication and request additional scopes of the user in order to use the first method. Once you have added the additional scopes to your request you will then need to authenticate your user again.
Example:
function initializeAnalytics()
{
// Creates and returns the Analytics Reporting service object.
// Use the developers console and download your service account
// credentials in JSON format. Place them in this directory or
// change the key file location if necessary.
$KEY_FILE_LOCATION = __DIR__ . '/service-account-credentials.json';
// Create and configure a new client object.
$client = new Google_Client();
$client->setApplicationName("Hello Analytics Reporting");
$client->setAuthConfig($KEY_FILE_LOCATION);
$client->setScopes(['https://www.googleapis.com/auth/analytics.readonly', 'https://www.googleapis.com/auth/analytics.manage.users.readonly']);
$analytics = new Google_Service_Analytics($client);
return $analytics;
}
I am not sure where you got the code you are using from. I would recommend using googles official samples. Service accounts need to have their access granted at the account level. I have shown added an example that shows how to set the scopes. You just need to find where in your code you are setting your scopes I cant see it in anything you have posted so far. I also have some samples that i have created ServiceAccount.php

Try inserting the Account ID found in the Analytics Account Settings instead of "123456" in this line of code:
... management_accountUserLinks->listManagementAccountUserLinks('**123456**');
Also the Service Account needs to have access permissions on the account level.

Related

Issue with DocuSign sending Envelopes

I recently changed my DocuSign integration to use the JWT OAuth flow. To achieve this I have a few classes.
OAuth Client
<?php
namespace App\DocuSign;
use DocuSign\eSign\Client\ApiClient;
use DocuSign\eSign\Client\Auth\OAuth;
use DocuSign\eSign\Configuration;
use Exception;
use Illuminate\Support\Facades\Log;
/**
* Helper class to generate a DocuSign Client instance using JWT OAuth2.
*
* #see
*
*/
class OAuthClient
{
/**
* Create a new DocuSign API Client instance using JWT based OAuth2.
*/
public static function createApiClient()
{
$config = (new Configuration())->setHost(config('docusign.host'));
$oAuth = (new OAuth())->setOAuthBasePath(config('docusign.oauth_base_path'));
$apiClient = new ApiClient($config, $oAuth);
try {
$response = $apiClient->requestJWTUserToken(
config('docusign.integrator_key'),
config('docusign.user_id'),
config('docusign.private_key'),
'signature impersonation',
60
);
if ($response) {
$accessToken = $response[0]['access_token'];
$config->addDefaultHeader('Authorization', 'Bearer ' . $accessToken);
$apiClient = new ApiClient($config);
return $apiClient;
}
} catch (Exception $e) {
// If consent is required we just need to give the consent URL.
if (strpos($e->getMessage(), 'consent_required') !== false) {
$authorizationUrl = config('docusign.oauth_base_path') . '/oauth/auth?' . http_build_query([
'scope' => 'signature impersonation',
'redirect_uri' => config('docusign.redirect_url'),
'client_id' => config('docusign.integrator_key'),
'response_type' => 'code'
]);
Log::critical('Consent not given for DocuSign API', [
'authorization_url' => $authorizationUrl
]);
abort(500, 'Consent has not been given to use the DocuSign API');
}
throw $e;
}
}
}
Signature Client Service
<?php
namespace App\DocuSign;
use DocuSign\eSign\Api\EnvelopesApi;
use DocuSign\eSign\Client\ApiClient;
class SignatureClientService
{
/**
* DocuSign API Client
*/
public ApiClient $apiClient;
/**
* Create a new instance of our class.
*/
public function __construct()
{
$this->apiClient = OAuthClient::createApiClient();
}
/**
* Getter for the EnvelopesApi
*/
public function getEnvelopeApi(): EnvelopesApi
{
return new EnvelopesApi($this->apiClient);
}
}
Then, in my constructors where I want to use it I'm doing
/**
* Create a new controller instance
*/
public function __construct()
{
$this->clientService = new SignatureClientService();
$this->envelopesApi = $this->clientService->getEnvelopeApi();
}
Finally, I use it like so
$envelopeSummary = $this->envelopesApi->createEnvelope(config('docusign.api_account_id'), $envelopeDefinition);
But I get an error that reads
DocuSign\eSign\Client\ApiException: Error while requesting server,
received a non successful HTTP code [400] with response Body:
O:8:"stdClass":2:{s:9:"errorCode";s:21:"USER_LACKS_MEMBERSHIP";s:7:"message";s:60:"The
UserID does not have a valid membership in this Account.";} in
/homepages/45/d641872465/htdocs/sites/ita-portal/vendor/docusign/esign-client/src/Client/ApiClient.php:344
I researched this and this would imply that the user is not within the account, but they are. I also checked that this account owns the envelopes that I'm trying to send.
For reference I took inspiration for envelope sending from here: https://developers.docusign.com/docs/esign-rest-api/how-to/request-signature-template-remote/
What I think is happening is that the request is going to the wrong server or the wrong account.
I'd suggest using a packet analyser like Fiddler or Wireshark to log where your requests are headed (or just log the request within your application)
The auth URLs seem to be correct since you're not getting a 401 unauthorised error but the envelopes and other queries' must match the base URL located in your account under the Apps and Keys page. It would be of the form demo.docusign.net for our demo environment or xxx.docusign.net for our production environment

How to upload to google drive with service account and php

Down you can see my code and it uploads files to my google drive. Now I am trying to use service account to let the people to upload files to my Google drive without their google accounts (Visitors will submit html form with their file and my app will upload that file to my drive ). But I am stuck with it. Can not find even just one working example. Any ideas?
$client = new Google\Client();
$client->setAuthConfig('credentials.json');
$client->addScope(Google\Service\Drive::DRIVE);
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
$client->setRedirectUri($redirect_uri);
if (isset($_GET['code'])) {
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
$client->setAccessToken($token);
// store in the session also
$_SESSION['upload_token'] = $token;
// redirect back to the example
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
if (!empty($_SESSION['upload_token'])) {
$client->setAccessToken($_SESSION['upload_token']);
if ($client->isAccessTokenExpired()) {
unset($_SESSION['upload_token']);
}
} else {
$authUrl = $client->createAuthUrl();
}
echo $client->getAccessToken();
if ($_SERVER['REQUEST_METHOD'] == 'GET' && $client->getAccessToken()) {
// We'll setup an empty 1MB file to upload.
DEFINE("TESTFILE", 'test.jpg');
if (!file_exists(TESTFILE)) {
$fh = fopen(TESTFILE, 'w');
fseek($fh, 1024 * 1024);
fwrite($fh, "!", 1);
fclose($fh);
}
// This is uploading a file directly, with no metadata associated.
$file = new Google\Service\Drive\DriveFile();
$service = new Google_Service_Drive($client);
$file->setName("Hello World!");
$result = $service->files->create(
$file,
[
'data' => file_get_contents(TESTFILE),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'
]
);
$permissionService = new Google_Service_Drive_Permission();
$permissionService->role = "reader";
$permissionService->type = "anyone"; // anyone with the link can view the file
$service->permissions->create($result->id, $permissionService);
The following code will show you how to set up service account authorization.
Remember though the files will be uploaded to the service accounts drive account. If you want them uploaded to your personal drive account. You need to share a directory on your drive account with the service account. You do that though the web app like you would any other user, using the service account email address. Its the property that looks like an email.
You should just be able to remove the auth you have now and then use this. You will however need set the parents in the upload metadata to be that of that directory you want the fill uploaded to.
// Load the Google API PHP Client Library.
require_once __DIR__ . '/vendor/autoload.php';
// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');
/**
* Gets the Google client refreshing auth if needed.
* Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
* Initializes a client object.
* #return A google client object.
*/
function getGoogleClient() {
return getServiceAccountClient();
}
/**
* Builds the Google client object.
* Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
* Scopes will need to be changed depending upon the API's being accessed.
* array(Google_Service_Analytics::DRIVE)
* List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
* #return A google client object.
*/
function getServiceAccountClient() {
try {
// Create and configure a new client object.
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope(array(Google_Service_Analytics::DRIVE));
return $client;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
Doing something like this will then get you the same service object.
$service = new Google_Service_Drive(getGoogleClient());

Google API: 404 Domain not found

I am new to working with Google API but I have a project that requires me to access their domain to find a user's manager by email. Before I started on the code I wanted to set everything up so I followed the example file for PHP. I was able to get it to work but had some issues with refreshing the token once it expired and research pushed me towards using a Service Account, as this is a server cron script and I don't want to deal with any user interactions.
I created the Service Account, enabled G Suite Domain-wide Delegation, and added access for: https://www.googleapis.com/auth/admin.directory.user.readonly
I get a Google_Service_Exception with my script.
The response is:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "notFound",
"message": "Domain not found."
}
],
"code": 404,
"message": "Domain not found."
}
}
I am assuming this means it doesn't know the accounts domain but I don't see how I can resolve this. I assume that if this was a permissions issue, Google would tell me. I tried searching online but no luck as the issues I found were using a different method and the fixes weren't something that could be done on the Service Account. I am stuck right now so I hope a push in the right direction will get me on track.
This is the test script I am using:
<?php
require_once( __DIR__. '/vendor/autoload.php' );
define('CREDENTIALS_PATH', '/path/to/service_account.json');
define('SCOPES', implode(' ', array(
Google_Service_Directory::ADMIN_DIRECTORY_USER_READONLY)
));
date_default_timezone_set('America/New_York');
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName('TestingApp');
$client->setAuthConfig(CREDENTIALS_PATH);
$client->setScopes(SCOPES);
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Directory($client);
// Print the first 10 users in the domain.
$optParams = array(
'customer' => 'my_customer',
'maxResults' => 10,
'orderBy' => 'email',
);
$results = $service->users->listUsers($optParams);
if (count($results->getUsers()) == 0) {
print "No users found.\n";
} else {
print "Users:\n";
foreach ($results->getUsers() as $user) {
printf("%s (%s)\n", $user->getPrimaryEmail(),
$user->getName()->getFullName());
}
}
My service_account.json contains (cleaned obviously)
{
"type": "service_account",
"project_id": "PROJECT_ID",
"private_key_id": "PRIVATE_KEY_ID",
"private_key": "PRIVATE_KEY",
"client_email": "SERVICE_ACCOUNT_EMAIL.iam.gserviceaccount.com",
"client_id": "CLIENT_ID",
"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/SERVICE_ACCOUNT_IDENTIFIER.iam.gserviceaccount.com"
}
Thanks for any assistance on this.
Okay, this was a very easy step to overlook but it was an extremely simple fix.
The issue here was that the domain for the account was not identified. I was under the impression that the service account was already attached to the domain but that is not the case. So the fix is just one line of code to add to the client to set it to a user that is in the domain (for my case).
The fix for me was to add:
$client->setSubject('account#domain.com');
to my getClient method.
so now the method looks like:
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
function getClient() {
$client = new Google_Client();
$client->setApplicationName('TestingApp');
$client->setAuthConfig(CREDENTIALS_PATH);
$client->setScopes(SCOPES);
$client->setSubject('account#domain.com');
return $client;
}
I saw this mentioned in the API but it states it as optional. Hopefully this will help someone else too.
for me was the same error, but i needed to share my calendar with service account email (that found in json auth file). After that, error dissapeared.
For my case it was the domain value I passed with listUsers() function caused this error. Let's say my domain for GSuite is xyz.com and I tried with something like this
$dir = new \Google_Service_Directory($googleClient);
$dir->users->listUsers(array('domain' => 'abc.com', 'maxResults' => 500));
Instead I should use the correct domain name for value of the 'domain' like below.
$dir = new \Google_Service_Directory($googleClient);
$dir->users->listUsers(array('domain' => 'xyz.com', 'maxResults' => 500));

Google OAuth ,Error 401 invalid client

I am trying to login using google+ .But getting
That’s an error.
Error: invalid_client
The OAuth client was not found.
Request Details
access_type=offline
openid.realm=
scope=https://www.googleapis.com/auth/plus.login
origin=http://localhost
response_type=code permission
redirect_uri=storagerelay://http/localhost?id=auth929840
ss_domain=http://localhost
client_id={{ CLIENT_ID }}
I have double-checked the client id .Help would be appreciated
I have attached my index.php file.
<?php
/*
* Sample application for Google+ client to server authentication.
* Remember to fill in the OAuth 2.0 client id and client secret,
* which can be obtained from the Google Developer Console at
* https://code.google.com/apis/console
*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Note (Gerwin Sturm):
* Include path is still necessary despite autoloading because of the require_once in the libary
* Client library should be fixed to have correct relative paths
* e.g. require_once '../Google/Model.php'; instead of require_once 'Google/Model.php';
*/
set_include_path(get_include_path() . PATH_SEPARATOR . __DIR__ .'/vendor/google/apiclient/src');
require_once __DIR__.'/vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Simple server to demonstrate how to use Google+ Sign-In and make a request
* via your own server.
*
* #author silvano#google.com (Silvano Luciani)
*/
/**
* Replace this with the client ID you got from the Google APIs console.
*/
const CLIENT_ID = 'XXXXXXXX-itqqmr9qhegol91ne7sgkkeksmncfgqp.apps.googleusercontent.com';
/**
* Replace this with the client secret you got from the Google APIs console.
*/
const CLIENT_SECRET = 'XXXXXXXXXXX';
/**
* Optionally replace this with your application's name.
*/
const APPLICATION_NAME = "CoachGator";
$client = new Google_Client();
$client->setApplicationName(APPLICATION_NAME);
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setRedirectUri('postmessage');
$plus = new Google_Service_Plus($client);
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), array(
'twig.path' => __DIR__,
));
$app->register(new Silex\Provider\SessionServiceProvider());
// Initialize a session for the current user, and render index.html.
$app->get('/', function () use ($app) {
$state = md5(rand());
$app['session']->set('state', $state);
return $app['twig']->render('index.html', array(
'CLIENT_ID' => CLIENT_ID,
'STATE' => $state,
'APPLICATION_NAME' => APPLICATION_NAME
));
});
// Upgrade given auth code to token, and store it in the session.
// POST body of request should be the authorization code.
// Example URI: /connect?state=...&gplus_id=...
$app->post('/connect', function (Request $request) use ($app, $client) {
$token = $app['session']->get('token');
if (empty($token)) {
// Ensure that this is no request forgery going on, and that the user
// sending us this connect request is the user that was supposed to.
if ($request->get('state') != ($app['session']->get('state'))) {
return new Response('Invalid state parameter', 401);
}
// Normally the state would be a one-time use token, however in our
// simple case, we want a user to be able to connect and disconnect
// without reloading the page. Thus, for demonstration, we don't
// implement this best practice.
//$app['session']->set('state', '');
$code = $request->getContent();
// Exchange the OAuth 2.0 authorization code for user credentials.
$client->authenticate($code);
$token = json_decode($client->getAccessToken());
// You can read the Google user ID in the ID token.
// "sub" represents the ID token subscriber which in our case
// is the user ID. This sample does not use the user ID.
$attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)
->getAttributes();
$gplus_id = $attributes["payload"]["sub"];
// Store the token in the session for later use.
$app['session']->set('token', json_encode($token));
$response = 'Successfully connected with token: ' . print_r($token, true);
} else {
$response = 'Already connected';
}
return new Response($response, 200);
});
// Get list of people user has shared with this app.
$app->get('/people', function () use ($app, $client, $plus) {
$token = $app['session']->get('token');
if (empty($token)) {
return new Response('Unauthorized request', 401);
}
$client->setAccessToken($token);
$people = $plus->people->listPeople('me', 'visible', array());
/*
* Note (Gerwin Sturm):
* $app->json($people) ignores the $people->items not returning this array
* Probably needs to be fixed in the Client Library
* items isn't listed as public property in Google_Service_Plus_Person
* Using ->toSimpleObject for now to get a JSON-convertible object
*/
return $app->json($people->toSimpleObject());
});
// Revoke current user's token and reset their session.
$app->post('/disconnect', function () use ($app, $client) {
$token = json_decode($app['session']->get('token'))->access_token;
$client->revokeToken($token);
// Remove the credentials from the user's session.
$app['session']->set('token', '');
return new Response('Successfully disconnected', 200);
});
$app->run();

PHP Google Drive API installation and file upload

Hi guys i'm trying uploading file trought G drive API.
Can't find out why it returns error:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Gdrive{
function initialize(){
$credentials = $this->GetOAuth2Credentials($_GET['code']);
$_SESSION['credentials'] = $credentials;
}
/**
* Exchange an authorization code for OAuth 2.0 credentials.
*
* #param String $authorizationCode Authorization code to exchange for an
* access token and refresh token. The refresh token is only returned by
* Google on the very first exchange- when a user explicitly approves
* the authorization request.
* #return OauthCredentials OAuth 2.0 credentials object
*/
function GetOAuth2Credentials($authorizationCode) {
$client = new apiClient();
$client->setClientId(Config::5112+++++.apps.****5971157#developer.gserviceaccount.com);
$client->setRedirectUri(Config::site_url());
/**
* Ordinarily we wouldn't set the $_GET variable. However, the API library's
* authenticate() function looks for authorization code in the query string,
* so we want to make sure it is set to the correct value passed into the
* function arguments.
*/
$_GET['code'] = $authorizationCode;
$jsonCredentials = json_decode($client->authenticate());
$oauthCredentials = new OauthCredentials(
$jsonCredentials->access_token,
isset($jsonCredentials->refresh_token)?($jsonCredentials->refresh_token):null,
$jsonCredentials->created,
$jsonCredentials->expires_in,
Config::CLIENT_ID,
Config::CLIENT_SECRET
);
return $oauthCredentials;
}
function SaveNewFile($inputFile) {
try {
$mimeType = 'text/plain';
$file = new Google_DriveFile();
$file->setTitle($inputFile->title);
$file->setDescription($inputFile->description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($inputFile->parentId != null) {
$parentsCollectionData = new DriveFileParentsCollection();
$parentsCollectionData->setId($inputFile->parentId);
$file->setParentsCollection(array($parentsCollectionData));
}
$createdFile = $this->service->files->insert($file, array(
'data' => $inputFile->content,
'mimeType' => $mimeType,
));
return $createdFile;
} catch (apiServiceException $e) {
/*
* Log error and re-throw
*/
error_log('Error saving new file to Drive: ' . $e->getMessage(), 0);
throw $e;
}
}
}
when i invoke the initialize() method it returns error:
Message: Undefined index: code
Fatal error: Class 'apiClient' not found
what should be? i'm doing right in my code ? does i need more code to make it works? i created web application project on google api console.
need i to include google php sdk? in the google docs it is not mentioned for google drive api :/
You are probably using an older version of the PHP client library. Make sure you have the latest source and follow the instructions in the Google Drive SDK quickstart page to learn how to write a complete PHP app to upload a file to Drive:
https://developers.google.com/drive/quickstart
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();
please use those require files and Google_Client().

Categories