PHP code example of hypocenter / laravel-signature
1. Go to this page and download the library: Download hypocenter/laravel-signature library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hypocenter / laravel-signature example snippets
return [
// 默认的驱动
'default' => 'default',
// 支持多个签名器配置
'signatures' => [
'default' => [
'resolver' => 'header',
'repository' => 'array',
'nonce_length' => 16,
'cache_driver' => 'file',
'cache_name' => 'laravel-signature',
'time_tolerance' => 5* 60,
'default_app_id' => 'tFVzAUy07VIj2p8v',
]
],
// 数据获取器定义,支持从不同来源获取
'resolvers' => [
'header' => [
'class' => Hypocenter\LaravelSignature\Payload\Resolvers\HeaderResolver::class,
'key_app_id' => 'X-SIGN-APP-ID',
'key_sign' => 'X-SIGN',
'key_timestamp' => 'X-SIGN-TIME',
'key_nonce' => 'X-SIGN-NONCE',
],
'query' => [
'class' => Hypocenter\LaravelSignature\Payload\Resolvers\QueryResolver::class,
'key_app_id' => '_appid',
'key_sign' => '_sign',
'key_timestamp' => '_time',
'key_nonce' => '_nonce',
]
],
// App 定义数据仓库,支持从不同来源获取
'repositories' => [
// 从数据库中读取
'model' => [
'class' => Hypocenter\LaravelSignature\Define\Repositories\ModelRepository::class,
'model' => Hypocenter\LaravelSignature\Define\Models\AppDefine::class,
],
// 从配置文件中读取
'array' => [
'class' => Hypocenter\LaravelSignature\Define\Repositories\ArrayRepository::class,
'defines' => [
// Add more defines here.
[
'id' => 'tFVzAUy07VIj2p8v',
'name' => 'RPC',
'secret' => 'u4JsCDCwCUakBCVn',
'config' => null
],
],
],
],
];
$client = new \GuzzleHttp\Client(['base_uri' => env('RPC_SERVER')]);
$payload = new Payload::forSign()
->setAppId('your app ID') // 如果设置了 default_app_id 可省略
->setMethod('GET')
->setPath('api/users')
->setData(['page' => 1, 'page_size' => 20])
->build();
$driver = app('signature')->get();
$driver->sign($payload);
$res = $client->request($payload->getMethod(), $payload->getPath() . '?'. http_build_query($payload->getData()), [
'headers' => [
'Accept' => "application/json",
'X-SIGN-APP-ID' => $payload->getAppId(),
'X-SIGN' => $payload->getSign(),
'X-SIGN-TIME' => $payload->getTimestamp(),
'X-SIGN-NONCE' => $payload->getNonce()
]
]);
class Kernel extends HttpKernel {
protected $routeMiddleware = [
// ...
'signature' => \Hypocenter\LaravelSignature\Middleware\SignatureMiddleware::class
];
}
Route::get('test-sign', 'SignController')->middleware('signature'); // 使用默认渠道
Route::get('test-sign', 'SignController')->middleware('signature:custom'); // 使用其他驱动
php artisan vendor:publish --provider="Hypocenter\LaravelSignature\SignatureServiceProvider"