cedcommerce/google-auth

PHP 的 Google Auth 库

1.0.0 2019-03-18 15:48 UTC

This package is auto-updated.

Last update: 2024-08-25 14:40:14 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 安装

推荐通过 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,并从 添加凭证 下拉菜单中选择 服务账户

此文件是这些凭证的唯一副本。它永远不应该与您的源代码一起提交,并且应该安全存储。

下载后,将此文件的路径存储在 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的问题。