cedcommerce/google-apiclient

Google API 客户端库

2.0.1 2019-06-14 12:05 UTC

This package is auto-updated.

Last update: 2024-09-14 23:50:05 UTC


README

Build Status

Google API PHP 客户端库

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

然后浏览到您指定的主机和端口(在上面的示例中,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);
$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 > 代理 > SSL 代理设置 并添加您想要捕获的域。对于 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

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

我想看一个X的例子!

如果X是库的功能,请放好!如果X是使用特定服务的示例,最好的地方是那些特定API的团队 - 我们更喜欢链接到他们的示例,而不是将它们添加到库中,因为这样他们可以锁定库的特定版本。如果您有其他API的示例,请告诉我们,我们将很乐意在README上方添加链接!

为什么你还支持5.2?

当我们在1.0.0分支上开始工作时,我们知道需要修复库的0.6版本中的几个基本问题。当时,我们查看库的使用情况以及其他相关项目,并确定PHP 5.2的安装基础仍然庞大且活跃。您可以在WordPress统计中的PHP版本图表中看到这一点:http://wordpress.org/about/stats/。我们将继续查看我们看到的用途类型,并尽可能利用新的PHP功能。

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

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

如何处理非JSON响应类型?

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

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

如何将字段设置为null?

库会从发送到Google API的对象中移除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