1.对接平台接口新增api-key参数

This commit is contained in:
2026-05-25 09:31:24 +08:00
parent 9a43e1d8f2
commit cde5a851e5
10 changed files with 105 additions and 11 deletions

View File

@@ -0,0 +1,64 @@
<?php
declare(strict_types=1);
namespace app\api\middleware;
use app\api\util\ReturnCode;
use plugin\saiadmin\exception\ApiException;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
/**
* 校验对接平台 api-key与 .env 中 API_KEY 一致)
* 仅用于 /api/v1/* 平台对接接口
*
* 取值优先级(按顺序读取,首个非空即采用):
* 1. 请求头 api-key推荐
* 2. 查询参数 api_key / api-key
* 3. body 表单/JSON api_key / api-key
*/
class ApiKeyMiddleware implements MiddlewareInterface
{
public function process(Request $request, callable $handler): Response
{
$expected = (string) config('api.platform_api_key', '');
if ($expected === '') {
throw new ApiException('API_KEY is not configured', ReturnCode::SERVER_ERROR);
}
$apiKey = $this->resolveApiKey($request);
if ($apiKey === '') {
throw new ApiException('Please provide api-key', ReturnCode::UNAUTHORIZED);
}
if (!hash_equals($expected, $apiKey)) {
throw new ApiException('Invalid api-key', ReturnCode::FORBIDDEN);
}
return $handler($request);
}
private function resolveApiKey(Request $request): string
{
$headerValue = $request->header('api-key');
if ($headerValue !== null && trim((string) $headerValue) !== '') {
return trim((string) $headerValue);
}
foreach (['api_key', 'api-key'] as $key) {
$val = $request->get($key);
if ($val !== null && trim((string) $val) !== '') {
return trim((string) $val);
}
}
foreach (['api_key', 'api-key'] as $key) {
$val = $request->post($key);
if ($val !== null && trim((string) $val) !== '') {
return trim((string) $val);
}
}
return '';
}
}