• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

.github/H03-May-2022-96

examples/H03-May-2022-1,422884

src/Google/H03-May-2022-4,0762,446

style/H03-May-2022-16089

tests/H03-May-2022-4,9953,450

.travis.ymlH A D12-Nov-20211 KiB4836

CONTRIBUTING.mdH A D12-Nov-20211.5 KiB2314

LICENSEH A D12-Nov-202110 KiB204169

README.mdH A D12-Nov-202114.6 KiB377263

UPGRADING.mdH A D12-Nov-202111.2 KiB328254

composer.jsonH A D12-Nov-20211.2 KiB4241

phpunit.xml.distH A D12-Nov-2021691 2019

README.md

1[![Build Status](https://travis-ci.org/google/google-api-php-client.svg?branch=master)](https://travis-ci.org/google/google-api-php-client)
2
3# Google APIs Client Library for PHP #
4
5The Google API Client Library enables you to work with Google APIs such as Google+, Drive, or YouTube on your server.
6
7These 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.
8
9## Google Cloud Platform
10
11For Google Cloud Platform APIs such as Datastore, Cloud Storage or Pub/Sub, we recommend using [GoogleCloudPlatform/google-cloud-php](https://github.com/GoogleCloudPlatform/google-cloud-php) which is under active development.
12
13## Requirements ##
14* [PHP 5.4.0 or higher](http://www.php.net/)
15
16## Developer Documentation ##
17http://developers.google.com/api-client-library/php
18
19## Installation ##
20
21You can use **Composer** or simply **Download the Release**
22
23### Composer
24
25The preferred method is via [composer](https://getcomposer.org). Follow the
26[installation instructions](https://getcomposer.org/doc/00-intro.md) if you do not already have
27composer installed.
28
29Once composer is installed, execute the following command in your project root to install this library:
30
31```sh
32composer require google/apiclient:^2.0
33```
34
35Finally, be sure to include the autoloader:
36
37```php
38require_once '/path/to/your-project/vendor/autoload.php';
39```
40
41### Download the Release
42
43If you abhor using composer, you can download the package in its entirety. The [Releases](https://github.com/google/google-api-php-client/releases) page lists all stable versions. Download any file
44with the name `google-api-php-client-[RELEASE_NAME].zip` for a package including this library and its dependencies.
45
46Uncompress the zip file you download, and include the autoloader in your project:
47
48```php
49require_once '/path/to/google-api-php-client/vendor/autoload.php';
50```
51
52For additional installation and setup instructions, see [the documentation](https://developers.google.com/api-client-library/php/start/installation).
53
54## Examples ##
55See the [`examples/`](examples) directory for examples of the key client features. You can
56view them in your browser by running the php built-in web server.
57
58```
59$ php -S localhost:8000 -t examples/
60```
61
62And then browsing to the host and port you specified
63(in the above example, `http://localhost:8000`).
64
65### Basic Example ###
66
67```php
68// include your composer dependencies
69require_once 'vendor/autoload.php';
70
71$client = new Google_Client();
72$client->setApplicationName("Client_Library_Examples");
73$client->setDeveloperKey("YOUR_APP_KEY");
74
75$service = new Google_Service_Books($client);
76$optParams = array('filter' => 'free-ebooks');
77$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
78
79foreach ($results as $item) {
80  echo $item['volumeInfo']['title'], "<br /> \n";
81}
82```
83
84### Authentication with OAuth ###
85
86> An example of this can be seen in [`examples/simple-file-upload.php`](examples/simple-file-upload.php).
87
881. Follow the instructions to [Create Web Application Credentials](https://developers.google.com/api-client-library/php/auth/web-app#creatingcred)
891. Download the JSON credentials
901. Set the path to these credentials using `Google_Client::setAuthConfig`:
91
92    ```php
93    $client = new Google_Client();
94    $client->setAuthConfig('/path/to/client_credentials.json');
95    ```
96
971. Set the scopes required for the API you are going to call
98
99    ```php
100    $client->addScope(Google_Service_Drive::DRIVE);
101    ```
102
1031. Set your application's redirect URI
104
105    ```php
106    // Your redirect URI can be any registered URI, but in this example
107    // we redirect back to this same page
108    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
109    $client->setRedirectUri($redirect_uri);
110    ```
111
1121. In the script handling the redirect URI, exchange the authorization code for an access token:
113
114    ```php
115    if (isset($_GET['code'])) {
116        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
117    }
118    ```
119
120### Authentication with Service Accounts ###
121
122> An example of this can be seen in [`examples/service-account.php`](examples/service-account.php).
123
124Some APIs
125(such as the [YouTube Data API](https://developers.google.com/youtube/v3/)) do
126not support service accounts. Check with the specific API documentation if API
127calls return unexpected 401 or 403 errors.
128
1291. Follow the instructions to [Create a Service Account](https://developers.google.com/api-client-library/php/auth/service-accounts#creatinganaccount)
1301. Download the JSON credentials
1311. Set the path to these credentials using the `GOOGLE_APPLICATION_CREDENTIALS` environment variable:
132
133    ```php
134    putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
135    ```
136
1371. Tell the Google client to use your service account credentials to authenticate:
138
139    ```php
140    $client = new Google_Client();
141    $client->useApplicationDefaultCredentials();
142    ```
143
1441. Set the scopes required for the API you are going to call
145
146    ```php
147    $client->addScope(Google_Service_Drive::DRIVE);
148    ```
149
1501. 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:
151
152    ```php
153    $client->setSubject($user_to_impersonate);
154    ```
155
156### Making Requests ###
157
158The classes used to call the API in [google-api-php-client-services](https://github.com/Google/google-api-php-client-services) are autogenerated. They map directly to the JSON requests and responses found in the [APIs Explorer](https://developers.google.com/apis-explorer/#p/).
159
160A JSON request to the [Datastore API](https://developers.google.com/apis-explorer/#p/datastore/v1beta3/datastore.projects.runQuery) would look like this:
161
162```json
163POST https://datastore.googleapis.com/v1beta3/projects/YOUR_PROJECT_ID:runQuery?key=YOUR_API_KEY
164
165{
166    "query": {
167        "kind": [{
168            "name": "Book"
169        }],
170        "order": [{
171            "property": {
172                "name": "title"
173            },
174            "direction": "descending"
175        }],
176        "limit": 10
177    }
178}
179```
180
181Using this library, the same call would look something like this:
182
183```php
184// create the datastore service class
185$datastore = new Google_Service_Datastore($client);
186
187// build the query - this maps directly to the JSON
188$query = new Google_Service_Datastore_Query([
189    'kind' => [
190        [
191            'name' => 'Book',
192        ],
193    ],
194    'order' => [
195        'property' => [
196            'name' => 'title',
197        ],
198        'direction' => 'descending',
199    ],
200    'limit' => 10,
201]);
202
203// build the request and response
204$request = new Google_Service_Datastore_RunQueryRequest(['query' => $query]);
205$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
206```
207
208However, as each property of the JSON API has a corresponding generated class, the above code could also be written like this:
209
210```php
211// create the datastore service class
212$datastore = new Google_Service_Datastore($client);
213
214// build the query
215$request = new Google_Service_Datastore_RunQueryRequest();
216$query = new Google_Service_Datastore_Query();
217//   - set the order
218$order = new Google_Service_Datastore_PropertyOrder();
219$order->setDirection('descending');
220$property = new Google_Service_Datastore_PropertyReference();
221$property->setName('title');
222$order->setProperty($property);
223$query->setOrder([$order]);
224//   - set the kinds
225$kind = new Google_Service_Datastore_KindExpression();
226$kind->setName('Book');
227$query->setKinds([$kind]);
228//   - set the limit
229$query->setLimit(10);
230
231// add the query to the request and make the request
232$request->setQuery($query);
233$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
234```
235
236The 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](https://developers.google.com/apis-explorer/#p/) before using any of the services here.
237
238### Making HTTP Requests Directly ###
239
240If Google Authentication is desired for external applications, or a Google API is not available yet in this library, HTTP requests can be made directly.
241
242The `authorize` method returns an authorized [Guzzle Client](http://docs.guzzlephp.org/), so any request made using the client will contain the corresponding authorization.
243
244```php
245// create the Google client
246$client = new Google_Client();
247
248/**
249 * Set your method for authentication. Depending on the API, This could be
250 * directly with an access token, API key, or (recommended) using
251 * Application Default Credentials.
252 */
253$client->useApplicationDefaultCredentials();
254$client->addScope(Google_Service_Plus::PLUS_ME);
255
256// returns a Guzzle HTTP Client
257$httpClient = $client->authorize();
258
259// make an HTTP request
260$response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me');
261```
262
263### Caching ###
264
265It is recommended to use another caching library to improve performance. This can be done by passing a [PSR-6](http://www.php-fig.org/psr/psr-6/) compatible library to the client:
266
267```php
268use League\Flysystem\Adapter\Local;
269use League\Flysystem\Filesystem;
270use Cache\Adapter\Filesystem\FilesystemCachePool;
271
272$filesystemAdapter = new Local(__DIR__.'/');
273$filesystem        = new Filesystem($filesystemAdapter);
274
275$cache = new FilesystemCachePool($filesystem);
276$client->setCache($cache);
277```
278
279In this example we use [PHP Cache](http://www.php-cache.com/). Add this to your project with composer:
280
281```
282composer require cache/filesystem-adapter
283```
284
285### Updating Tokens ###
286
287When using [Refresh Tokens](https://developers.google.com/identity/protocols/OAuth2InstalledApp#refresh) or [Service Account Credentials](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#overview), 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:
288
289```php
290$logger = new Monolog\Logger;
291$tokenCallback = function ($cacheKey, $accessToken) use ($logger) {
292  $logger->debug(sprintf('new access token received at cache key %s', $cacheKey));
293};
294$client->setTokenCallback($tokenCallback);
295```
296
297### Debugging Your HTTP Request using Charles ###
298
299It is often very useful to debug your API calls by viewing the raw HTTP request. This library supports the use of [Charles Web Proxy](https://www.charlesproxy.com/documentation/getting-started/). Download and run Charles, and then capture all HTTP traffic through Charles with the following code:
300
301```php
302// FOR DEBUGGING ONLY
303$httpClient = new GuzzleHttp\Client([
304    'proxy' => 'localhost:8888', // by default, Charles runs on localhost port 8888
305    'verify' => false, // otherwise HTTPS requests will fail.
306]);
307
308$client = new Google_Client();
309$client->setHttpClient($httpClient);
310```
311
312Now all calls made by this library will appear in the Charles UI.
313
314One 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`.
315
316### Service Specific Examples ###
317
318YouTube: https://github.com/youtube/api-samples/tree/master/php
319
320## How Do I Contribute? ##
321
322Please see the [contributing](CONTRIBUTING.md) page for more information. In particular, we love pull requests - but please make sure to sign the [contributor license agreement](https://developers.google.com/api-client-library/php/contribute).
323
324## Frequently Asked Questions ##
325
326### What do I do if something isn't working? ###
327
328For support with the library the best place to ask is via the google-api-php-client tag on StackOverflow: http://stackoverflow.com/questions/tagged/google-api-php-client
329
330If there is a specific bug with the library, please [file a issue](https://github.com/google/google-api-php-client/issues) 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.
331
332### I want an example of X! ###
333
334If 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!
335
336### Why do you still support 5.2? ###
337
338When we started working on the 1.0.0 branch we knew there were several fundamental issues to fix with the 0.6 releases of the library. At that time we looked at the usage of the library, and other related projects, and determined that there was still a large and active base of PHP 5.2 installs. You can see this in statistics such as the PHP versions chart in the WordPress stats: http://wordpress.org/about/stats/. We will keep looking at the types of usage we see, and try to take advantage of newer PHP features where possible.
339
340### Why does Google_..._Service have weird names? ###
341
342The _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.
343
344### How do I deal with non-JSON response types? ###
345
346Some 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:
347
348```
349$opt_params = array(
350  'alt' => "json"
351);
352```
353
354### How do I set a field to null? ###
355
356The 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.
357
358## Code Quality ##
359
360Run 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.
361
362    phpunit tests/
363
364### Coding Style
365
366To check for coding style violations, run
367
368```
369vendor/bin/phpcs src --standard=style/ruleset.xml -np
370```
371
372To automatically fix (fixable) coding style violations, run
373
374```
375vendor/bin/phpcbf src --standard=style/ruleset.xml
376```
377