Subversion Repositories cheapmusic

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
103 - 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
 
5
## Description ##
6
The Google API Client Library enables you to work with Google APIs such as Google+, Drive, or YouTube on your server.
7
 
8
## Beta ##
9
This library is in Beta. We're comfortable enough with the stability and features of the library that we want you to build real production applications on it. We will make an effort to support the public and protected surface of the library and maintain backwards compatibility in the future. While we are still in Beta, we reserve the right to make incompatible changes.
10
 
11
## Requirements ##
12
* [PHP 5.4.0 or higher](http://www.php.net/)
13
 
14
## Google Cloud Platform APIs
15
If you're looking to call the **Google Cloud Platform** APIs, you will want to use the [Google Cloud PHP](https://github.com/googlecloudplatform/google-cloud-php) library instead of this one.
16
 
17
## Developer Documentation ##
18
http://developers.google.com/api-client-library/php
19
 
20
## Installation ##
21
 
22
You can use **Composer** or simply **Download the Release**
23
 
24
### Composer
25
 
26
The preferred method is via [composer](https://getcomposer.org). Follow the
27
[installation instructions](https://getcomposer.org/doc/00-intro.md) if you do not already have
28
composer installed.
29
 
30
Once composer is installed, execute the following command in your project root to install this library:
31
 
32
```sh
33
composer require google/apiclient:^2.0
34
```
35
 
36
Finally, be sure to include the autoloader:
37
 
38
```php
39
require_once '/path/to/your-project/vendor/autoload.php';
40
```
41
 
42
### Download the Release
43
 
44
If 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
45
with the name `google-api-php-client-[RELEASE_NAME].zip` for a package including this library and its dependencies.
46
 
47
Uncompress the zip file you download, and include the autoloader in your project:
48
 
49
```php
50
require_once '/path/to/google-api-php-client/vendor/autoload.php';
51
```
52
 
53
For additional installation and setup instructions, see [the documentation](https://developers.google.com/api-client-library/php/start/installation).
54
 
55
## Examples ##
56
See the [`examples/`](examples) directory for examples of the key client features. You can
57
view them in your browser by running the php built-in web server.
58
 
59
```
60
$ php -S localhost:8000 -t examples/
61
```
62
 
63
And then browsing to the host and port you specified
64
(in the above example, `http://localhost:8000`).
65
 
66
### Basic Example ###
67
 
68
```php
69
// include your composer dependencies
70
require_once 'vendor/autoload.php';
71
 
72
$client = new Google_Client();
73
$client->setApplicationName("Client_Library_Examples");
74
$client->setDeveloperKey("YOUR_APP_KEY");
75
 
76
$service = new Google_Service_Books($client);
77
$optParams = array('filter' => 'free-ebooks');
78
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);
79
 
80
foreach ($results as $item) {
81
  echo $item['volumeInfo']['title'], "<br /> \n";
82
}
83
```
84
 
85
### Authentication with OAuth ###
86
 
87
> An example of this can be seen in [`examples/simple-file-upload.php`](examples/simple-file-upload.php).
88
 
89
1. Follow the instructions to [Create Web Application Credentials](https://developers.google.com/api-client-library/php/auth/web-app#creatingcred)
90
1. Download the JSON credentials
91
1. Set the path to these credentials using `Google_Client::setAuthConfig`:
92
 
93
    ```php
94
    $client = new Google_Client();
95
    $client->setAuthConfig('/path/to/client_credentials.json');
96
    ```
97
 
98
1. Set the scopes required for the API you are going to call
99
 
100
    ```php
101
    $client->addScope(Google_Service_Drive::DRIVE);
102
    ```
103
 
104
1. Set your application's redirect URI
105
 
106
    ```php
107
    // Your redirect URI can be any registered URI, but in this example
108
    // we redirect back to this same page
109
    $redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
110
    $client->setRedirectUri($redirect_uri);
111
    ```
112
 
113
1. In the script handling the redirect URI, exchange the authorization code for an access token:
114
 
115
    ```php
116
    if (isset($_GET['code'])) {
117
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
118
        $client->setAccessToken($token);
119
    }
120
    ```
121
 
122
### Authentication with Service Accounts ###
123
 
124
> An example of this can be seen in [`examples/service-account.php`](examples/service-account.php).
125
 
126
1. Follow the instructions to [Create a Service Account](https://developers.google.com/api-client-library/php/auth/service-accounts#creatinganaccount)
127
1. Download the JSON credentials
128
1. Set the path to these credentials using the `GOOGLE_APPLICATION_CREDENTIALS` environment variable:
129
 
130
    ```php
131
    putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
132
    ```
133
 
134
1. Tell the Google client to use your service account credentials to authenticate:
135
 
136
    ```php
137
    $client = new Google_Client();
138
    $client->useApplicationDefaultCredentials();
139
    ```
140
 
141
1. Set the scopes required for the API you are going to call
142
 
143
    ```php
144
    $client->addScope(Google_Service_Drive::DRIVE);
145
    ```
146
 
147
1. 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:
148
 
149
    ```php
150
    $client->setSubject($user_to_impersonate);
151
    ```
152
 
153
### Making Requests ###
154
 
155
The 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/).
156
 
157
A JSON request to the [Datastore API](https://developers.google.com/apis-explorer/#p/datastore/v1beta3/datastore.projects.runQuery) would look like this:
158
 
159
```json
160
POST https://datastore.googleapis.com/v1beta3/projects/YOUR_PROJECT_ID:runQuery?key=YOUR_API_KEY
161
 
162
{
163
    "query": {
164
        "kind": [{
165
            "name": "Book"
166
        }],
167
        "order": [{
168
            "property": {
169
                "name": "title"
170
            },
171
            "direction": "descending"
172
        }],
173
        "limit": 10
174
    }
175
}
176
```
177
 
178
Using this library, the same call would look something like this:
179
 
180
```php
181
// create the datastore service class
182
$datastore = new Google_Service_Datastore($client);
183
 
184
// build the query - this maps directly to the JSON
185
$query = new Google_Service_Datastore_Query([
186
    'kind' => [
187
        [
188
            'name' => 'Book',
189
        ],
190
    ],
191
    'order' => [
192
        'property' => [
193
            'name' => 'title',
194
        ],
195
        'direction' => 'descending',
196
    ],
197
    'limit' => 10,
198
]);
199
 
200
// build the request and response
201
$request = new Google_Service_Datastore_RunQueryRequest(['query' => $query]);
202
$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
203
```
204
 
205
However, as each property of the JSON API has a corresponding generated class, the above code could also be written like this:
206
 
207
```php
208
// create the datastore service class
209
$datastore = new Google_Service_Datastore($client);
210
 
211
// build the query
212
$request = new Google_Service_Datastore_RunQueryRequest();
213
$query = new Google_Service_Datastore_Query();
214
//   - set the order
215
$order = new Google_Service_Datastore_PropertyOrder();
216
$order->setDirection('descending');
217
$property = new Google_Service_Datastore_PropertyReference();
218
$property->setName('title');
219
$order->setProperty($property);
220
$query->setOrder([$order]);
221
//   - set the kinds
222
$kind = new Google_Service_Datastore_KindExpression();
223
$kind->setName('Book');
224
$query->setKinds([$kind]);
225
//   - set the limit
226
$query->setLimit(10);
227
 
228
// add the query to the request and make the request
229
$request->setQuery($query);
230
$response = $datastore->projects->runQuery('YOUR_DATASET_ID', $request);
231
```
232
 
233
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](https://developers.google.com/apis-explorer/#p/) before using any of the services here.
234
 
235
### Making HTTP Requests Directly ###
236
 
237
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.
238
 
239
The `authorize` method returns an authorized [Guzzle Client](http://docs.guzzlephp.org/), so any request made using the client will contain the corresponding authorization.
240
 
241
```php
242
// create the Google client
243
$client = new Google_Client();
244
 
245
/**
246
 * Set your method for authentication. Depending on the API, This could be
247
 * directly with an access token, API key, or (recommended) using
248
 * Application Default Credentials.
249
 */
250
$client->useApplicationDefaultCredentials();
251
$client->addScope(Google_Service_Plus::PLUS_ME);
252
 
253
// returns a Guzzle HTTP Client
254
$httpClient = $client->authorize();
255
 
256
// make an HTTP request
257
$response = $httpClient->get('https://www.googleapis.com/plus/v1/people/me');
258
```
259
 
260
### Caching ###
261
 
262
It 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:
263
 
264
```php
265
$cache = new Stash\Pool(new Stash\Driver\FileSystem);
266
$client->setCache($cache);
267
```
268
 
269
In this example we use [StashPHP](http://www.stashphp.com/). Add this to your project with composer:
270
 
271
```
272
composer require tedivm/stash
273
```
274
 
275
### Updating Tokens ###
276
 
277
When 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:
278
 
279
```php
280
$logger = new Monolog\Logger;
281
$tokenCallback = function ($cacheKey, $accessToken) use ($logger) {
282
  $logger->debug(sprintf('new access token received at cache key %s', $cacheKey));
283
};
284
$client->setTokenCallback($tokenCallback);
285
```
286
 
287
### Debugging Your HTTP Request using Charles ###
288
 
289
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](https://www.charlesproxy.com/documentation/getting-started/). Download and run Charles, and then capture all HTTP traffic through Charles with the following code:
290
 
291
```php
292
// FOR DEBUGGING ONLY
293
$httpClient = new GuzzleHttp\Client([
294
    'proxy' => 'localhost:8888', // by default, Charles runs on localhost port 8888
295
    'verify' => false, // otherwise HTTPS requests will fail.
296
]);
297
 
298
$client = new Google_Client();
299
$client->setHttpClient($httpClient);
300
```
301
 
302
Now all calls made by this library will appear in the Charles UI.
303
 
304
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`.
305
 
306
### Service Specific Examples ###
307
 
308
YouTube: https://github.com/youtube/api-samples/tree/master/php
309
 
310
## How Do I Contribute? ##
311
 
312
Please 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).
313
 
314
## Frequently Asked Questions ##
315
 
316
### What do I do if something isn't working? ###
317
 
318
For 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
319
 
320
If 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.
321
 
322
### I want an example of X! ###
323
 
324
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!
325
 
326
### Why do you still support 5.2? ###
327
 
328
When 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.
329
 
330
### Why does Google_..._Service have weird names? ###
331
 
332
The _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.
333
 
334
### How do I deal with non-JSON response types? ###
335
 
336
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:
337
 
338
```
339
$opt_params = array(
340
  'alt' => "json"
341
);
342
```
343
 
344
### How do I set a field to null? ###
345
 
346
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.
347
 
348
## Code Quality ##
349
 
350
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.
351
 
352
    phpunit tests/
353
 
354
### Coding Style
355
 
356
To check for coding style violations, run
357
 
358
```
359
vendor/bin/phpcs src --standard=style/ruleset.xml -np
360
```
361
 
362
To automatically fix (fixable) coding style violations, run
363
 
364
```
365
vendor/bin/phpcbf src --standard=style/ruleset.xml
366
```