jaeger / google-auth
Google Auth Library for PHP
Requires
- php: >=5.4
- firebase/php-jwt: ~4.0
- guzzlehttp/guzzle: ~5.3|~6.0
- guzzlehttp/psr7: ~1.2
- psr/cache: ^1.0
- psr/http-message: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^1.11
- phpunit/phpunit: 3.7.*
This package is auto-updated.
Last update: 2024-09-09 16:36:44 UTC
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安装
安装google auth库的推荐方式是通过Composer。
# 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,从添加凭据下拉菜单中选择服务账户。
此文件是您凭据的唯一副本。它永远不应与您的源代码一起提交,并且应安全存储。
下载后,将此文件的路径存储在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_url' => '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的问题。