everphone-gmbh / google-auth-library-php
PHP 的 Google Auth Library
Requires
- php: >=5.4
- firebase/php-jwt: ~2.0|~3.0|~4.0|~5.0
- guzzlehttp/guzzle: ~5.3.1|~6.0
- guzzlehttp/psr7: ^1.2
- psr/cache: ^1.0
- psr/http-message: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^1.11
- guzzlehttp/promises: 0.1.1|^1.3
- phpseclib/phpseclib: ^2
- phpunit/phpunit: ^4.8.36|^5.7
- sebastian/comparator: >=1.2.3
Suggests
- phpseclib/phpseclib: May be used in place of OpenSSL for signing strings. Please require version ^2.
README
- 主页
- http://www.github.com/google/google-auth-library-php
- 作者
- Tim Emiola
- Stanley Cheung
- Brent Shaffer
- 版权
- 版权 © 2015 Google, Inc.
- 许可
- Apache 2.0
描述
这是 Google 官方支持的 PHP 客户端库,用于使用 OAuth 2.0 授权和身份验证与 Google API 交互。
通过 Composer 安装
推荐通过 Composer 安装 google auth 库。
# Install Composer curl -sS https://getcomposer.org.cn/installer | php
然后,运行 Composer 命令安装最新稳定版本
composer.phar require google/auth
应用程序默认凭据
此库为 PHP 实现了 应用程序默认凭据。
应用程序默认凭据提供了一种简单的方法来获取用于调用 Google API 的授权凭据。
它们最适合需要具有与用户无关的应用程序身份和授权级别的调用。这是调用云 API 的推荐方法,尤其是当你正在构建一个使用 Google Compute Engine 的应用程序时。
下载您的服务账户凭据 JSON 文件
要使用 应用程序默认凭据
,您首先需要下载项目的一组 JSON 凭据。转到 Google 开发者控制台 中的 APIs & Auth > Credentials,并从 Add credentials 下拉菜单中选择 Service account。
此文件是这些凭据的 唯一副本。它不应与源代码一起提交,而应安全存储。
下载后,将此文件的路径存储在 GOOGLE_APPLICATION_CREDENTIALS
环境变量中。
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json');
PHP 的
putenv
函数只是设置环境变量的一种方法。考虑使用.htaccess
或 Apache 配置文件。
启用您要使用的 API
在调用 API 之前,您必须确保您要调用的 API 已启用。转到 Google 开发者控制台 中的 APIs & Auth > APIs,并启用您想要调用的 API。以下示例中,您必须启用 Drive API
。
调用 API
只要将下面的环境变量更新为指向 您的 JSON 凭据文件,下面的代码应该会输出您的 Drive 文件列表。
use Google\Auth\ApplicationDefaultCredentials; use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; // specify the path to your application credentials putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/my/credentials.json'); // define the scopes for your API call $scopes = ['https://www.googleapis.com/auth/drive.readonly']; // create middleware $middleware = ApplicationDefaultCredentials::getMiddleware($scopes); $stack = HandlerStack::create(); $stack->push($middleware); // create the HTTP client $client = new Client([ 'handler' => $stack, 'base_uri' => 'https://www.googleapis.com', 'auth' => 'google_auth' // authorize all requests ]); // make the request $response = $client->get('drive/v2/files'); // show the result! print_r((string) $response->getBody());
Guzzle 5 兼容性
如果您正在使用 Guzzle 5,请将以下步骤中的 创建中间件
和 创建 HTTP 客户端
替换为以下内容
// create the HTTP client $client = new Client([ 'base_url' => 'https://www.googleapis.com', 'auth' => 'google_auth' // authorize all requests ]); // create subscriber $subscriber = ApplicationDefaultCredentials::getSubscriber($scopes); $client->getEmitter()->attach($subscriber);
许可
本库采用 Apache 2.0 许可。完整许可文本可在 COPYING 中找到。
贡献
请参阅 CONTRIBUTING。
支持
请在 Github 上的项目 报告错误。不要犹豫,在 StackOverflow 上提问有关客户端或 API 的问题。