dchapkine/guzzle-http-signature

该包的最新版本(dev-master)没有提供许可证信息。

Guzzle 插件,用于使用 hmac 签名 HTTP 请求。换句话说,它是 https://github.com/joyent/node-http-signature 库(仅请求签名部分)的 PHP 5.3+ 版本。

dev-master 2012-11-24 07:01 UTC

This package is not auto-updated.

Last update: 2024-09-28 13:09:39 UTC


README

Guzzle Http Signature 插件是 node-http-signature 模块 的 PHP 5.3 版本。它允许您使用 签名认证方案 简单地签名 HTTP 头部。

注意,它仅实现客户端部分(签名创建),并没有实现服务器部分(签名解析和验证)。

有关此处使用的“签名认证方案”的更多信息,请参阅 http_signing.md

支持算法

目前仅支持 'hmac-sha1', 'hmac-sha256', 'hmac-sha512' 算法。

入门(通过 Composer)

推荐通过 Composer 安装 guzzle-http-signature。

  1. 在您的项目 composer.json 文件中添加以下依赖项,然后使用 php composer.phar install 命令安装。

    {
    	"require": {
    		"guzzle/guzzle": "2.*",
    		"dchapkine/guzzle-http-signature": "dev-master"
    	}
    }
  2. 使用它

    <?php
    
    require_once 'vendor/autoload.php';
    
    use Guzzle\Http\Client;
    use Guzzle\Http\Exception\ClientErrorResponseException;
    use Guzzle\Http\Exception\BadResponseException;
    use GuzzleHttpSignature\HttpSignaturePlugin;
    use Guzzle\Http\Exception\CurlException;
    
    
    
    //
    // request config
    //
    $requestUrl = 'https://api.domain.tld/jobs/44';
    $requestMethod = 'POST';
    $requestData = array("some" => array("custom" => array("data")));
    $requestHeaders = array('content-md5' => md5(http_build_query($requestData)));
    
    
    //
    // signature config
    //
    $keyId = "Test";			// your key id
    $key = "secret";			// your private key
    $algorithm = "hmac-sha512";	// algorithm: hmac-sha1, hmac-sha256, hmac-sha512
    $headersToSign = array(		// headers we want to include into signature
    	"date",
    	"content-md5"
    );
    
    
    //
    // sending request
    //
    try
    {
    	$plugin = new HttpSignaturePlugin(array(
    		'keyId' => $keyId,
    		'key' => $key,
    		'algorithm' => $algorithm,
    		'headers' => $headersToSign
    	));
    	
    	$client = new Client();
    	$client->addSubscriber($plugin);
    	$req = $client->createRequest($requestMethod, $requestUrl, $requestHeaders, $requestData);
    	$response = $req->send();
    }
    catch (ClientErrorResponseException $e)
    // guzzle throws ClientErrorResponseException when error http codes are sent (401, 500, ...)
    {
    	$response = $e->getResponse();
    }
    catch (CurlException $e)
    // the api provider is probably down or there is an issue with connection
    {
    	$msg = $e->getMessage();
    }
    
    
    //
    // print response
    //
    header('Content-Type: text');
    if (isset($response))
    	echo "\n" . $response->getStatusCode() . "\n" . $response->getBody(true) . "\n";
    else
    	echo $msg."\n";
    

链接

@see https://github.com/joyent/node-http-signature/blob/master/http_signing.md

@see http://joyent.com/blog/a-bit-more-about-the-new-joyent-cloud-api/