truelayer/signing

生成并验证TrueLayer API请求签名

v1.0.0 2024-02-29 17:13 UTC

This package is auto-updated.

Last update: 2024-08-29 18:31:48 UTC


README

PHP库,用于生成和验证TrueLayer API请求签名。如果您想了解更多关于TrueLayer签名如何工作的信息,请参阅此文档以获取解释。

安装

需要使用composer

$ composer require truelayer/signing

用法

签名

首先,创建一个Signer实例,使用以下方法之一

use TrueLayer\Signing\Signer;

$signer = Signer::signWithPemFile('kid-value', '/path/to/privatekey');
$signer = Signer::signWithPem('kid-value', $pemContents);
$signer = Signer::signWithPemBase64('kid-value', $pemContentsBase64Encoded);
$signer = Signer::signWithKey('kid-value', new \Jose\Component\Core\JWK());

然后您可以使用它来创建签名

use TrueLayer\Signing\Signer;

$signature = $signer->method('POST')
    ->path('/path') // The api path
    ->header('Idempotency-Key', 'my-key') // The idempotency key you must send with your request
    ->body('stringified request body')
    ->sign();    

您还可以对PSR-7请求进行签名,这将自动编译签名并将其添加到Tl-Signature头中。

use TrueLayer\Signing\Signer;

$request = $signer->addSignatureHeader($request)

验证

首先,检索公钥

使用Guzzle库的示例

use TrueLayer\Signing\Verifier;
use GuzzleHttp\Client;

// Note: you should add error handling as appropriate
$httpClient = new Client();
$response = $httpClient->get('https://webhooks.truelayer-sandbox.com/.well-known/jwks')->getBody()->getContents();
$keys = json_decode($response, true)['keys'];

$verifier = Verifier::verifyWithJsonKeys(...$keys); // Note the spread operator, it's important.

然后您可以使用它来验证您的webhook中收到的签名,该签名位于tl-signature头下

$verifier
    ->path('/path') // Should be your webhook path, for example $_SERVER['REQUEST_URI']
    ->headers($headers) // All headers you receive. Header names can be in any casing.
    ->body('stringified request body'); // For example file_get_contents('php://input');

try {
    $verifier->verify($headers['tl-signature']);
} catch (InvalidSignatureException $e) {
    throw $e; // Handle invalid signature. You should not use this request's data.
}