Giter Site home page Giter Site logo

google-api-php-client's Introduction

Google APIs Client Library for PHP

NOTE: please check to see if the package you'd like to install is available in our list of Google cloud packages first, as these are the recommended libraries.

Reference Docs
https://googleapis.github.io/google-api-php-client/main/
License
Apache 2.0

The Google API Client Library enables you to work with Google APIs such as Gmail, Drive or YouTube on your server.

These client libraries are officially supported by Google. However, the libraries are considered complete and are in maintenance mode. This means that we will address critical bugs and security issues but will not add any new features.

Google Cloud Platform

For Google Cloud Platform APIs such as Datastore, Cloud Storage, Pub/Sub, and Compute Engine, we recommend using the Google Cloud client libraries. For a complete list of supported Google Cloud client libraries, see googleapis/google-cloud-php.

Requirements

Developer Documentation

The docs folder provides detailed guides for using this library.

Installation

You can use Composer or simply Download the Release

Composer

The preferred method is via composer. Follow the installation instructions if you do not already have composer installed.

Once composer is installed, execute the following command in your project root to install this library:

composer require google/apiclient:^2.15.0

If you're facing a timeout error then either increase the timeout for composer by adding the env flag as COMPOSER_PROCESS_TIMEOUT=600 composer install or you can put this in the config section of the composer schema:

{
    "config": {
        "process-timeout": 600
    }
}

Finally, be sure to include the autoloader:

require_once '/path/to/your-project/vendor/autoload.php';

This library relies on google/apiclient-services. That library provides up-to-date API wrappers for a large number of Google APIs. In order that users may make use of the latest API clients, this library does not pin to a specific version of google/apiclient-services. In order to prevent the accidental installation of API wrappers with breaking changes, it is highly recommended that you pin to the latest version yourself prior to using this library in production.

Cleaning up unused services

There are over 200 Google API services. The chances are good that you will not want them all. In order to avoid shipping these dependencies with your code, you can run the Google\Task\Composer::cleanup task and specify the services you want to keep in composer.json:

{
    "require": {
        "google/apiclient": "^2.15.0"
    },
    "scripts": {
        "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Drive",
            "YouTube"
        ]
    }
}

This example will remove all services other than "Drive" and "YouTube" when composer update or a fresh composer install is run.

IMPORTANT: If you add any services back in composer.json, you will need to remove the vendor/google/apiclient-services directory explicitly for the change you made to have effect:

rm -r vendor/google/apiclient-services
composer update

NOTE: This command performs an exact match on the service name, so to keep YouTubeReporting and YouTubeAnalytics as well, you'd need to add each of them explicitly:

{
    "extra": {
        "google/apiclient-services": [
            "Drive",
            "YouTube",
            "YouTubeAnalytics",
            "YouTubeReporting"
        ]
    }
}

Download the Release

If you prefer not to use composer, you can download the package in its entirety. The Releases page lists all stable versions. Download any file with the name google-api-php-client-[RELEASE_NAME].zip for a package including this library and its dependencies.

Uncompress the zip file you download, and include the autoloader in your project:

require_once '/path/to/google-api-php-client/vendor/autoload.php';

For additional installation and setup instructions, see the documentation.

Examples

See the examples/ directory for examples of the key client features. You can view them in your browser by running the php built-in web server.

$ php -S localhost:8000 -t examples/

And then browsing to the host and port you specified (in the above example, http://localhost:8000).

Basic Example

// include your composer dependencies
require_once 'vendor/autoload.php';

$client = new Google\Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("YOUR_APP_KEY");

$service = new Google\Service\Books($client);
$query = 'Henry David Thoreau';
$optParams = [
  'filter' => 'free-ebooks',
];
$results = $service->volumes->listVolumes($query, $optParams);

foreach ($results->getItems() as $item) {
  echo $item['volumeInfo']['title'], "<br /> \n";
}

Authentication with OAuth

An example of this can be seen in examples/simple-file-upload.php.

  1. Follow the instructions to Create Web Application Credentials

  2. Download the JSON credentials

  3. Set the path to these credentials using Google\Client::setAuthConfig:

    $client = new Google\Client();
    $client->setAuthConfig('/path/to/client_credentials.json');
  4. Set the scopes required for the API you are going to call

    $client->addScope(Google\Service\Drive::DRIVE);
  5. Set your application's redirect URI

    // Your redirect URI can be any registered URI, but in this example
    // we redirect back to this same page
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
    $client->setRedirectUri($redirect_uri);
  6. In the script handling the redirect URI, exchange the authorization code for an access token:

    if (isset($_GET['code'])) {
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    }

Authentication with Service Accounts

An example of this can be seen in examples/service-account.php.

Some APIs (such as the YouTube Data API) do not support service accounts. Check with the specific API documentation if API calls return unexpected 401 or 403 errors.

  1. Follow the instructions to Create a Service Account

  2. Download the JSON credentials

  3. Set the path to these credentials using the GOOGLE_APPLICATION_CREDENTIALS environment variable:

    putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
  4. Tell the Google client to use your service account credentials to authenticate:

    $client = new Google\Client();
    $client->useApplicationDefaultCredentials();
  5. Set the scopes required for the API you are going to call

    $client->addScope(Google\Service\Drive::DRIVE);
  6. If you have delegated domain-wide access to the service account and you want to impersonate a user account, specify the email address of the user account using the method setSubject:

    $client->setSubject($user_to_impersonate);

How to use a specific JSON key

If you want to a specific JSON key instead of using GOOGLE_APPLICATION_CREDENTIALS environment variable, you can do this:

$jsonKey = [
   'type' => 'service_account',
   // ...
];
$client = new Google\Client();
$client->setAuthConfig($jsonKey);

Making Requests

The classes used to call the API in google-api-php-client-services are autogenerated. They map directly to the JSON requests and responses found in the APIs Explorer.

A JSON request to the Datastore API would look like this:

POST https://datastore.googleapis.com/v1beta3/projects/YOUR_PROJECT_ID:runQuery?key=YOUR_API_KEY
{
    "query": {
        "kind": [{
            "name": "Book"
        }],
        "order": [{
            "property": {
                "name": "title"
            },
            "direction": "descending"
        }],
        "limit": 10
    }
}

Using this library, the same call would look something like this:

// create the datastore service class
$datastore = new Google\Service\Datastore($client);

// build the query - this maps directly to the JSON
$query = new Google\Service\Datastore\Query([
    'kind' => [
        [
            'name' => 'Book',
        ],
    ],
    'order' => [
        'property' => [
            'name' => 'title',
        ],
        'direction' => 'descending',
    ],
    'limit' => 10,
]);

// build the request and response
$request = new Google\Service\Datastore\RunQueryRequest(['query' => $query]);
$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);

However, as each property of the JSON API has a corresponding generated class, the above code could also be written like this:

// create the datastore service class
$datastore = new Google\Service\Datastore($client);

// build the query
$request = new Google\Service\Datastore_RunQueryRequest();
$query = new Google\Service\Datastore\Query();
//   - set the order
$order = new Google\Service\Datastore_PropertyOrder();
$order->setDirection('descending');
$property = new Google\Service\Datastore\PropertyReference();
$property->setName('title');
$order->setProperty($property);
$query->setOrder([$order]);
//   - set the kinds
$kind = new Google\Service\Datastore\KindExpression();
$kind->setName('Book');
$query->setKinds([$kind]);
//   - set the limit
$query->setLimit(10);

// add the query to the request and make the request
$request->setQuery($query);
$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);

The method used is a matter of preference, but it will be very difficult to use this library without first understanding the JSON syntax for the API, so it is recommended to look at the APIs Explorer before using any of the services here.

Making HTTP Requests Directly

If Google Authentication is desired for external applications, or a Google API is not available yet in this library, HTTP requests can be made directly.

If you are installing this client only to authenticate your own HTTP client requests, you should use google/auth instead.

The authorize method returns an authorized Guzzle Client, so any request made using the client will contain the corresponding authorization.

// create the Google client
$client = new Google\Client();

/**
 * Set your method for authentication. Depending on the API, This could be
 * directly with an access token, API key, or (recommended) using
 * Application Default Credentials.
 */
$client->useApplicationDefaultCredentials();
$client->addScope(Google\Service\Plus::PLUS_ME);

// returns a Guzzle HTTP Client
$httpClient = $client->authorize();

// make an HTTP request
$response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me');

Caching

It is recommended to use another caching library to improve performance. This can be done by passing a PSR-6 compatible library to the client:

use League\Flysystem\Adapter\Local;
use League\Flysystem\Filesystem;
use Cache\Adapter\Filesystem\FilesystemCachePool;

$filesystemAdapter = new Local(__DIR__.'/');
$filesystem        = new Filesystem($filesystemAdapter);

$cache = new FilesystemCachePool($filesystem);
$client->setCache($cache);

In this example we use PHP Cache. Add this to your project with composer:

composer require cache/filesystem-adapter

Updating Tokens

When using Refresh Tokens or Service Account Credentials, it may be useful to perform some action when a new access token is granted. To do this, pass a callable to the setTokenCallback method on the client:

$logger = new Monolog\Logger();
$tokenCallback = function ($cacheKey, $accessToken) use ($logger) {
  $logger->debug(sprintf('new access token received at cache key %s', $cacheKey));
};
$client->setTokenCallback($tokenCallback);

Debugging Your HTTP Request using Charles

It is often very useful to debug your API calls by viewing the raw HTTP request. This library supports the use of Charles Web Proxy. Download and run Charles, and then capture all HTTP traffic through Charles with the following code:

// FOR DEBUGGING ONLY
$httpClient = new GuzzleHttp\Client([
    'proxy' => 'localhost:8888', // by default, Charles runs on localhost port 8888
    'verify' => false, // otherwise HTTPS requests will fail.
]);

$client = new Google\Client();
$client->setHttpClient($httpClient);

Now all calls made by this library will appear in the Charles UI.

One additional step is required in Charles to view SSL requests. Go to Charles > Proxy > SSL Proxying Settings and add the domain you'd like captured. In the case of the Google APIs, this is usually *.googleapis.com.

Controlling HTTP Client Configuration Directly

Google API Client uses Guzzle as its default HTTP client. That means that you can control your HTTP requests in the same manner you would for any application using Guzzle.

Let's say, for instance, we wished to apply a referrer to each request.

use GuzzleHttp\Client;

$httpClient = new Client([
    'headers' => [
        'referer' => 'mysite.com'
    ]
]);

$client = new Google\Client();
$client->setHttpClient($httpClient);

Other Guzzle features such as Handlers and Middleware offer even more control.

Partial Consent and Granted Scopes

When using OAuth2 3LO (e.g. you're a client requesting credentials from a 3rd party, such as in the simple file upload example), you may want to take advantage of Partial Consent.

To allow clients to only grant certain scopes in the OAuth2 screen, pass the querystring parameter for enable_serial_consent when generating the authorization URL:

$authUrl = $client->createAuthUrl($scope, ['enable_serial_consent' => 'true']);

Once the flow is completed, you can see which scopes were granted by calling getGrantedScope on the OAuth2 object:

// Space-separated string of granted scopes if it exists, otherwise null.
echo $client->getOAuth2Service()->getGrantedScope();

Service Specific Examples

YouTube: https://github.com/youtube/api-samples/tree/master/php

How Do I Contribute?

Please see the contributing page for more information. In particular, we love pull requests - but please make sure to sign the contributor license agreement.

Frequently Asked Questions

What do I do if something isn't working?

For support with the library the best place to ask is via the google-api-php-client tag on StackOverflow: https://stackoverflow.com/questions/tagged/google-api-php-client

If there is a specific bug with the library, please file an issue in the GitHub issues tracker, including an example of the failing code and any specific errors retrieved. Feature requests can also be filed, as long as they are core library requests, and not-API specific: for those, refer to the documentation for the individual APIs for the best place to file requests. Please try to provide a clear statement of the problem that the feature would address.

I want an example of X!

If X is a feature of the library, file away! If X is an example of using a specific service, the best place to go is to the teams for those specific APIs - our preference is to link to their examples rather than add them to the library, as they can then pin to specific versions of the library. If you have any examples for other APIs, let us know and we will happily add a link to the README above!

Why do some Google\Service classes have weird names?

The Google\Service classes are generally automatically generated from the API discovery documents: https://developers.google.com/discovery/. Sometimes new features are added to APIs with unusual names, which can cause some unexpected or non-standard style naming in the PHP classes.

How do I deal with non-JSON response types?

Some services return XML or similar by default, rather than JSON, which is what the library supports. You can request a JSON response by adding an 'alt' argument to optional params that is normally the last argument to a method call:

$opt_params = array(
  'alt' => "json"
);

How do I set a field to null?

The library strips out nulls from the objects sent to the Google APIs as it is the default value of all of the uninitialized properties. To work around this, set the field you want to null to Google\Model::NULL_VALUE. This is a placeholder that will be replaced with a true null when sent over the wire.

Code Quality

Run the PHPUnit tests with PHPUnit. You can configure an API key and token in BaseTest.php to run all calls, but this will require some setup on the Google Developer Console.

phpunit tests/

Coding Style

To check for coding style violations, run

vendor/bin/phpcs src --standard=style/ruleset.xml -np

To automatically fix (fixable) coding style violations, run

vendor/bin/phpcbf src --standard=style/ruleset.xml

google-api-php-client's People

Contributors

abusalam avatar assimilationstheorie avatar bshaffer avatar carusogabriel avatar chixor avatar deconf avatar dwsupplee avatar grant avatar ianbarber avatar ip512 avatar ircmaxell avatar ithinkihaveacat avatar itsazzad avatar jdpedrie avatar justinbeckwith avatar kunit avatar localheinz avatar ltrebing avatar mattwhisenhunt avatar mishan avatar release-please[bot] avatar ricardofontanelli avatar silvolu avatar simonschaufi avatar sqrrrl avatar swissspidy avatar tbetbetbe avatar theacodes avatar whatthejeff avatar wibblymat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

google-api-php-client's Issues

Possible small bug on Oauth2.php

Hello there,

On this line 156, file "OAuth2.php":
https://github.com/google/google-api-php-client/blob/5c58413bba2301ef602d2a6650d4f5d82088ce64/src/Google/Auth/OAuth2.php#L156

It’s:

if (strpos($scope, 'plus.login') && strlen($rva) > 0) {

And should be:

if (strpos($scope, 'plus.login')!==false && strlen($rva) > 0) {

We also need a solution for issue 39, because the third example on https://developers.google.com/youtube/partner/code_samples/php#uploading_a_new_reference__so_youtube_can_automatically_generate_claims_for_newly_uploaded_videos_on_behalf_of_the_asset_s_owner isn’t working… Even if you put the YouTubePartner.php file to work along with the code, because this file isn’t on the repository yet.

Could you please have a look at it?

Best regards,

Store id_token when refreshing token

Is there a reason to not store the id_token when refreshing the access_token?

My question is because when I use the verifyIdToken method after a refreshToken, it fails.

allow gzip for API calls

The documentation recommends using gzip for API calls, but it doesn't look like the php-client is doing this. I thought maybe the Google_Service or Google_Service_Resource classes would be able to customize the headers of the Google_Http_Request object they ultimately call, but there didn't seem to be a way to do that.

Thanks for listening!

handling of partially failed batch jobs

If some subset of a batch job fails, then it is not possible to see which requests failed because any one failure will throw an exception that exits Google_Http_Batch::parseResponse. Recovery/reporting would be possible if Google_Http_Batch had an option to include exceptions in its response array and allow the caller to examine/deal with them.

status.embeddable not recognized on insert/update

Hi,

i'm not sure this an issue with the PHP api client, with the API itself or if i'm doing something wrong.

The value of status.embeddable is simply ignored for $youtube->videos->insert() and $youtube->videos->update() and is always set to the (default) value true.

I'm basically using the code from the PHP examples.

Inspecting the Google_Http_Request object (at this point) shows that the property is set correctly:

Google_Http_Request Object
(
    ...
    [postBody:protected] => {"snippet":{"categoryId":22,"description":"Test","tags":[""],"title":"Test"},"status":{"embeddable":false,"privacyStatus":"unlisted"}}
    ...
)

The responseBodyproperty shows that everything was accepted except embeddable:

Google_Http_Request Object
(
    ...
[responseBody:protected] => {
...
 "status": {
  "uploadStatus": "processed",
  "privacyStatus": "unlisted",
  "license": "youtube",
  "embeddable": true,
  "publicStatsViewable": true
 }
}
)

Any help or hints appreciated.

Temporary files not cleaned up

Came upon an issue where server was degraded by the client using up all the available inodes for temporary file storage.

Cannot authenticate

I've been trying to follow the examples on the google group and in this repository.

I'm building this on localhost have the following topography:

webRoot/
  api/
    index.php
    resources/calendar.php

  libs/google/1.0.1a/
    Auth/
    Cache/
    Http/
    …
    Client.php
    …

The contents of libs/google/1.0.1a/ are from src/Google/ (and require_once links updated via global find+replace).

curl -X GET 'http://localhost/api/index.php/calendar/not_used_yet/events'

index.php detects calendar in the path and forwards the request to calendar.php:

# api/resources/calendar.php
session_start();
class Calendar extends Response {
  protected $service;

  function __construct() {
    set_include_path(get_include_path() . PATH_SEPARATOR . 'libs/google/1.0.1a/');
    require_once 'Client.php';
    require_once 'service/Calendar.php';

    $client = new Google_Client();
    $client->setApplicationName('test');
    // redirectUri = 'http://localhost/api/index.php/calendar'
    $client->setScopes('calendar');

    $this->service = new Google_Service_Calendar($client);

    if ( isset($_GET['code']) )
    {
      $client->authenticate($_GET['code']);
      $_SESSION['access_token'] = $client->getAccessToken();
    }
    if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
      $client->setAccessToken($_SESSION['access_token']);
    else
      $authUrl = $client->createAuthUrl();

    if ( $client->getAccessToken() )
    {
      $_SESSION['access_token'] = $client->getAccessToken();
      $token_data = $client->verifyIdToken()->getAttributes();
    }
  }

  public function events( $req ) {
    $this->connect();
    $calendarList = $this->service->calendarList->listCalendarList();
  }
}

I've populated the params in Config.php, yet I still get:

Fatal error: Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/users/me/calendarList?key=$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$: (401) Login Required' in sitRoot/api/libs/google/1.0.1a/Http/REST.php:75 Stack trace:

0 sitRoot/api/libs/google/1.0.1a/Http/REST.php(45): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))

1 sitRoot/api/libs/google/1.0.1a/Client.php(492): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))

2 sitRoot/api/libs/google/1.0.1a/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))

3 sitRoot/api/libs/google/1.0.1a/service/Calendar.php(941): Google_Service_Resource->call('list', Array, 'Google_Service_...')

4 /Sites/ in sitRoot/api/libs/google/1.0.1a/Http/REST.php on line 75

I also can't get idtoken.php to work:

Invalid parameter value for redirect_uri: Raw IP addresses not allowed.

If an IP address is not allowed, then why did the api console ask for one when generating my server token??

Also, this is an API. Why is there a redirect? There is no human interaction—my script is providing credentials; how is this not a call and response?

Reseller service working with sandbox ?

Hello,

I have a script using the Reseller Service to retrieve my subscriptions. It works fine with the production api, but when I use the sandbox I get this exception :

Error calling GET https://www.googleapis.com/apps/reseller/v1sandbox/subscriptions: (500) {
 "error": {
  "code": 500,
  "message": null
 }
}

To use the sandbox I modified the Google_Service_Reseller class like this :

changed

$this->servicePath = 'apps/reseller/v1/';

to

$this->servicePath = 'apps/reseller/v1sandbox/';

This is the code I use to retrieve my subscriptions :

set_include_path(get_include_path() . PATH_SEPARATOR . 'lib/google-api-client/src');

$keyLocation = 'keys/google-apps/xxxxxxxxxxx.p12';
$key = file_get_contents($keyLocation);

$client = new Google_Client();
$client->setApplicationName('myapp');
$service = new Google_Service_Reseller($client);

if (isset($_SESSION['service_token'])) {
  $client->setAccessToken($_SESSION['service_token']);
}

$cred = new Google_Auth_AssertionCredentials(
    'myOauth2EmailAddress',
    array(
        'https://www.googleapis.com/auth/apps.order',
        'https://www.googleapis.com/auth/apps.order.readonly'
        ),
    $key
);

$cred->sub = 'mysub';
$client->setAssertionCredentials($cred);

if($client->getAuth()->isAccessTokenExpired()) {
  $client->getAuth()->refreshTokenWithAssertion($cred);
}

$_SESSION['service_token'] = $client->getAccessToken();

$service->subscriptions->listSubscriptions();

Thanks.

Weird Size Issue - 600KB video file results in 18MB upload traffic. 8 MB file results in 228MB outgoing traffic

I am trying to upload a video to you tube using the latest code samples.
The file size is around 600 KB (KiloBytes).

While the sample uploads the video fine using the chunked upload method, I found something really strange.

A file size of 600KB results in an upload traffic of around 17 to 18 MB.
Assuming, a base64_encode of the same file results in a physical file size of : 884KB.

Can someone explain, if the large upload traffic is natural or there is some issue ?

If it is normal, then this is an extremely inefficient way of uploading data. Youtube should develop better methods.

I also tested with a physical file of size 8MB and it resulted in an upload traffic of whooping 228 MB.

Can any one throw some light on this ? if someone wants, I can paste the entire code of the script I am using,

I can see why people are complaining about slow uploads too : #50

Edit : Tested with the previous version of the code. google-api-php-client-1.0.0-alpha - This works fine, and upload traffic is equal to file size.

dataTable property not accessible

This property is protected and there is no method to get the dataTable data.

Outputs a dataTable property in the response, containing a Data Table object. This Data Table object can be used directly with Google Charts visualizations.

So how can I use this "directly" with Google Charts API?

Possible cache issue...?

Old subject: is it possible 'if-none-match' breaks file_get_contents in IO\Stream.php?

Hi... I've just updated "google/apiclient" and my code stopped to work. After a while I've found a possible issue... Double quotes in etag for if-none-match header are not escaped. Is this important?

When I've added a line ($v = addslashes($v);) just before line 77 everything is back to normal... I think...
...

Why PHP 5.2?

I'm just curious, why you still have the requirements set to PHP 5.2?
Why don't you move the codebase to 5.4 in order to leverage the new features as namespaces, autoloading, traits, etc.

Youtube upload video error

Following the example from here https://developers.google.com/youtube/v3/code_samples/php#resumable_uploads I've tried to upload a video but received the next error :

Warning: file_get_contents(/upload/youtube/v3/videos?part=status%2Csnippet&uploadType=resumable): failed to open stream: No error in...\Google\IO\Stream.php on line 109
Call Stack

Time Memory Function Location

1 0.0011 160976 {main}( ) ..\upload.php:0
2 0.0609 3369288 Google_Http_MediaFileUpload->nextChunk( ) ..\upload.php:90
3 0.0609 3369512 Google_Http_MediaFileUpload->getResumeUri( ) ..\MediaFileUpload.php:123
4 0.0615 3370664 Google_IO_Stream->makeRequest( ) ..\MediaFileUpload.php:260
5 0.0618 3375192 file_get_contents ( ) ..\Stream.php:109

function does not work -> management_dailyUploads (Analytics Daily Upload)

Analytics Management API - Daily Upload Developer Guide

such a request causes an error:
$Analytics_test = $service->management_dailyUploads->upload(
'123456789', // your accountID
'UA-123456789-1', // your web property ID
'xxxxxxxxxxxxxxxxxx', // your custom data source UID
'2014-01-05', // date
1, // append number
'cost', // type of data
array(
'reset' => true,
'data' => file_get_contents("reports/report_2013-12-23.csv"),
'mimeType' => 'application/octet-stream',
'uploadType' => 'media'));

at least incorrectly formed URL request...

Service Account and Delegation of Authority

Hi there,

I spent some hours to try to understand what's wrong but I really do know.
I'm trying to use the Directory service with a Service Account.
I have configure every thing possible as describe here on this page https://developers.google.com/drive/web/delegation#delegate_domain-wide_authority_to_your_service_account :

  • Create a service account on my console API ;
  • Active the API on my Google Apps console ;
  • Add the Client ID with scopes on the Google Apps console ;

But i'm facing a strange issue with the API... (i've try with the master version and also with tags...)

Here is my code :

function newBuildService($anArray) {
    $config = new Google_Config();
    $config->setCacheClass('Google_Cache_Memcache');
    $config->setClassConfig('Google_Cache_Memcache',
      array('host' => 'does_not_matter', 'port' => '37337'));
    /*$config->setClassConfig('Google_Http_Request',
      array('disable_gzip' => false));*/

    global $client;
    $client = new Google_Client($config);
    $client->setApplicationName("Client_Library_Examples");
    $service = new Google_Service_Directory($client);
    $_SESSION['service_token'] = null;
    if (isset($_SESSION['service_token'])) {
      $client->setAccessToken($_SESSION['service_token']);
    }
    $key = file_get_contents($anArray['p12file']);
    $cred = new Google_Auth_AssertionCredentials(
         $anArray['service_account_email'],
        array(DIRECTORY_SCOPE),
        $key
        ,'notasecret'
        ,'http://oauth.net/grant_type/jwt/1.0/bearer'
    );
    ///!\ THIS LINE CAUSE THE ISSUE
    $cred->sub = "[email protected]";

    $client->setAssertionCredentials($cred);
    if($client->getAuth()->isAccessTokenExpired()) {
      $client->getAuth()->refreshTokenWithAssertion($cred);
    }
    $_SESSION['service_token'] = $client->getAccessToken();   
    return $service;
}   
$adminService = newBuildService($anArray);
$res = $adminService->groups->listGroups(array('domain'=>'mydomain.com'));

When a run this code, i've this error :
Fatal error: Uncaught exception 'Google_Auth_Exception' with message 'Error refreshing the OAuth2 token, message: '<title>Comptes Google</title> <script type="text/javascript" src="https://ssl.gstatic.com/accounts/o/237772143-common_lib.js"></script> <style>@media screen and (max-width:500px) {#robot {background: none; min-height: 0; min-width: 0; padding: 0;}#stack_trace {display: none;}} #oauth2_request_info_header {background-image: url("https://ssl.gstatic.com/accounts/o/blank.gif");}</style>

<a href="//www.google.com/" in D:\workspace_myeclipse10\visu\visu\google-api-php-client-master\src\Google\Auth\OAuth2.php on line 328

And when i try comment this mandatory line "$cred->sub = "[email protected]";" i've this message :
Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/admin/directory/v1/groups?domain=mydomain.com: (403) Not Authorized to access this resource/api'

I hope this is clear. Does anyone knows what's wrong ?
Thanks for your help.
Sebastien

Issues with functions using PHP versions prior to 5.3.4

gzip compression for the API client does not work prior to PHP version 5.3.4: The documentation should be updated to note this or a check should be done in the code to disable gzip compression for PHP versions prior to 5.3.4 (at least until cURL support is added)

There is a bug in PHP versions prior to 5.3.4 where the auth headers will not get set properly using stream_context_create, so all requests to the APIs will fail.

See https://bugs.php.net/bug.php?id=52926 and http://www.php.net/ChangeLog-5.php#5.3.4... Something like:

if(version_compare(phpversion(),"5.3.4",">=")){
  $disable_gzip = false;
}else{
  $disable_gzip = true;
}

And then setting the disable_gzip param to that…

Also if 5.2.1 is still being supported, then should lcfirst be used in src/Google/Utils.php? This appears to have been released in 5.3

Google Tasks - Error calling GET - (401) Login Required

I am trying to get list of tasks and I am getting error Login Required. How can I view my Tasks in default tasklist?

Error:

Fatal error:  Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/tasks/v1/users/@me/lists: (401) Login Required' in C:\wamp\www\tasks\Google\Http\REST.php:75
Stack trace:
#0 C:\wamp\www\tasks\Google\Http\REST.php(45): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 C:\wamp\www\tasks\Google\Http\Request.php(83): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 C:\wamp\www\tasks\Google\Service\Resource.php(190): Google_Http_Request->execute()
#3 C:\wamp\www\tasks\Google\Service\Tasks.php(371): Google_Service_Resource->call('list', Array, 'Google_Service_...')
#4 C:\wamp\www\tasks\index.php(41): Google_Service_Tasks_Tasklists_Resource->listTasklists()
#5 {main}
  thrown in C:\wamp\www\tasks\Google\Http\REST.php on line 75

My code:

<?php
        require_once 'Google/Client.php';
        require_once 'Google/Service/Tasks.php';

        $client_id = 'MY_CLIENT_ID';
        $client_secret = 'MY_CLIENT_SECRET';
        $redirect_uri = 'http://localhost/tasks/';

        $client = new Google_Client();
        $client->setApplicationName("Client_Library_Examples");
        $client->setClientId($client_id);
        $client->setClientSecret($client_secret);
        $client->setRedirectUri($redirect_uri);
        $client->setScopes("https://www.googleapis.com/auth/tasks");
        $client->setScopes("https://www.googleapis.com/auth/tasks.readonly");
        $authUrl = $client->createAuthUrl();

        if (isset($_GET['code'])) {
            $client->authenticate($_GET['code']);
            $_SESSION['access_token'] = $client->getAccessToken();
            $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
            header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
        }

        if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
            $client->setAccessToken($_SESSION['access_token']);
        }

        echo '<a href="' . $authUrl . '">link me</a>';

        $service = new Google_Service_Tasks($client);

        echo '<pre>';
        $service->tasklists->listTasklists();


        ?>

Typos in Analytics Service

Found an issue using this service recently throwing an error:

Failed with message: (get) unknown parameter: 'start-date'

Turns out there are two typos in the Analytics service file

"start_date" => array(
    "location" => "query",
    "type" => "string",
    'required' => true,
),
"end_date" => array(
    "location" => "query",
    "type" => "string",
    'required' => true,
),

should be

"start-date" => array(
    "location" => "query",
    "type" => "string",
    'required' => true,
),
"end-date" => array(
    "location" => "query",
    "type" => "string",
    'required' => true,
),

PHP Notices

Calling:

$sources = $service->management_customDataSources->listManagementCustomDataSources($prop->accountId, $prop->id);
$customDataSources = $sources->getItems();

results in PHP Notices when no items are returned:

PHP Notice:  Undefined index: items in .../vendor/google/apiclient/src/Google/Model.php on line 49
PHP Notice:  Undefined index: items in .../vendor/google/apiclient/src/Google/Model.php on line 70

allowed memory fatal error

PHP Fatal error: Allowed memory size of 1073741824 bytes exhausted (tried to allocate 36 bytes) in /vendor/google/apiclient/src/Google/Model.php on line 113

this error keep shown even increasing the php.ini allowed memory

Upload 4Mb file to YouTube took over 9 minutes since gzip compression added

The YouTube Service insert method was working fine prior to this update, but the since the gzip compression was added to IO/Stream.php, the time it takes is significantly increased.

I've used a debugger in my IDE and the time is spent in the call to file_get_contents() on line 111 in IO/Stream.php

$response_data = file_get_contents(
    $url,
    false,
    $context
);

I am running PHP 5.5.1, ZLib Version 1.2.7, Apache 2.4.6, Windows 7

I've a project going live for Adidas on monday that uses this code, so any assistance with it would be very appreciated.

require_once error in Client.php

I am trying to migrate to 1.0 api in Drupal 7.and the first error I get is:

Fatal error: require_once() [function.require]: Failed opening required 'Google/Auth/AssertionCredentials.php' (include_path='.;C:\Program Files (x86)\acquia-drupal\common\pear') in C:\Users\cdavidyoung\Sites\public_html\includes\google-api-php-client\src\Google\Client.php on line 18

Why are all of the paths now prefixed with "Google/"? This seems to be causing the error. Is there include_path setting that we need to set to use this new api?

0.6->1.0 migration guide incomplete

Hi, folks. I just submitted a patch for OwnCloud's Google Drive plugin to migrate it to 1.0 (there's a small chance I even got it right!), and noticed a couple of things missing from the 0.6-1.0 migration guide:

  • In Client.php , $auth , $io , $cache and $config are now private; it seems to have been pretty common for people to use $io especially when downloading files, and indeed Google's own sample code at https://developers.google.com/drive/web/manage-downloads does this. Would be good to note that you have to use getAuth(), getIo(), getCache(), getConfig() now.
  • The authenticatedRequest functions seem to have moved from the IO classes to the Auth classes

So with those two taken together, in migrating the OC app's file download function, I had to go from:

$io->authenticatedRequest($request);

to:

getAuth()->authenticatedRequest($request);

Thanks!

Google_Service_Oauth2 get user info

I am unable of retrieving authenticated user information through Google_Service_Oauth2. After authentication processes i am able to execute the following method:

$user = $oauth2->userinfo->get();

But when I print user fields by calling getEmail, getGiven_name, getFamily_name and so on, these fields are in blank except for getId. User Id is ok, so the authentication process is correct, but basic profile information is in blank.

I saw that this get method accepts an array of optional parameters, and I have tried to add email, or other fields but it does not work.

With the old 0.6.x library I was able to extract these fields without problems.

Any hint?

Auto-loader doesn't work for service subclasses

When using composer to install this library and depending on the composer autoloader, it is unable to instantiate a service subclass unless you first instantiate the service class.

Example:

<?php
include 'vendor/autoload.php';
$googleUserName = new Google_Service_Directory_UserName();
?>

That results in the error:

include(Google_Service_Directory_User.php): failed to open stream: No such file or directory

The problem is that file does not exist, the class Google_Service_Directory_User is defined in Google/Service/Directory.php.

The sub/child classes of each service should be defined in their own files in the proper folders. So class Google_Service_Directory_User should be defined in Google/Service/Directory/User.php.

As a workaround for now, you must instantiate the service class object first, which causes PHP to load that file, which then includes the definition of the sub class:

<?php
include 'vendor/autoload.php';
$dir = new Google_Service_Directory($client);
$googleUserName = new Google_Service_Directory_UserName();
?>

That way works.

As a side note, if part of the reason for the refactoring of this library is to use more modern practices, it should also ditch the Super_Long_Class_Names in favor of namespaces and up the minimum PHP version.

Stream.php Error

I get an error when uploading a video to YouTube.
This script is being run in a command line, after the form is submitted.

Code:

// Get the Google Client.
require_once MODULES.'Social'.DS.'Google'.DS.'Client.php';
// Get the YouTube Service.
require_once MODULES.'Social'.DS.'Google'.DS.'Service'.DS.'YouTube.php';

$client=new Google_Client();
$client->setApplicationName("API Project");
$client->setClientId(CLIENT_ID);
$client->setClientSecret(CLIENT_SECRET);
$client->setScopes('https://www.googleapis.com/auth/youtube');
$client->setRedirectUri(REDIRECT_URI);
$client->setDeveloperKey(DEV_KEY);
$client->refreshToken(REFRESH_TOKEN);

$youtube_service=new Google_Service_YouTube($client);

// Lots of code snipping here

// Set the path to the video on the server.
$video_path='video_file.mp4';

// Create a YouTube video with snippet and status.
$google_video=new Google_Service_YouTube_Video();
$google_video->setSnippet($google_video_snippet);
$google_video->setStatus($google_video_status);

// Size of each chunk of data in bytes. Setting it higher leads faster upload (less chunks, for reliable connections).
// Setting it lower leads better recovery (fine-grained chunks).
$chunk_size_bytes=1_1024_1024;

// Setting the defer flag to true tells the client to return a request which can be called
// with ->execute(); instead of making the API call immediately.
$client->setDefer(TRUE);

// Create a video insert request.
$insert_response=$yt->insertVideo('status,snippet', $google_video);

// Create a MediaFileUpload object for resumable uploads.
$media_file_upload=new Google_Http_MediaFileUpload($client, $insert_response, 'video/*', NULL, TRUE, $chunk_size_bytes);
$media_file_upload->setFileSize(filesize($video_path));

// Set $upload_status to FALSE by default.
$upload_status=FALSE;
// Read the media file and upload it chunk by chunk.
$handle=fopen($video_path, "rb");
while(!$upload_status && !feof($handle))
{
$chunk=fread($handle, $chunk_size_bytes);
$upload_status=$media_file_upload->nextChunk($chunk);
}
fclose($handle);

// If you want to make other calls after the file upload, set setDefer back to false
$client->setDefer(FALSE);

Error:

Warning: file_get_contents(/upload/youtube/v3/videos?part=status%2Csnippet&key=BLAH_BLAH&uploadType=resumable) [/phpmanual/function.file-get-contents.html]: failed to open stream: No such file or directory in Google/IO/Stream.php on line 109

Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect' in Google/IO/Stream.php:112
Stack trace:
#0 Google/Http/MediaFileUpload.php(260): Google_IO_Stream->makeRequest(Object(Google_Http_Request))
#1 Google/Http/MediaFileUpload.php(123): Google_Http_MediaFileUpload->getResumeUri()
#2 YouTubeUpload.php(118): Google_Http_MediaFileUpload->nextChunk('????ftypmp42???...')
#3 {main}

thrown in Google/IO/Stream.php on line 112

Simple File Upload not working

I was trying to upload a simple file to drive using the files->insert API.
Just migrated from .6 to 1.0 but still didn't work out.

Can anyone please help?


Warning: file_get_contents(compress.zlib://https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart&key=xxxxxxxxxxxxxx): failed to open stream: operation failed in /Applications/XAMPP/xamppfiles/htdocs/Google/IO/Stream.php on line 115

Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect' in /Applications/XAMPP/xamppfiles/htdocs/Google/IO/Stream.php:118 Stack trace:
#0 /Applications/XAMPP/xamppfiles/htdocs/Google/Http/REST.php(42): Google_IO_Stream->makeRequest(Object(Google_Http_Request))
#1 /Applications/XAMPP/xamppfiles/htdocs/Google/Client.php(487): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 /Applications/XAMPP/xamppfiles/htdocs/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 /Applications/XAMPP/xamppfiles/htdocs/Google/Service/Drive.php(1694): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 /Applications/XAMPP/xamppfiles/htdocs/dashboard_update.php(59): Google_Service_Drive_Files_Resource->insert(Object(Google_Service_Drive_DriveFile), Array)
#5 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/Google/IO/Stream.php on line 118

Google Analytics - Simple example

I am trying to use this library to use Google Analysis API

I got this already:

<?php

require_once 'Google/Client.php';
require_once 'Google/Service/Analytics.php';
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
$client->setDeveloperKey("MY_SECRET_API"); //security measures
$service = new Google_Service_Analytics($client);

/*
  https://www.googleapis.com/analytics/v3/data/
  ga?ids=ga%123456
  &dimensions=ga%3Acampaign
  &metrics=ga%3Atransactions
  &start-date=2013-12-25
  &end-date=2014-01-08
  &max-results=50
 */

$results = $service->data_ga;

echo '<pre>';
print_r($results);
echo '</pre>';

How to call that query in comments?

Support array/object query parameters

Would it be possible to support URL query parameters that are an array/object?

https://github.com/google/google-api-php-client/blob/86fb12d484da7fecbe04cecf767ac83008f24234/src/Google/Http/REST.php#L123

        if (isset($paramSpec['repeated']) && is_array($paramSpec['value'])) {
          foreach ($paramSpec['value'] as $value) {
            $queryVars[] = $paramName . '=' . rawurlencode($value);
          }
        } elseif ($paramSpec['type'] === 'object' && is_array($paramSpec['value'])) {
          $objParam = array($paramName => $paramSpec['value']);
          $queryVars[] = http_build_query($objParam);
        } else {
          $queryVars[] = $paramName . '=' . rawurlencode($paramSpec['value']);
        }

This would build a URL like:

example.com/api?query[param1]=foo

Undefined index: errors in google-api-php-client/src/io/Google_REST.php

sometimes the google+ api retuns errors without setting the 'errors' key. so the code throws an error.

in relation to https://code.google.com/p/google-api-php-client/issues/detail?id=266 i would suggest the following change:

//throw new Google_ServiceException($err, $code, null, $decoded['error']['errors']);
$error_msg = $err;
if(isset($decoded['error']) && isset($decoded['error']['errors'])){
  $error_msg = $decoded['error']['errors'];
}
throw new Google_ServiceException($err, $code, null, $error_msg);

createAuthUrl() may be configured to return a URL with HTML-encoded ampersands, but Google Drive's auth fails on such URLs

So, this is an interesting one. Still working on porting OwnCloud's Google Drive app to the v1.x version of google-api-php-client .

0.6's (OAuth2) createAuthUrl didn't use http_build_query, it just imploded an array into a string using a raw & character as a separator:

$params = implode('&', $params);

1.0's version uses http_build_query:

    return self::OAUTH2_AUTH_URL . "?" . http_build_query($params);

On modern PHP versions (it seems to be 5.3+), http_build_query uses an encoded ampersand as the separator by default. So createAuthUrl gives a URL like this:

"https://accounts.google.com/o/oauth2/auth?response_type=code&amp;redirect_uri=https%3A%2F%2Fwww.happyassassin.net%2Fowncloud%2Findex.php%2Fsettings%2Fadmin&amp;client_id=redacted.apps.googleusercontent.com&amp;scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&amp;access_type=online&amp;approval_prompt=auto"

However, the actual OAuth system doesn't seem to like that. If we pass it that URL, we get this:

Error:invalid_request

Missing required parameter: redirect_uri

Request Details

response_type=code
amp;redirect_uri=https://www.happyassassin.net/owncloud/index.php/settings/admin
amp;scope=https://www.googleapis.com/auth/drive
amp;approval_prompt=auto
amp;access_type=online
amp;client_id=(redacted)

Note all those "amp;"s.

If I make OwnCloud's app do an html_entity_decode() on the URL returned by createAuthUrl() then everything works, but this is obviously fairly silly.

If I'm understanding everything correctly, then either Google's OAuth implementation should be made to work correctly with HTML-encoded ampersands, or google-api-php-client should be doing this:

return self::OAUTH2_AUTH_URL . "?" . http_build_query($params, '', '&');

I'm fairly sure the problem here is on Google's side either in google-api-php-client or in your OAuth server, I don't think the OC app is doing anything wrong.

Problem inserting rows Fusiontable

Hello, I have a problem when I want to insert a row into kml type column (text > 650 characters) .

$local_kml="&ltMultiGeometry&gt&ltPoint&gt&ltcoordinates&gt24.140480,44.135342,0.0&lt/coordinates&gt&lt/Point&gt&ltLineString&gt&ltextrude&gt1&lt/extrude&gt&lttessellate&gt1&lt/tessellate&gt&ltcoordinates&gt24.140480,44.135342,0.0 24.126301,44.144180,0.0 24.115210,44.151180,0.0 24.114630,44.151489,0.0 24.114120,44.151699,0.0 24.112841,44.152069,0.0 24.107710,44.153358,0.0 24.105780,44.153809,0.0 24.102489,44.154678,0.0 24.101170,44.155102,0.0 24.100401,44.155399,0.0 24.097790,44.156681,0.0 24.097340,44.156818,0.0 24.095270,44.157291,0.0 24.094919,44.157410,0.0 24.090691,44.159679,0.0 24.087879,44.160992,0.0 24.085251,44.161980,0.0 24.080259,44.163780,0.0 24.054230,44.172298,0.0 24.042780,44.176102,0.0 &lt/coordinates&gt&lt/LineString&gt&lt/MultiGeometry&gt";
$insertQuery = "insert into 1_in5SzLPuEV-MnS_Eq1vf2D4ICJJI4wR7bQ5hOo (kml,dn,km_start,km_end,text,iconName,lastUpdate) values ('{$local_kml}','test4','{$km_start }','{$km_end}','{$cauza}','{$snowflake_simple}',1)";
$ftclient=ConnectFusion($client);
var_dump($ftclient->query->sql($insertQuery));

Warning: file_get_contents(compress.zlib://https://www.googleapis.com/fusiontables/v1/query): failed to open stream: operation failed in .../Google/IO/Stream.php on line 115

Fatal error: Uncaught exception 'Google_IO_Exception' with message 'HTTP Error: Unable to connect' in .../Google/IO/Stream.php:118 Stack trace: #0 .../Google/Http/REST.php(42): Google_IO_Stream->makeRequest(Object(Google_Http_Request)) #1 .../Google/Client.php(487): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request)) #2 .../Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request)) #3 /.../Google/Service/Fusiontables.php(682): Google_Service_Resource->call('sql', Array, 'Google_Service_...') #4 /../my.php(113): Google_Service_Fusiontables_Query_Resource->sql('insert into 1_i...') #5 .../my.php(59): test(Object(Google_ in ../Google/IO/Stream.php on line 118

It works if I remove some coordonates from $local_kml.

Return HTTP Code in Media File Upload

It seems like it should be easier to get the HTTP Response Code from MediaFileUpload.php, so if there is an error it can be retried.

For example declaring a variable
/** @var int $httpResultCode */
private $httpResultCode;

adding the function

public function getHttpResultCode()
{
    return $this->httpResultCode;
}

and setting

$code = $response->getResponseHttpCode();

$this->httpResultCode = $code;

in the nextChunk function

Another related question - if I am using the upload example from https://github.com/google/google-api-php-client/blob/master/examples/fileupload.php - and I am looping through, checking for errors would $status = $media->nextChunk(false); just try uploading the last chunk that was set in nextChunk again?

Insert object into google cloud storage returns 'no such bucket'

Im using google-api-php-client. I´m authenticating with service account and recieving TOKEN ok. Trying to insert object in Google Cloud Storage, using Google Cloud Storage JSON api.

When trying to INSERT object into BUCKET, returns: NoSuchBucket-The specified bucket does not exist. But I can assure that it does exist, as I can see in the web manager console, and already have images I´ve uploaded days ago.

The complete message says: Error calling POST https://www.googleapis.com/upload/storage/v1beta2/b/{here-goes-my-existing-bucket-name}/o?uploadType=multipart&name=thec36b23baf2778d.jpg: (404)

How may I start debuging to find the issue?

thanks

File upload generating incorrect request URL

When executing examples/simplefileupload.php a fatal Google_IO_Exception of "HTTP Error: Unable to connect" is thrown in Google_IO_Stream::makeRequest() at line 112. This is due to the request URL from Google_Http_Request::getUrl() resulting in a value of "/upload/drive/v2/files?uploadType=media" while I was expecting a fully qualified domain name to be included, such as "https://www.googleapis.com" from Google_Config::getBasePath().

I stepped through the execution and noticed Google_Service_Resource::call() is trying to help out a file upload by creating a new instance of Google_Http_MediaFileUpload. However, Google_Http_MediaFileUpload will set the Google_Http_Request::$baseComponent in Google_Http_MediaFileUpload ::transformToUploadUrl() before Google_Http_REST::execute() gets a chance to set the value at line 44.

Backtrace
6. throw() at /vagrant/src/Google/IO/Stream.php: 112
5. makeRequest() at /vagrant/src/Google/Http/REST.php: 46
4. execute() at /vagrant/src/Google/Client.php: 492
3. execute() at /vagrant/src/Google/Service/Resource.php: 194
2. call() at /vagrant/src/Google/Service/Drive.php: 1696

  1. insert() at /vagrant/examples/simplefileupload.php: 86

File cache locking issue

Trying to get a google+ sign in working, I ran across an issue where the file cache was failing to write any data into the cache file, giving a warning such as:

Warning: file_put_contents(): Only 0 of 5610 bytes written, possibly out of free disk space in D:\Web\igorally\site\vendor\google\apiclient\src\Google\Cache\File.php line 73

Spent a while messing with permissions figuring that was the cause, but when I dived into the code I saw the issue was caused by the file locking setup.

Locking the file using fopen/flock prevents file_put_contents from writing to that same file. Changing the line to fwrite resolved the problem.

$result = file_put_contents($storageFile, $data);

changed to

$result = fwrite($this->fh, $data);

How can I retrieve contacts using this?

I have been looking through all of the examples

here https://developers.google.com/api-client-library/php/
and here https://github.com/google/google-api-php-client/tree/master/examples

and the services https://github.com/google/google-api-php-client/tree/master/src/Google/Service

but there doesn't appear to be any services which use the scopes which the api documentation states to use.

This may not be the right place to ask but I'm struggling to find any useful documentation or working tutorials which relate to this.

Cheers

YouTubePartner.php not found

Hello

We here at Altafonte Music Network are trying to connect our automated system with your APIs. We’re working with Google API YoutubePartners.

Our main goal is to upload audio references to match and automatically claim videos. We work ok PHP.

We’re following this example:
https://developers.google.com/youtube/partner/code_samples/php#uploading_a_new_reference__so_youtube_can_automatically_generate_claims_for_newly_uploaded_videos_on_behalf_of_the_asset_s_owner
(second half of the doc)

We got it through the old API (Google API PHP Client 0.6.7) and the "Google_YouTubePartnerService.php" file we found here: https://developers.google.com/youtube/partner/client_libraries , but this isn’t useful because we need “Service account” authentication, and the API doesn’t work with this.

So, we tried with Google API PHP Client 1.0.0 unsuccessfully. We get the authentication but we need to find this file: "Google/Service/YouTubePartner.php”, called by your example on the URL mentioned above: https://developers.google.com/youtube/partner/code_samples/php

Thanks for your help!

listEvents "id" parameter in request

My code looks something like this:

...
$service = new Google_Service_Calendar($client);
$events = $service->events->listEvents('{my_nonurlencoded_calendar}');

This returns:

[09-Dec-2013 06:51:32 UTC] PHP Fatal error:  Uncaught exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/calendar/v3/calendars/{my_calendar}%7Bid%7D?key={my_key}: (404) Not Found'

Note the %7Bid%7D. I scouted around the best I could to try to find where that request parameter is added to no avail.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.