risan / oauth1
PHP 的 OAuth 1.0 客户端库
Requires
- php: >=5.6.4
- guzzlehttp/guzzle: ~6.3
- guzzlehttp/psr7: ^1.4.2
- paragonie/random_compat: ~1.4|~2.0
- psr/http-message: ^1.0
Requires (Dev)
- phpunit/phpunit: ~5.7|~6.4
This package is auto-updated.
Last update: 2024-09-17 20:40:29 UTC
README
PHP 的简单、流畅和可扩展的 OAuth 1.0 客户端库。
目录
安装
推荐通过 Composer 安装此包。在终端运行以下命令以安装此包
composer require risan/oauth1
快速入门指南
此包非常灵活。您可以使用它与任何实现 OAuth 1.0 协议的提供商进行交互,例如 Twitter。
以下是一个如何使用此包与 Twitter API 交互的快速示例:获取授权用户的推文。
<?php // Includes the Composer autoload file. require 'vendor/autoload.php'; // Start the session. session_start(); // Create an instance of Risan\OAuth1\OAuth1 class. $oauth1 = Risan\OAuth1\OAuth1Factory::create([ 'client_credentials_identifier' => 'YOUR_TWITTER_API_KEY', 'client_credentials_secret' => 'YOUR_TWITTER_API_SECRET', 'temporary_credentials_uri' => 'https://api.twitter.com/oauth/request_token', 'authorization_uri' => 'https://api.twitter.com/oauth/authorize', 'token_credentials_uri' => 'https://api.twitter.com/oauth/access_token', 'callback_uri' => 'YOUR_CALLBACK_URI', ]); if (isset($_SESSION['token_credentials'])) { // Get back the previosuly obtain token credentials (step 3). $tokenCredentials = unserialize($_SESSION['token_credentials']); $oauth1->setTokenCredentials($tokenCredentials); // STEP 4: Retrieve the user's tweets. // It will return the Psr\Http\Message\ResponseInterface instance. $response = $oauth1->request('GET', 'https://api.twitter.com/1.1/statuses/user_timeline.json'); // Convert the response to array and display it. var_dump(json_decode($response->getBody()->getContents(), true)); } elseif (isset($_GET['oauth_token']) && isset($_GET['oauth_verifier'])) { // Get back the previosuly generated temporary credentials (step 1). $temporaryCredentials = unserialize($_SESSION['temporary_credentials']); unset($_SESSION['temporary_credentials']); // STEP 3: Obtain the token credentials (also known as access token). $tokenCredentials = $oauth1->requestTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']); // Store the token credentials in session for later use. $_SESSION['token_credentials'] = serialize($tokenCredentials); // this basically just redirecting to the current page so that the query string is removed. header('Location: ' . (string) $oauth1->getConfig()->getCallbackUri()); exit(); } else { // STEP 1: Obtain a temporary credentials (also known as the request token) $temporaryCredentials = $oauth1->requestTemporaryCredentials(); // Store the temporary credentials in session so we can use it on step 3. $_SESSION['temporary_credentials'] = serialize($temporaryCredentials); // STEP 2: Generate and redirect user to authorization URI. $authorizationUri = $oauth1->buildAuthorizationUri($temporaryCredentials); header("Location: {$authorizationUri}"); exit(); }
配置
您可以使用 Risan\OAuth1\OAuth1Factory
类的静态 create
方法轻松创建 Risan\OAuth1\Auth1
类的实例。它需要您传递一个包含以下键的配置数组
client_credentials_identifier
:客户端凭证标识符,也称为消费者密钥或 API 密钥。client_credentials_secret
:客户端凭证密钥,也称为消费者密钥或 API 密钥。temporary_credentials_uri
:获取临时凭证的 URI(也称为请求令牌)。authorization_uri
:授权用户的 URI。token_credentials_uri
:获取令牌凭证的 URI(也称为访问令牌)。
还可以传递两个可选配置
callback_uri
:用户成功授权后将被重定向到的 URI。base_uri
:用于构建绝对 URI 的基本 URI,如果您将相对 URI 传递到配置数组或向受保护资源发送请求时。
签名
每个 HTTP 请求都必须包含签名,以便提供商可以验证该请求的真实性。此签名过程由实现 Risan\OAuth1\Signature\SignerInterface
接口的签名器实例处理。此包包括两个签名器类,您可以使用
Risan\OAuth1\Signature\HmacSha1Signer
:使用 HMAC-SHA1 方法签名请求。Risan\OAuth1\Signature\PlainTextSigner
:使用纯文本方法签名请求。
您可以将此签名器实例作为 Risan\OAuth1\OAuth1Factory
类的 create
静态方法的第二个参数传递
$plainTextSigner = new Risan\OAuth1\Signature\PlainTextSigner(); $oauth1 = Risan\OAuth1\OAuth1Factory::create($config, $plainTextSigner);
如果您未向 create
方法传递任何签名器实例,则默认使用 HMAC-SHA1 签名器。
您还可以创建一个自定义签名器类,只要它实现了 Risan\OAuth1\Signature\SignerInterface
接口即可。
OAuth 1.0 流程
要访问受保护资源,OAuth 1.0 流程可以分为四个步骤
步骤 1:获取临时凭证
第一步是获取临时凭证,通常称为访问令牌。要获取它,您需要调用 Risan\OAuth1\OAuth1
实例上的 requestTemporaryCredentials
方法
$temporaryCredentials = $oauth1->requestTemporaryCredentials();
它将返回一个 Risan\OAuth1\Credentials\TemporaryCredentials
类的实例,您稍后可以使用它来生成授权 URI(步骤 2)和获取令牌凭证(步骤 3)。
步骤 2:生成并重定向用户到授权 URI
一旦获得临时凭据,下一步是生成并重定向用户到授权页面。在这里,用户将需要授权您的应用程序。您需要将之前获得的 Risan\OAuth1\Credentials\TemporaryCredentials
类实例传递给 buildAuthorizationUri
方法以生成授权 URI。
$authorizationUri = $oauth1->buildAuthorizationUri($temporaryCredentials); // Redirect user to the authorization URI. header("Location: {$authorizationUri}"); exit();
步骤 3:获取令牌凭证
第三步是获取令牌凭据,也称为访问令牌。在成功授权后,提供商将重定向用户到定义的回调 URI,并至少附带两个附加查询参数
oauth_token
oauth_verifier
除了之前获得的临时凭据外,您还需要将这两个查询参数传递给 requestTokenCredentials
方法以获取令牌凭据。
$tokenCredentials = $oauth1->requestTokenCredentials($temporaryCredentials, $_GET['oauth_token'], $_GET['oauth_verifier']);
此方法将返回 Risan\OAuth1\Credentials\TokenCredentials
类的实例,您需要该实例来访问受保护的资源。
步骤 4:访问受保护资源
最后,一旦您获得了令牌凭据实例,您就可以开始向受保护的资源发起请求。在向受保护的资源发起任何请求之前,将获得的 Risan\OAuth1\Credentials\TokenCredentials
实例传递给 setTokenCredentials
方法,否则将抛出异常。
// Set the previously obtained token credentials. $oauth1->setTokenCredentials($tokenCredentials); // Make a request to the protected resource. $response = $oauth1->request('GET', 'https://api.twitter.com/1.1/statuses/user_timeline.json');
request
方法将返回 Psr\Http\Message\ResponseInterface
类的实例。
制作 HTTP 请求
一旦使用 setTokenCredentials
方法设置了获得的令牌凭据,您就可以开始向受保护的 API 端点发起 HTTP 请求。您可以使用 request
方法来这样做。
$response = $oauth1->request($method, $uri, $options);
此方法接受三个参数
method
(必需):您希望使用的 HTTP 方法(例如,GET
、POST
、PUT
、PATCH
、DELETE
)uri
(必需):您希望访问的 API 端点的 URI。您还可以传递一个相对 URI,只要在配置数组中传递base_uri
。options
(可选):这是一个可选的数组参数,用于配置您的请求。它与您在通过 Guzzle 发起 HTTP 请求时传递的相同的 Request Options 相同。您可以在 Guzzle 文档 中检查所有可传递的选项。
还有一些针对常用 HTTP 方法的快捷方法
// GET method $oauth1->get($uri, $options); // POST method $oauth1->post($uri, $options); // PUT method $oauth1->put($uri, $options); // PATCH method $oauth1->patch($uri, $options); // DELETE method $oauth1->delete($uri, $options);
处理响应
request
方法将返回 Psr\Http\Message\ResponseInterface
类的实例。您可以使用 getStatusCode
方法检查返回的状态代码。
echo $response->getStatusCode();
或者,您也可以像这样获取返回响应的标题
// Get all of the headers $headers = $response->getHeaders(); // Or get a specific header $header = $response->getHeader('X-Foo');
要获取响应体,您可以使用 getBody
方法。注意,它将返回一个 Psr\Http\Message\StreamInterface
实例。要将 StreamInterface
实例转换为字符串,您可以调用 getContents
方法或直接将其转换为字符串。
$bodyStream = $response->getBody(); // Get the string representation of the stream $bodyStream = $bodyStream->getContents(); // Or simply cast it $bodyString = (string) $bodyStream;
因此,如果 API 端点返回 JSON 格式的响应,您可以将返回的响应转换为关联数组,如下所示
$result = json_decode($response->getBody()->getContents(), true);
内置提供商
此软件包还提供了一些第三方提供商,您可以使用。
Trello
使用 trello
方法创建一个配置了 Trello 的 OAuth1
实例。
$oauth1 = Risan\OAuth1\ProviderFactory::trello([ 'client_credentials_identifier' => 'YOUR_TRELLO_API_KEY', 'client_credentials_secret' => 'YOUR_TRELLO_SECRET', 'callback_uri' => 'YOUR_CALLBACK_URI', ]);
您可以从 开发者 API 密钥 页面获取您的 API 密钥和密钥。基础 URI 设置为 https://api.trello.com/1/
,因此您可以使用相对 URI。
$response = $oauth1->request('GET', 'members/johndoe/cards');
Tumblr
使用 tumblr
方法创建一个配置了 Tumblr 的 OAuth1
实例。
$oauth1 = Risan\OAuth1\ProviderFactory::tumblr([ 'client_credentials_identifier' => 'YOUR_TUMBLR_CONSUMER_KEY', 'client_credentials_secret' => 'YOUR_TUMBLR_CONSUMER_SECRET', 'callback_uri' => 'YOUR_CALLBACK_URI', ]);
您需要在 此处 注册 Tumblr 应用程序以获取消费者密钥和密钥。基础 URI 设置为 https://api.tumblr.com/v2/
,因此您可以使用相对 URI。
$response = $oauth1->request('GET', 'user/info');
使用 twitter
方法创建一个配置了 Twitter 的 OAuth1
实例。
$oauth1 = Risan\OAuth1\ProviderFactory::twitter([ 'client_credentials_identifier' => 'YOUR_TWITTER_CONSUMER_KEY', 'client_credentials_secret' => 'YOUR_TWITTER_CONSUMER_SECRET', 'callback_uri' => 'YOUR_CALLBACK_URI', ]);
您需要在此处注册Twitter应用程序以获取消费者密钥和密钥。基本URI设置为https://api.twitter.com/1.1/
,因此您可以使用相对URI。
$response = $oauth1->request('GET', 'statuses/user_timeline.json');
Upwork
使用upwork
方法创建一个配置为Upwork的OAuth1
实例。
$oauth1 = Risan\OAuth1\ProviderFactory::upwork([ 'client_credentials_identifier' => 'YOUR_API_KEY', 'client_credentials_secret' => 'YOUR_API_SECRET', 'callback_uri' => 'YOUR_CALLBACK_URI', ]);
您需要在此处注册Upwork应用程序以获取API密钥和密钥。基本URI设置为https://www.upwork.com/
,因此您可以使用相对URI。
$response = $oauth1->request('GET', 'api/auth/v1/info.json');
许可证
MIT © Risan Bagja Pradana