Google-api-php-client - A PHP client library for accessing Google APIs

Last update: Aug 14, 2022

Google APIs Client Library for PHP

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.12.1

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.12.1"
    },
    "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 explicity 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.

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 its 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

GitHub

https://github.com/googleapis/google-api-php-client
Comments
  • 1. refresh_token is not avaliable in response

    using following code to get token but there is no refresh token available in json

    $client->setAccessType("offline"); $client->authenticate($_GET['code']); $client->setApprovalPrompt("auto"); $_SESSION['upload_token'] = $client->getAccessToken();

    print_r($_SESSION['upload_token']);

    output :

    {"access_token":"ya29.PgB0miRDMD3H-iAAAAD88eQLK9N84muCYYR4TEhwffsj5yNJBXMt34Sd6B815Q","token_type":"Bearer","expires_in":3597,"created":1404986763}

    i am trying to refresh token for my app i want to show google drive list but after login and connect to the drive after some time token expired and unable to refresh the token

    i want to save the token in database and use it for next time so user can access his google drive any time after connection it.

    if i try following code

    $client->refreshToken($google_token);

    getting following error

    Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'

    Reviewed by navneetccna at 2014-07-22 11:46
  • 2. Fatal error: Class 'Google_Client' not found

    Api installed manually, not via Composer, downloaded from here (first zip): https://github.com/google/google-api-php-client/releases

    I got this error, trying to instantiate the main class: Fatal error: Class 'Google_Client' not found

    • Php "require_once" looks ok (no error).
    • Json's credentials looks ok (no error).
    • Class instance not ok.

    require_once('./vendor/autoload.php'); putenv('GOOGLE_APPLICATION_CREDENTIALS=./mycredentials.json'); $client = new Google_Client(); $client->useApplicationDefaultCredentials(); $client->setScopes('https://www.googleapis.com/auth/fusiontables'); $service = new Google_Service_Fusiontables($client);

    This is the source code I can see in /vendor/autoload.php `<?php

    // autoload.php @generated by Composer

    require_once DIR . '/composer' . '/autoload_real.php';

    return ComposerAutoloaderInit9c18b0e2f8ac75b5fbc347bb34dca41d::getLoader();`

    Any hint?

    Reviewed by simonericci at 2017-05-05 16:42
  • 3. Unsupported SSL context options are set. The following options are present, but have been ignored: cafile

    Since earlier today (around 9:35AM EST), I'm getting this error message in the log:

      E 2015-07-09 10:35:51.967  200     779 B   889ms E 10:35:51.611 E 10:35:51.817 /[email protected]&_=1436448941263
      190.188.222.26 - XXX [09/Jul/2015:06:35:51 -0700] "GET /[email protected]&_=1436448941263 HTTP/1.1" 200 779 - "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.61 Safari/537.36" "mailroof-test.appspot.com" ms=889 cpu_ms=329 cpm_usd=0.000177 instance=00c61b117c0ffb0afc187ade6b0e941e8ff97f60 app_engine_release=1.9.24
      E 10:35:51.611 Unsupported SSL context options are set. The following options are present, but have been ignored: cafile
    

    Still, the code seems to "work" in the sense that nothing is broken or missing in the functionality. But it is getting my log file full with this anoyment.

    BTW, I was using PHP API 1.1.2 and today I upgraded to1.1.4 and later to the master version. I noticed the error log long after that and I thought that upgrade could be causing it. So I rolled back all the changes but still the error is there.

    Any ideas of what could be causing this? and a solution?

    PS: It seems to my like a ssl certificate error. Is it really possible?

    Reviewed by nebadom at 2015-07-09 22:37
  • 4. cURL error 60

    Fatal error: Uncaught exception 'GuzzleHttp\Exception\RequestException' with message 'cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)' in D:\bin\xampp\htdocs\google-api-php-client\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php:187 Stack trace: #0 D:\bin\xampp\htdocs\google-api-php-client\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(150): GuzzleHttp\Handler\CurlFactory::createRejection(Object(GuzzleHttp\Handler\EasyHandle), Array) #1 D:\bin\xampp\htdocs\google-api-php-client\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php(103): GuzzleHttp\Handler\CurlFactory::finishError(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleHttp\Handler\CurlFactory)) #2 D:\bin\xampp\htdocs\google-api-php-client\vendor\guzzlehttp\guzzle\src\Handler\CurlHandler.php(43): GuzzleHttp\Handler\CurlFactory::finish(Object(GuzzleHttp\Handler\CurlHandler), Object(GuzzleHttp\Handler\EasyHandle), Object(GuzzleH in D:\bin\xampp\htdocs\google-api-php-client\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 187

    What is this problem? How can I solve this? I checked a lot of links related with this, but no result. Please help me all. Thanks for your time.

    Reviewed by amitsadana444 at 2016-02-10 06:33
  • 5. Fix #400: move autoloader to src/Google

    This makes system-wide installation of the library more viable.

    It's a quick job, but it looks fine. I ran the test suite and got the same results before and after.

    Reviewed by AdamWill at 2014-12-20 20:52
  • 6. Sporadic "Invalid Credentials" Issues - Service Account

    I seem to be having weird issues with "Invalid Credentials" errors, service accounts and the Search Console API. Sometimes everything works and I can access the API, then some time later I may try an access the SC API and I get an "Invalid Credentials" error. This is without changing any code.

    Edit: Very weird. I swapped around my scopes and then it started working again. Nothing else was changed. Why would swapping my scopes around every so often work?

    Here is what I am using:

    class Google {
    
        private function googleApiAuthorise()
        {
    
            $client = new \Google_Client();
            putenv('GOOGLE_APPLICATION_CREDENTIALS=' . base_path() . '/keys/Tool-xxxxxxxxx.json');
            $client->useApplicationDefaultCredentials();
            $client->setSubject([email protected]');
            $client->setApplicationName("Tool");
            $scopes = ['https://www.googleapis.com/auth/webmasters.readonly', 'https://www.googleapis.com/auth/webmasters'];
            $client->setScopes($scopes);
    
            if( $client->isAccessTokenExpired()) {
    
                $client->refreshTokenWithAssertion();
    
            }
    
            return $client;
    
        }
    
        public function getSearchAnalytics($search_type = 'web')
        {
    
            $authorise = Google::googleApiAuthorise();
    
            $service = new \Google_Service_Webmasters($authorise);
    
            $request = new \Google_Service_Webmasters_SearchAnalyticsQueryRequest;
    
            $request->setStartRow(0);
            $request->setStartDate('2016-06-01');
            $request->setEndDate(Carbon::now()->toDateString());
            $request->setSearchType($search_type);
            $request->setRowLimit(200);
            $request->setDimensions(array('date','page','country','device','query'));
    
            $query_search = $service->searchanalytics->query("http://www.example.com/", $request); 
            $rows = $query_search->getRows();
    
            return $rows;
    
        }
    }
    

    The weird thing is it works sometimes. Is this some sort of bug? I've followed pretty much every tutorial out there about service accounts and this API client, but it still seems to be quite random as to why sometimes I can use the API and other times I get an "Invalid Credentials" error.

    Reviewed by strategyst at 2016-10-12 22:34
  • 7. Downloading a document using export link is not working

    When trying to download a file without a download link using it's export link new library give authentication error and says that the file does not exist. File is owned by the user which uses the API. In old version 0.6.* this problem did not occure.

    Here's a piece of code:

    try {
                /* @var Google_Service_Drive_DriveFile $file */
                $file = $service->files->get($id);
            } catch (Google_Exception $e) {
                $this->_setError(sprintf('Error retrieving file data by id "%s". Error thrown: %s', $id, $e->getMessage()));
                return false;
            }
    
            $downloadUrl = $file->getDownloadUrl();
    
            //Native Google Drive files do not have a download link, use (standard) export link.
            if (!$downloadUrl) {
                $exportLinks = $file->getExportLinks();
    
                    switch ($file->getMimeType()) {
                        case self::FILE_TYPE_SPREADSHEET:
                        case self::FILE_TYPE_FORM:
                            $exportFormat = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                            break;
    
                        case self::FILE_TYPE_DOCUMENT:
                            $exportFormat = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                            break;
    
                        case self::FILE_TYPE_PRESENTATION:
                            $exportFormat = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
                            break;
    
                        default:
                            $keys = array_keys($exportLinks);
                            $exportFormat = $keys[0];
                            break;
                    }
    
                $downloadUrl = $exportLinks[$exportFormat];
            }
    
            if ($downloadUrl) {
                $request = new Google_Http_Request($downloadUrl);
                $clientAuth = $this->_getClient()->getAuth();
                $clientAuth->sign($request);
                $httpRequest = $clientAuth->authenticatedRequest($request);
    
                            /* if the file is not created via API responce code is always 404 */
                if ($httpRequest->getResponseHttpCode() == 200) {}
                   }
    }
    
    Reviewed by ghost at 2014-02-21 08:26
  • 8. Getting access and refresh token from auth code without a redirect

    As asked in https://www.en.advertisercommunity.com/t5/Basics-for-Business-Owners/GMB-authentication-from-JavaScript-API-and-consume-from-offline/m-p/1747992#M79307

    I am trying to use an auth code generated from the Javascript Client to then get access and refresh token. But when i call

    $client->fetchAccessTokenWithAuthCode($code);

    with a code generated on javascript I do not get the tokens. Is there a way to implement this so a redirect approach is not required? Redirects are really dirty and just not elegant and complex to handle for one page apps.

    Reviewed by bizmate at 2018-06-30 00:52
  • 9. Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\google\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67

    Hello,

    I am trying to use the Google API client to make a dashboard with relevant information. However, when I follow the steps on the hello analytics tutorial, and try to connect, I get the following error:

    Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\google\vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php on line 67

    How would I go about solving this? Thanks.

    Reviewed by wubs23 at 2018-03-05 13:08
  • 10. OAuth2 callback verification hangs server on PHP 5.5

    on google app engine, the $client->authenticate($_GET['code']); call is still working, but moving to AWS EC2 using Elastic Beanstalk on PHP 5.5, that call generates an error in the log that completely hangs the server and returns nothing. here is the error:

    [Thu May 29 21:10:05.925138 2014] [core:notice] [pid 28838] AH00052: child pid 31163 exit signal Illegal instruction (4)

    any idea what this could be? would it work on PHP 5.4 or 5.3?

    Reviewed by cloudward at 2014-05-30 16:51
  • 11. simple-query.php example returns 'HTTP Error: Unable to connect: '0''

    Hi -

    I am newish to PHP and very new to the Google API's, so my apologies in advance if I am making an idiot of myself.

    As mentioned, I am new to the Google API's, so after downloading the source I decided to start with the simple-query example.

    I created a Simple API key - with no restrictions on the URI's - inserted it in the code, ran the code and promptly received the above error message, i.e. "HTTP Error: Unable to connect: '0'".

    After some playing I was able to identify the problem line as being line #117 in the module IO\Abstract, i.e.:

    "list($responseData, $responseHeaders, $respHttpCode) = $this->executeRequest($request);"

    A var_dump of $request returned the following: class Google_Http_Request#21 (14) { private $batchHeaders => array(3) { 'Content-Type' => string(16) "application/http" 'Content-Transfer-Encoding' => string(6) "binary" 'MIME-Version' => string(3) "1.0" } protected $queryParams => array(3) { 'q' => string(19) "Henry David Thoreau" 'filter' => string(11) "free-ebooks" 'key' => string(39) "yCo0************_Jvima_**" } protected $requestMethod => string(3) "GET" protected $requestHeaders => array(0) { } protected $baseComponent => string(26) "https://www.googleapis.com" protected $path => string(17) "/books/v1/volumes" protected $postBody => NULL protected $userAgent => string(56) "Client_Library_Examples google-api-php-client/1.0.5-beta" protected $canGzip => NULL protected $responseHttpCode => NULL protected $responseHeaders => NULL protected $responseBody => NULL protected $expectedClass => string(28) "Google_Service_Books_Volumes" public $accessKey => NULL }

    A try-catch block around the offending line returned the following: I/O Abstract call error: HTTP Error: Unable to connect: '0' #0 C:\srv\GoogleApi\Google\IO\Abstract.php(120): Google_IO_Stream->executeRequest(Object(Google_Http_Request)) #1 C:\srv\GoogleApi\Google\Http\REST.php(42): Google_IO_Abstract->makeRequest(Object(Google_Http_Request)) #2 C:\srv\GoogleApi\Google\Client.php(499): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request)) #3 C:\srv\GoogleApi\Google\Service\Resource.php(195): Google_Client->execute(Object(Google_Http_Request)) #4 C:\srv\GoogleApi\Google\Service\Books.php(2304): Google_Service_Resource->call('list', Array, 'Google_Service_...') #5 C:\srv\GoogleApi\simple-query.php(68): Google_Service_Books_Volumes_Resource->listVolumes('Henry David Tho...', Array) #6 {main}

    NB: The line number shown above is 120, i.e. original line number #117 plus three lines for the var_dump and the try-catch.

    Technical stuff: Windows 7 Ultimate / PHP 5.5.11 / Apache 2.4

    Tested using PhpStorm version 7 / IE version 11 / Firefox version 29

    Any assistance greatly appreciated ...

    Reviewed by rowanrh at 2014-05-19 10:43
  • 12. Uploading empty file using drive API

    The example in the documentation loaded an empty file when I tested it, but debugging found that it loaded normally with this code

     $file = $driveService->files->create($fileMetadata, array([
                'data' => $content,
                'mimeType' => 'image/jpeg',
                'uploadType' => 'multipart',
                'fields' => 'id'],
           'data' => $content));
    

    /src/Service/Resource.php seems to be missing a foreach before line 209 (if (isset($parameters['data'])) {) why arrive like this $parameters[0]['data']

    thanks

    Reviewed by tulioluizm at 2022-08-12 13:51
  • 13. GuzzleHttp timeout

    The timeout parameter is not set. When creating the auth request, it is in the code src/AuthHandler/Guzzle6AuthHandler.php

    private function createAuthHttp(ClientInterface $http)
        {
            return new Client([
                'base_uri' => $http->getConfig('base_uri'),
                'http_errors' => true,
                'verify' => $http->getConfig('verify'),
                'proxy' => $http->getConfig('proxy'),
            ]);
        }
    
    Reviewed by dolphin17 at 2022-08-11 07:31
  • 14. google api allow users to connect when 3P cookies are not available

    I use google/apiclient and version 2.12 for develop authentification system with google but in private navigation I found button blocked cookies enabled for default and this button blocked authentification and acces , where is solution with google api to allow user connect with gmail when blocked cookies in private navigation

    Reviewed by mabaied at 2022-08-10 08:24
  • 15. Running Youtube Comment Thread Insert Works Locally But Deployed to Server Rec'v 400 (same exact code)

    Environment details

    • OS: ubuntu 20
    • PHP version: 8.1
    • Package name and version: google api php latest

    code

    This is my code (sorry after tons of trying random crap to try and figure out the issue). I can post a comment just fine if I run this exact code locally. Just deployed to my production server - and this is the error i receive -

    image

    No freaking clue why. I have tried several things. I've tried disabling SSL verification in guzzle defaults. I can see that it properly is set before sending - didnt work (a suggestion i found elsewhere)

    I tried adding my cert path to the curl cainfo setting in php ini - in case it mattered as someone thought somewhere else... didnt help (yes restarted apache2 afterwards)

    I tried everything under the sun. Tried hitting the site from non-https as well just to see if it mattered.

    Funny thing is - i can even get it to work when i run my local through ngrok. It's JUST on production. When searching around I have found a handful of stragglers in the wild with the same issue, sadly no responses to their pain. And its pain.

    Thanks for any help.

    Reviewed by bryanbassett at 2022-08-05 18:52
  • 16. Undefined index: type in ..\vendor\google\apiclient\src\Service\Resource.php:281

    Hi I'm getting undefined index 'type' and 'location' when trying to upload a 2MB csv file to Google Drive but I can't find any docs about 'type' and 'location' parameters.

    $driveService = $this->getDriveInstance();
    
      $fileMetadata = new \Google\Service\Drive\DriveFile(array(
          'parents' => array('xxxxxxxxx')
      ));
      
      $file = $driveService->files->create($fileMetadata, array(
          [
              'data' => $stringContent,
              'mimeType' => 'text/csv',
              'uploadType' => 'media',
          ]
      ));
    

    Thanks!

    Reviewed by arlequin99 at 2022-08-02 18:11
  • 17. Indexing API Batch Request API Quota Issue

    Hi,

    I am using Batch service to Publish URLs to indexing API. But It is count each Urls as single request, but It should be 1 request for 1 batch?

    My issue is If I Publish 20 URls in single batch request it is counting as 20 Publish requests per day instead 1 request.

    $client = new \Google_Client();
    
    $client->setAuthConfig('/var/www/html/privateKey.json');
    $client->addScope('https://www.googleapis.com/auth/indexing');
    $client->setUseBatch(true);
    
    $service = new \Google_Service_Indexing($client);
    $batch = $service->createBatch();
    
    // add request
    $postBody = new \Google_Service_Indexing_UrlNotification();
    foreach ($urlList as $url) {
        $postBody->setType('URL_UPDATED');
        $postBody->setUrl($url);
        $batch ->add($service->urlNotifications->publish($postBody));
    }
    // ---- add request
    
    $results = $batch->execute(); // it does authorize in execute()
    
    Reviewed by chiragvels at 2022-07-29 09:30
Google PHP API Client Services

Google PHP API Client Services

Aug 7, 2022
OVHcloud APIs lightweight PHP wrapper

Lightweight PHP wrapper for OVHcloud APIs - The easiest way to use OVHcloud APIs in your PHP applications - Compatible with PHP 7.4, 8.0, 8.1 - Not affiliated with OVHcloud

Jul 27, 2022
Laravel Package for 1APP. Learn how to integrate our APIs to build a web or mobile integration to send and accept payments for your application and businesses.
Laravel Package for 1APP. Learn how to integrate our APIs to build a web or mobile integration to send and accept payments for your application and businesses.

1APP Laravel Library Learn how to integrate our APIs to build a web or mobile integration to accept payments, make payment of Bills and as well custom

Jul 25, 2022
PHP client library for the DynamicPDF Cloud API.
PHP client library for the DynamicPDF Cloud API.

PHP Client (php-client) The PHP Client (php-client) project uses the DynamicPDF Cloud API's PHP client library to create, merge, split, form fill, sta

Nov 29, 2021
Nexmo REST API client for PHP. API support for SMS, Voice, Text-to-Speech, Numbers, Verify (2FA) and more.

Client Library for PHP Support Notice This library and it's associated packages, nexmo/client and nexmo/client-core have transitioned into a "Maintena

Jul 21, 2022
DigitalOcean API v2 client for Symfony and API Platform

DigitalOcean Bundle for Symfony and API Platform DunglasDigitalOceanBundle allows using the DigitalOcean API from your Symfony and API Platform projec

Jul 27, 2022
API client for ThePay - payment gate API
API client for ThePay - payment gate API

This is the official highly compatible public package of The Pay SDK which interacts with The Pay's REST API. To get started see examples below.

May 23, 2022
A versatile PHP Library for Google PageSpeed Insights

PhpInsights An easy-to-use API Wrapper for Googles PageSpeed Insights. The JSON response is mapped to objects for an headache-free usage. Installation

Jun 24, 2022
PHP package to manage google-api interactions

Google-api-client PHP package to manage google-api interactions Supports: Google Drive API Google Spreadsheet API Installation composer require obrio-

Apr 28, 2022
🌐 Free Google Translate API PHP Package. Translates totally free of charge.

Google Translate PHP Free Google Translate API PHP Package. Translates totally free of charge. Installation Basic Usage Advanced Usage Language Detect

Aug 10, 2022
Google Drive Api Wrapper by PHP

GoogleDrive Api Wrapper usage at first you need to create oauth client on google cloud platform. so go to the your google console dashboard and create

Mar 24, 2022
Google Translator Api Wrapper For Php Developers.

Google Translator Api Wrapper For Php Developers.

May 16, 2022
PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

PHP JSON-RPC 2.0 Server/Client Implementation with Automatic Client Class Generation via SMD

Feb 14, 2022
An elegant wrapper around Google Vision API
An elegant wrapper around Google Vision API

STILL UNDER DEVELOPMENT - DO NOT USE IN PRODUCTION Requires PHP 8.0+ For feedback, please contact me. This package provides an elegant wrapper around

Aug 5, 2022
Simple Google Tts Api Class

Simple Google Tts Api Class

Nov 7, 2021
oursms.app client library that allows you to send SMS

Oursms laravel client https://oursms.app client library that allows you to send SMS Installation Install oursms client with composer composer requir

Jun 11, 2021
⚡️ Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC.
⚡️ Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC.

Web3 PHP is a supercharged PHP API client that allows you to interact with a generic Ethereum RPC. This project is a work-in-progress. Code and docume

Aug 6, 2022
A simple PHP GitHub API client, Object Oriented, tested and documented.

PHP GitHub API A simple Object Oriented wrapper for GitHub API, written with PHP. Uses GitHub API v3 & supports GitHub API v4. The object API (v3) is

Aug 13, 2022
A simple Object Oriented PHP Client for Termii SMS API

Termii Client A simple Object Oriented PHP Client for Termii SMS API. Uses Termii API. Requirements PHP >= 7.2 Guzzlehttp ~6|~7 Installation Via Compo

Feb 24, 2022