bitgandtter/google-api

此包已废弃,不再维护。作者建议使用google/apiclient包。

Google API 客户端库


README

PHP Google API 客户端库

参考文档
https://googleapis.github.io/google-api-php-client/main/
许可证
Apache 2.0

Google API 客户端库使您能够在服务器上使用 Google API,如 Gmail、Drive 或 YouTube。

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

Google Cloud Platform

对于 Google Cloud Platform API,如 DatastoreCloud StoragePub/SubCompute Engine,我们建议使用 Google Cloud 客户端库。有关支持的 Google Cloud 客户端库的完整列表,请参阅 googleapis/google-cloud-php

要求

开发者文档

docs 文件夹提供了使用此库的详细指南。

安装

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

Composer

首选方法是使用 composer。如果您还没有安装 composer,请按照 安装说明 进行操作。

一旦安装了 composer,请在项目根目录中执行以下命令来安装此库

composer require google/apiclient:^2.12.1

最后,请务必包含自动加载器

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

此库依赖于 google/apiclient-services。该库为大量 Google API 提供了最新的 API 包装器。为了使用户能够使用最新的 API 客户端,此库不针对 google/apiclient-services 的特定版本进行锁定。为了防止意外安装具有破坏性更改的 API 包装器,强烈建议您在使用此库进行生产之前自己锁定到最新的版本。

清理未使用的服务

谷歌API服务超过200个。你很可能不会想要全部使用。为了避免将它们作为依赖项与你的代码一起打包,你可以运行Google\Task\Composer::cleanup任务,并在composer.json中指定你想要保留的服务。

{
    "require": {
        "google/apiclient": "^2.12.1"
    },
    "scripts": {
        "pre-autoload-dump": "Google\\Task\\Composer::cleanup"
    },
    "extra": {
        "google/apiclient-services": [
            "Drive",
            "YouTube"
        ]
    }
}

以下示例将在运行composer update或新的composer install时删除除“Drive”和“YouTube”之外的所有服务。

重要:如果你在composer.json中添加任何服务,你需要明确删除vendor/google/apiclient-services目录,以便你所做的更改生效。

rm -r vendor/google/apiclient-services
composer update

注意:此命令对服务名称执行精确匹配,因此要保留YouTubeReportingYouTubeAnalytics,你需要明确添加它们。

{
    "extra": {
        "google/apiclient-services": [
            "Drive",
            "YouTube",
            "YouTubeAnalytics",
            "YouTubeReporting"
        ]
    }
}

下载发布版本

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

解压缩你下载的zip文件,并将自动加载器包含到你的项目中。

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

有关安装和设置的其他说明,请参阅文档

示例

查看examples/目录中的关键客户端功能示例。你可以通过运行内置的php web服务器在浏览器中查看它们。

$ php -S localhost:8000 -t examples/

然后浏览到你指定的主机和端口(在上面的示例中,http://localhost: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);
$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";
}

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

如何使用特定的JSON键

如果您想使用特定的JSON键而不是使用GOOGLE_APPLICATION_CREDENTIALS环境变量,您可以这样做:

$jsonKey = [
   'type' => 'service_account',
   // ...
];
$client = new Google\Client();
$client->setAuthConfig($jsonKey);

发送请求

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请求。

如果您仅安装此客户端来验证您自己的HTTP客户端请求,应使用google/auth

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代理。下载并运行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 > 代理 > SSL 代理设置 并添加您希望捕获的域名。对于 Google API,通常为 *.googleapis.com

直接控制 HTTP 客户端配置

Google API 客户端使用 Guzzle 作为其默认 HTTP 客户端。这意味着您可以以与使用 Guzzle 的任何应用程序相同的方式控制您的 HTTP 请求。

比如说,我们想要为每个请求应用一个引用者。

use GuzzleHttp\Client;

$httpClient = new Client([
    'headers' => [
        'referer' => 'mysite.com'
    ]
]);

$client = new Google\Client();
$client->setHttpClient($httpClient);

其他 Guzzle 功能,如 处理程序和中间件 提供了更多的控制。

特定服务示例

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

如何贡献?

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

常见问题

如果某件事不起作用,我该怎么办?

有关库的支持,最佳提问方式是通过 StackOverflow 上的 google-api-php-client 标签: https://stackoverflow.com/questions/tagged/google-api-php-client

如果库中存在特定错误,请在 GitHub 问题跟踪器中 提交问题,包括失败的代码示例以及任何特定的错误。也可以提交功能请求,只要它们是核心库请求,而不是特定于 API:对于这些,请参阅单个 API 的文档,以了解最佳提交请求位置。请尽量提供关于该功能将解决何种问题的明确声明。

我想看 X 的示例!

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

为什么一些 Google\Service 类有奇怪的名字?

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

我该如何处理非 JSON 响应类型?

一些服务默认返回XML或类似格式,而不是JSON,而库支持的是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