jayzcos / google-api-updated

Google API 客户端库

v2.2.2 2018-06-20 15:52 UTC

README

Build Status

PHP Google API 客户端库

Google API 客户端库允许您在服务器上与 Google API(如 Google+、Drive 或 YouTube)交互。

这些客户端库由 Google 官方支持。然而,库被认为是完整的,处于维护模式。这意味着我们将解决关键错误和安全问题,但不会添加任何新功能。

Google Cloud Platform

对于 Google Cloud Platform API(如 Datastore、Cloud Storage 或 Pub/Sub),我们建议使用处于积极开发中的 GoogleCloudPlatform/google-cloud-php

要求

开发者文档

http://developers.google.com/api-client-library/php

安装

您可以使用 Composer 或直接 下载发布版本

Composer

首选方法是使用 composer。如果您尚未安装 composer,请按照 安装说明 操作。

安装 composer 后,在项目根目录下执行以下命令以安装此库

composer require google/apiclient:^2.0

最后,请确保包含自动加载器

require_once '/path/to/your-project/vendor/autoload.php';

下载发布版本

如果您不喜欢使用 composer,可以下载整个包。在 发布页面 上列出了所有稳定版本。下载任何名称为 google-api-php-client-[RELEASE_NAME].zip 的文件,其中包含此库及其依赖项。

解压您下载的 zip 文件,并在您的项目中包含自动加载器

require_once '/path/to/google-api-php-client/vendor/autoload.php';

有关安装和配置的更多说明,请参阅 文档

示例

请参阅 examples/ 目录中的示例,以了解关键客户端功能。您可以通过运行内置的 php 网络服务器在浏览器中查看它们。

$ php -S localhost:8000 -t examples/

然后浏览到您指定的主机和端口(在上面的示例中,https://:8000)。

基本示例

// 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);
$optParams = array('filter' => 'free-ebooks');
$results = $service->volumes->listVolumes('Henry David Thoreau', $optParams);

foreach ($results as $item) {
  echo $item['volumeInfo']['title'], "<br /> \n";
}

使用 OAuth 进行身份验证

此示例可参见 examples/simple-file-upload.php

  1. 按照 创建 Web 应用凭证 的说明进行操作

  2. 下载 JSON 凭证

  3. 使用 Google_Client::setAuthConfig 设置这些凭证的路径

    $client = new Google_Client();
    $client->setAuthConfig('/path/to/client_credentials.json');
  4. 设置您要调用的 API 所需的权限范围

    $client->addScope(Google_Service_Drive::DRIVE);
  5. 设置您应用程序的重定向 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. 在处理重定向 URI 的脚本中,将授权代码交换为访问令牌

    if (isset($_GET['code'])) {
        $token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
    }

使用服务帐户进行身份验证

此示例可参见 examples/service-account.php

某些 API(如 YouTube 数据 API)不支持服务帐户。如果 API 调用返回意外的 401 或 403 错误,请检查特定 API 文档。

  1. 按照 创建服务帐户 的说明进行操作

  2. 下载 JSON 凭证

  3. 使用环境变量 GOOGLE_APPLICATION_CREDENTIALS 设置这些凭证的路径

    putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json');
  4. 告诉Google客户端使用您的服务帐户凭据进行身份验证

    $client = new Google_Client();
    $client->useApplicationDefaultCredentials();
  5. 设置您要调用的 API 所需的权限范围

    $client->addScope(Google_Service_Drive::DRIVE);
  6. 如果您已将域范围访问委托给服务帐户,并希望模拟用户帐户,请使用setSubject方法指定用户帐户的电子邮件地址

    $client->setSubject($user_to_impersonate);

发起请求

google-api-php-client-services中使用的类用于调用API是自动生成的。它们直接映射到APIs Explorer中找到的JSON请求和响应。

Datastore API的JSON请求可能如下所示

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

使用此库,相同的调用可能如下所示

// 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);

但是,由于JSON API的每个属性都有一个对应的生成类,上述代码也可以写成这样

// 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);

使用哪种方法取决于个人喜好,但在不了解API的JSON语法的情况下很难使用此库,因此建议在使用任何服务之前查看APIs Explorer

直接发起HTTP请求

如果外部应用程序需要Google身份验证,或者Google API尚未包含在此库中,可以直接发起HTTP请求。

authorize方法返回一个授权的Guzzle客户端,因此使用此客户端发出的任何请求都将包含相应的授权。

// 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');

缓存

建议使用另一个缓存库来提高性能。这可以通过向客户端传递一个PSR-6兼容的库来实现

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);

在此示例中,我们使用PHP Cache。使用composer将此添加到您的项目中

composer require cache/filesystem-adapter

更新令牌

当使用刷新令牌服务帐户凭据时,当授予新的访问令牌时执行某些操作可能很有用。为此,将可调用对象传递到客户端上的setTokenCallback方法

$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);

使用Charles调试您的HTTP请求

通过查看原始HTTP请求来调试API调用通常非常有用。此库支持使用Charles Web Proxy。下载并运行Charles,然后使用以下代码捕获通过Charles的所有HTTP流量

// 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);

现在,此库发出的所有调用都将出现在Charles UI中。

在Charles中查看SSL请求还需要进行一个额外的步骤。转到Charles > Proxy > SSL Proxying Settings并添加您希望捕获的域名。对于Google API,这通常是*.googleapis.com

服务特定示例

YouTube: https://github.com/youtube/api-samples/tree/master/php

我该如何贡献?

有关更多信息,请参阅贡献页面。特别是,我们喜欢拉取请求 - 但请确保签署贡献者许可协议

常见问题解答

如果出现问题,我该怎么做?

对于库的支持,最佳提问方式是通过 StackOverflow 上的 google-api-php-client 标签:[http://stackoverflow.com/questions/tagged/google-api-php-client](http://stackoverflow.com/questions/tagged/google-api-php-client)

如果库存在特定错误,请在 Github 问题跟踪器中提交一个问题,包括失败的代码示例和任何特定的错误信息。功能请求也可以提交,只要它们是核心库请求,而不是特定于 API 的请求:对于这些,请参考各个 API 的文档,以确定最佳提交请求的地方。请尽量提供清晰的问题说明,该功能将如何解决这些问题。

我想看看 X 的示例!

如果 X 是库的功能,就不用担心!如果 X 是使用特定服务的示例,最佳去处是那些特定 API 的团队——我们更倾向于链接到它们的示例,而不是将它们添加到库中,因为这样它们可以针对库的特定版本进行固定。如果您有其他 API 的示例,请告诉我们,我们将很高兴在 README 中添加链接!

为什么你们还支持 5.2?

当我们开始开发 1.0.0 分支时,我们知道库的 0.6 版本中存在一些基本问题需要修复。当时,我们分析了库的使用情况和其他相关项目,发现仍然有大量的 PHP 5.2 安装基础。您可以在 WordPress 统计中的 PHP 版本图表中看到这一点:[https://wordpresstheme.cn/about/stats/](https://wordpresstheme.cn/about/stats/)。我们将继续关注我们看到的用法类型,并尽可能利用新的 PHP 功能。

为什么 Google_..._Service 有奇怪的名字?

Service 类通常是从 API 发现文档自动生成的:[https://developers.google.com/discovery/](https://developers.google.com/discovery/)。有时 API 会添加一些名称不寻常的新功能,这可能导致 PHP 类中出现一些意外的或非标准的命名风格。

如何处理非 JSON 响应类型?

一些服务默认返回 XML 或类似的响应,而不是库支持的 JSON。您可以通过向方法调用的可选参数中添加一个 'alt' 参数来请求 JSON 响应,这个参数通常是方法调用的最后一个参数。

$opt_params = array(
  'alt' => "json"
);

如何将字段设置为 null?

库从发送到 Google API 的对象中移除 null,因为所有未初始化属性默认值为 null。为了解决这个问题,将您想设置为 null 的字段设置为 Google_Model::NULL_VALUE。这是一个占位符,在通过网络发送时会替换为真正的 null。

代码质量

使用 PHPUnit 运行 PHPUnit 测试。您可以在 BaseTest.php 中配置 API 密钥和令牌来运行所有调用,但这需要在 Google 开发者控制台中做一些设置。

phpunit tests/

编码风格

要检查编码风格违规,运行

vendor/bin/phpcs src --standard=style/ruleset.xml -np

要自动修复(可修复的)编码风格违规,运行

vendor/bin/phpcbf src --standard=style/ruleset.xml