Skip to content

Commit f449f53

Browse files
grantdwsupplee
authored andcommitted
docs: Adds developer docs to repo: Fixes #1648 Fixes #1649 Fixes #165… (#1668)
* docs: Adds developer docs to repo: Fixes #1648 Fixes #1649 Fixes #1650 Fixes #1651 Fixes #1652 Fixes #1653 * docs: Add guide for OAuth web * docs: Fix oauth-server doc * docs: Fix docs links * docs: Address @eesheesh's comments * docs: Fix bad link
1 parent 2d11de3 commit f449f53

12 files changed

+860
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ For Google Cloud Platform APIs such as Datastore, Cloud Storage or Pub/Sub, we r
1414
* [PHP 5.4.0 or higher](http://www.php.net/)
1515

1616
## Developer Documentation ##
17-
http://developers.google.com/api-client-library/php
17+
18+
The [docs folder](docs/) provides detailed guides for using this library.
1819

1920
## Installation ##
2021

docs/README.md

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Google API Client LIbrary for PHP Docs
2+
3+
The Google API Client Library for PHP offers simple, flexible access to many Google APIs.
4+
5+
## Documentation
6+
7+
- [Getting Started](start.md)
8+
- [API Keys](api-keys.md)
9+
- [Auth](auth.md)
10+
- [Installation](install.md)
11+
- [Media](media.md)
12+
- [OAuth Server](oauth-server.md)
13+
- [OAuth Web](oauth-web.md)
14+
- [Pagination](pagination.md)
15+
- [Parameters](parameters.md)

docs/api-keys.md

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# API Keys
2+
3+
When calling APIs that do not access private user data, you can use simple API keys. These keys are used to authenticate your application for accounting purposes. The Google Developers Console documentation also describes [API keys](https://developers.google.com/console/help/using-keys).
4+
5+
> Note: If you do need to access private user data, you must use OAuth 2.0. See [Using OAuth 2.0 for Web Server Applications](docs/oauth-server.md) and [Using OAuth 2.0 for Server to Server Applications](docs/oauth-web.md) for more information.
6+
7+
## Using API Keys
8+
9+
To use API keys, call the `setDeveloperKey()` method of the `Google_Client` object before making any API calls. For example:
10+
11+
```php
12+
$client->setDeveloperKey($api_key);
13+
```

docs/auth.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Authorization
2+
3+
The Google PHP Client Library supports several methods for making authenticated calls to the Google APIs.
4+
5+
- [API Keys](api-keys.md)
6+
- [OAuth 2.0 For Webservers](oauth-web.md)
7+
- [OAuth 2.0 Service Accounts](oauth-server.md)
8+
9+
In addition, it supports a method of identifying users without granting access to make Google API calls.
10+
11+
- [ID Token Verification](id-token.md)

docs/id-token.md

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# ID Token Authentication
2+
3+
ID tokens allow authenticating a user securely without requiring a network call (in many cases), and without granting the server access to request user information from the Google APIs.
4+
5+
> For a complete example, see the [idtoken.php](https://github.com/googleapis/google-api-php-client/blob/master/examples/idtoken.php) sample in the examples/ directory of the client library.
6+
7+
This is accomplished because each ID token is a cryptographically signed, base64 encoded JSON structure. The token payload includes the Google user ID, the client ID of the application the user signed in to, and the issuer (in this case, Google). It also contains a cryptographic signature which can be verified with the public Google certificates to ensure that the token was created by Google. If the user has granted permission to view their email address to the application, the ID token will additionally include their email address.
8+
9+
The token can be easily and securely verified with the PHP client library
10+
11+
```php
12+
function getUserFromToken($token) {
13+
$ticket = $client->verifyIdToken($token);
14+
if ($ticket) {
15+
$data = $ticket->getAttributes();
16+
return $data['payload']['sub']; // user ID
17+
}
18+
return false
19+
}
20+
```
21+
22+
The library will automatically download and cache the certificate required for verification, and refresh it if it has expired.

docs/install.md

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Installation
2+
3+
This page contains information about installing the Google APIs Client Library for PHP.
4+
5+
## Requirements
6+
7+
* PHP version 5.4 or greater.
8+
9+
## Obtaining the client library
10+
11+
There are two options for obtaining the files for the client library.
12+
13+
### Using Composer
14+
15+
You can install the library by adding it as a dependency to your composer.json.
16+
17+
```json
18+
"require": {
19+
"google/apiclient": "^2.0"
20+
}
21+
```
22+
23+
### Downloading from GitHub
24+
25+
Follow [the instructions in the README](https://github.com/google/google-api-php-client#download-the-release) to download the package locally.
26+
27+
### What to do with the files
28+
29+
After obtaining the files, include the autloader. If you used Composer, your require statement will look like this:
30+
31+
```php
32+
require_once '/path/to/your-project/vendor/autoload.php';
33+
```
34+
35+
If you downloaded the package separately, your require statement will look like this:
36+
37+
```php
38+
require_once '/path/to/google-api-php-client/vendor/autoload.php';
39+
```

docs/media.md

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Media Upload
2+
3+
The PHP client library allows for uploading large files for use with APIs such as Drive or YouTube. There are three different methods available.
4+
5+
## Simple Upload
6+
7+
In the simple upload case, the data is passed as the body of the request made to the server. This limits the ability to specify metadata, but is very easy to use.
8+
9+
```php
10+
$file = new Google_Service_Drive_DriveFile();
11+
$result = $service->files->insert($file, array(
12+
'data' => file_get_contents("path/to/file"),
13+
'mimeType' => 'application/octet-stream',
14+
'uploadType' => 'media'
15+
));
16+
```
17+
18+
## Multipart File Upload
19+
20+
With multipart file uploads, the uploaded file is sent as one part of a multipart form post. This allows metadata about the file object to be sent as part of the post as well. This is triggered by specifying the _multipart_ uploadType.
21+
22+
```php
23+
$file = new Google_Service_Drive_DriveFile();
24+
$file->setTitle("Hello World!");
25+
$result = $service->files->insert($file, array(
26+
'data' => file_get_contents("path/to/file"),
27+
'mimeType' => 'application/octet-stream',
28+
'uploadType' => 'multipart'
29+
));
30+
```
31+
32+
## Resumable File Upload
33+
34+
It is also possible to split the upload across multiple requests. This is convenient for larger files, and allows resumption of the upload if there is a problem. Resumable uploads can be sent with separate metadata.
35+
36+
```php
37+
$file = new Google_Service_Drive_DriveFile();
38+
$file->title = "Big File";
39+
$chunkSizeBytes = 1 * 1024 * 1024;
40+
41+
// Call the API with the media upload, defer so it doesn't immediately return.
42+
$client->setDefer(true);
43+
$request = $service->files->insert($file);
44+
45+
// Create a media file upload to represent our upload process.
46+
$media = new Google_Http_MediaFileUpload(
47+
$client,
48+
$request,
49+
'text/plain',
50+
null,
51+
true,
52+
$chunkSizeBytes
53+
);
54+
$media->setFileSize(filesize("path/to/file"));
55+
56+
// Upload the various chunks. $status will be false until the process is
57+
// complete.
58+
$status = false;
59+
$handle = fopen("path/to/file", "rb");
60+
while (!$status && !feof($handle)) {
61+
$chunk = fread($handle, $chunkSizeBytes);
62+
$status = $media->nextChunk($chunk);
63+
}
64+
65+
// The final value of $status will be the data from the API for the object
66+
// that has been uploaded.
67+
$result = false;
68+
if($status != false) {
69+
$result = $status;
70+
}
71+
72+
fclose($handle);
73+
// Reset to the client to execute requests immediately in the future.
74+
$client->setDefer(false);
75+
```

docs/oauth-server.md

+144
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
# Using OAuth 2.0 for Server to Server Applications
2+
3+
The Google APIs Client Library for PHP supports using OAuth 2.0 for server-to-server interactions such as those between a web application and a Google service. For this scenario you need a service account, which is an account that belongs to your application instead of to an individual end user. Your application calls Google APIs on behalf of the service account, so users aren't directly involved. This scenario is sometimes called "two-legged OAuth," or "2LO." (The related term "three-legged OAuth" refers to scenarios in which your application calls Google APIs on behalf of end users, and in which user consent is sometimes required.)
4+
5+
Typically, an application uses a service account when the application uses Google APIs to work with its own data rather than a user's data. For example, an application that uses [Google Cloud Datastore](https://cloud.google.com/datastore/) for data persistence would use a service account to authenticate its calls to the Google Cloud Datastore API.
6+
7+
If you have a G Suite domain—if you use [G Suite Business](https://gsuite.google.com), for example—an administrator of the G Suite domain can authorize an application to access user data on behalf of users in the G Suite domain. For example, an application that uses the [Google Calendar API](https://developers.google.com/google-apps/calendar/) to add events to the calendars of all users in a G Suite domain would use a service account to access the Google Calendar API on behalf of users. Authorizing a service account to access data on behalf of users in a domain is sometimes referred to as "delegating domain-wide authority" to a service account.
8+
9+
> **Note:** When you use [G Suite Marketplace](https://www.google.com/enterprise/marketplace/) to install an application for your domain, the required permissions are automatically granted to the application. You do not need to manually authorize the service accounts that the application uses.
10+
11+
> **Note:** Although you can use service accounts in applications that run from a G Suite domain, service accounts are not members of your G Suite account and aren't subject to domain policies set by G Suite administrators. For example, a policy set in the G Suite admin console to restrict the ability of Apps end users to share documents outside of the domain would not apply to service accounts.
12+
13+
This document describes how an application can complete the server-to-server OAuth 2.0 flow by using the Google APIs Client Library for PHP.
14+
15+
## Overview
16+
17+
To support server-to-server interactions, first create a service account for your project in the Developers Console. If you want to access user data for users in your G Suite domain, then delegate domain-wide access to the service account.
18+
19+
Then, your application prepares to make authorized API calls by using the service account's credentials to request an access token from the OAuth 2.0 auth server.
20+
21+
Finally, your application can use the access token to call Google APIs.
22+
23+
## Creating a service account
24+
25+
A service account's credentials include a generated email address that is unique, a client ID, and at least one public/private key pair.
26+
27+
If your application runs on Google App Engine, a service account is set up automatically when you create your project.
28+
29+
If your application doesn't run on Google App Engine or Google Compute Engine, you must obtain these credentials in the Google Developers Console. To generate service-account credentials, or to view the public credentials that you've already generated, do the following:
30+
31+
If your application runs on Google App Engine, a service account is set up automatically when you create your project.
32+
33+
If your application doesn't run on Google App Engine or Google Compute Engine, you must obtain these credentials in the Google Developers Console. To generate service-account credentials, or to view the public credentials that you've already generated, do the following:
34+
35+
1. Open the [**Service accounts** section](https://console.developers.google.com/permissions/serviceaccounts?project=_) of the Developers Console's **Permissions** page.
36+
2. Click **Create service account**.
37+
3. In the **Create service account** window, type a name for the service account and select **Furnish a new private key**. If you want to [grant G Suite domain-wide authority](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority) to the service account, also select **Enable G Suite Domain-wide Delegation**. Then, click **Create**.
38+
39+
Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. You are responsible for storing it securely.
40+
41+
You can return to the [Developers Console](https://console.developers.google.com/) at any time to view the client ID, email address, and public key fingerprints, or to generate additional public/private key pairs. For more details about service account credentials in the Developers Console, see [Service accounts](https://developers.google.com/console/help/service-accounts) in the Developers Console help file.
42+
43+
Take note of the service account's email address and store the service account's private key file in a location accessible to your application. Your application needs them to make authorized API calls.
44+
45+
**Note:** You must store and manage private keys securely in both development and production environments. Google does not keep a copy of your private keys, only your public keys.
46+
47+
### Delegating domain-wide authority to the service account
48+
49+
If your application runs in a G Suite domain and accesses user data, the service account that you created needs to be granted access to the user data that you want to access.
50+
51+
The following steps must be performed by an administrator of the G Suite domain:
52+
53+
1. Go to your G Suite domain’s [Admin console](http://admin.google.com).
54+
2. Select **Security** from the list of controls. If you don't see **Security** listed, select **More controls** from the gray bar at the bottom of the page, then select **Security** from the list of controls. If you can't see the controls, make sure you're signed in as an administrator for the domain.
55+
3. Select **Advanced settings** from the list of options.
56+
4. Select **Manage third party OAuth Client access** in the **Authentication** section.
57+
5. In the **Client name** field enter the service account's **Client ID**.
58+
6. In the **One or More API Scopes** field enter the list of scopes that your application should be granted access to. For example, if your application needs domain-wide access to the Google Drive API and the Google Calendar API, enter: https://www.googleapis.com/auth/drive, https://www.googleapis.com/auth/calendar.
59+
7. Click **Authorize**.
60+
61+
Your application now has the authority to make API calls as users in your domain (to "impersonate" users). When you prepare to make authorized API calls, you specify the user to impersonate.
62+
63+
[](#top_of_page)Preparing to make an authorized API call
64+
--------------------------------------------------------
65+
66+
After you have obtained the client email address and private key from the Developers Console, set the path to these credentials in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable ( **Note:** This is not required in the App Engine environment):
67+
68+
```php
69+
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
70+
```
71+
72+
Call the `useApplicationDefaultCredentials` to use your service account credentials to authenticate:
73+
74+
```php
75+
$client = new Google_Client();
76+
$client->useApplicationDefaultCredentials();
77+
```
78+
79+
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`:
80+
81+
```php
82+
$client->setSubject($user_to_impersonate);
83+
```
84+
85+
Use the authorized `Google_Client` object to call Google APIs in your application.
86+
87+
## Calling Google APIs
88+
89+
Use the authorized `Google_Client` object to call Google APIs by completing the following steps:
90+
91+
1. Build a service object for the API that you want to call, providing the authorized `Google_Client` object. For example, to call the Cloud SQL Administration API:
92+
93+
```php
94+
$sqladmin = new Google_Service_SQLAdmin($client);
95+
```
96+
97+
2. Make requests to the API service using the [interface provided by the service object](https://developers.google.com/api-client-library/php/start/get_started#build). For example, to list the instances of Cloud SQL databases in the examinable-example-123 project:
98+
99+
```php
100+
$response = $sqladmin->instances->listInstances('examinable-example-123')->getItems();
101+
```
102+
103+
## Complete example
104+
105+
The following example prints a JSON-formatted list of Cloud SQL instances in a project.
106+
107+
To run this example:
108+
109+
1. Create a new directory and change to it. For example:
110+
111+
```sh
112+
mkdir ~/php-oauth2-example
113+
cd ~/php-oauth2-example
114+
```
115+
116+
2. Install the [Google API Client Library](https://github.com/google/google-api-php-client) for PHP using [Composer](https://getcomposer.org):
117+
118+
```sh
119+
composer require google/apiclient:^2.0
120+
```
121+
122+
3. Create the file sqlinstances.php with the content below.
123+
4. Run the example from the command line:
124+
125+
```
126+
php ~/php-oauth2-example/sqlinstances.php
127+
```
128+
129+
### sqlinstances.php
130+
131+
```php
132+
<?php
133+
134+
require_once __DIR__.'/vendor/autoload.php';
135+
136+
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
137+
$client = new Google_Client();
138+
$client->useApplicationDefaultCredentials();
139+
140+
$sqladmin = new Google_Service_SQLAdmin($client);
141+
$response = $sqladmin->instances
142+
->listInstances('examinable-example-123')->getItems();
143+
echo json_encode($response) . "\n";
144+
```

0 commit comments

Comments
 (0)