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

Overview

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
Comments
  • Fatal error: Class 'Google_Client' not found

    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?

    opened by simonericci 29
  • refresh_token is not avaliable in response

    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" }'

    triage me :rotating_light: 
    opened by navneetccna 29
  • Unsupported SSL context options are set. The following options are present, but have been ignored: cafile

    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?

    opened by nebadom 26
  • cURL error 60

    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.

    opened by amitsadana444 25
  • Fix #400: move autoloader to src/Google

    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.

    cla: yes 
    opened by AdamWill 24
  •  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

    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.

    type: question 
    opened by wubs23 22
  • Sporadic

    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.

    opened by strategyst 22
  • Downloading a document using export link is not working

    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) {}
                   }
    }
    
    triage me :rotating_light: 
    opened by ghost 22
  • Getting access and refresh token from auth code without a redirect

    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.

    type: question 
    opened by bizmate 21
  • OAuth2 callback verification hangs server on PHP 5.5

    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?

    triage me :rotating_light: 
    opened by cloudward 21
  • simple-query.php example returns 'HTTP Error: Unable to connect: '0''

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

    triage me :rotating_light: 
    opened by rowanrh 21
  • google-api-php-client

    google-api-php-client

    Hi, I downloaded google-api-php-client v2.13.0 via composer using composer command. But i cant see the latest downloaded version in Client.php file which resides src directory instead that i have v2.12.6 only.

    Kindly update the current version of google-api-php-client in Client.php file.

    opened by BalachandarNatarajan 0
  • New authorization URI is a breaking change

    New authorization URI is a breaking change

    See https://github.com/googleapis/google-api-php-client/pull/2275

    Updating to the v2 auth URL broke the behavior of using setApprovalPrompt('force'), which was deprecated in favor of instead of the newer setPrompt('consent').

    In order to mitigate this breaking change, we could update the setApprovalPrompt function to call setPrompt('consent') instead.

    opened by bshaffer 0
  • feat: add support for PHP 8.2 ✨

    feat: add support for PHP 8.2 ✨

    Main changes

    • Run tests with PHP 8.2
    • Run all php versions with --prefer-lowest and --prefer-stable
    • Added 8.1 where missing
    • Run actions on feature branches
    opened by Nielsvanpach 2
  • Sometimes getting http 401 on requests

    Sometimes getting http 401 on requests

    We are using current v2.16.2. This works fine most of the time. But sometimes we get a http 401 back like this:

    Google\Http\REST::decodeHttpResponse()
    #1 [internal function]: Google\Http\REST::doExecute()
    #2 /var/www/html/magento2/vendor/google/apiclient/src/Task/Runner.php(187): call_user_func_array()
    #3 /var/www/html/magento2/vendor/google/apiclient/src/Http/REST.php(66): Google\Task\Runner->run()
    #4 /var/www/html/magento2/vendor/google/apiclient/src/Client.php(920): Google\Http\REST::execute()
    #5 /var/www/html/magento2/vendor/google/apiclient/src/Service/Resource.php(238): Google\Client->execute()
    #6 /var/www/html/magento2/vendor/google/apiclient-services/src/Sheets/Resource/SpreadsheetsValues.php(271): Google\Service\Resource->call()
    #7 /var/www/html/magento2/vendor/bobbie/module-tender/Helper/GoogleApi.php(189): Google\Service\Sheets\Resource\SpreadsheetsValues->update()
    #8 /var/www/html/magento2/vendor/bobbie/module-tender/Model/GoogleSheet.php(91): Bobbie\Tender\Helper\GoogleApi->setSpreadSheetValue()
    #9 /var/www/html/magento2/vendor/bobbie/module-tender/Model/TenderSheet.php(488): Bobbie\Tender\Model\GoogleSheet->setValue()
    [2022-11-29T14:44:41.634244+00:00] main.ERROR: {
      "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "errors": [
          {
            "message": "Invalid Credentials",
            "domain": "global",
            "reason": "authError",
            "location": "Authorization",
            "locationType": "header"
          }
        ],
        "status": "UNAUTHENTICATED"
      }
    }
     [] []
    

    Just milliseconds before I had successfull requests, and we are checking token lifetime frequently using:

     if ($this->getClient()->isAccessTokenExpired()) {
                // Refresh the token if possible, else fetch a new one.
                if ($this->client->getRefreshToken()) {
                    $this->client->fetchAccessTokenWithRefreshToken($this->client->getRefreshToken());
                    $this->persistToken($this->client);
    
    opened by alexgran 2
Releases(v2.13.0)
Owner
Google APIs
Clients for Google APIs and tools that help produce them.
Google APIs
SendGrid's PHP HTTP Client for calling APIs

Quickly and easily access any RESTful or RESTful-like API. If you are looking for the SendGrid API client library, please see this repo. Announcements

Twilio SendGrid 119 Nov 25, 2022
Google PHP API Client Services

Google PHP API Client Services

Google APIs 1.1k Dec 22, 2022
Attempting to create an intelligent mock of the Google API PHP Client for unit and functional testing

google-api-php-client-mock A small scale intelligent mock of the Google API PHP Client for unit and functional testing. Overview This is intended to m

SIL International 0 Jan 4, 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

Germain Carré 3 Sep 10, 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.

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

O'Bounce Technologies 4 Jul 25, 2022
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

DynamicPDF Cloud API 0 Nov 29, 2021
API Client library for PHP

ChronoSheetsAPI ChronoSheets is a flexible timesheet solution for small to medium businesses, it is free for small teams of up to 3 and there are iOS

Lachlan P 0 May 23, 2022
Client library to consume the 42 Intranet's API

ft-client Client library to consume the 42 Intranet's API Installation composer require mehdibo/ft-client Usage examples Using the Authorization Code

Mehdi Bounya 3 Nov 23, 2022
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

Nexmo 75 Sep 23, 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

Kévin Dunglas 25 Jul 27, 2022
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.

ThePay.cz s.r.o. 3 Oct 27, 2022
Code Quiz MonoRepo (API, API Client, App)

Code Quiz Welcome to the Code Quiz Open Source project from How To Code Well. This is an Open Source project that includes an API and an App for the d

How To Code Well 2 Nov 20, 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

Daniel Sentker 110 Dec 28, 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-

OBRIO 3 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

Levan Velijanashvili 1.5k Dec 31, 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

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

Google Translator Api Wrapper For Php Developers.

Roldex Stark 2 Oct 12, 2022
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

Ahmad Mayahi 24 Nov 20, 2022
Simple Google Tts Api Class

Simple Google Tts Api Class

Ömer Faruk Demirel 2 Dec 2, 2022