This commit is contained in:
wushumin
2026-05-11 15:28:27 +08:00
commit edd1a02157
302 changed files with 67193 additions and 0 deletions

View File

@@ -0,0 +1,78 @@
<?php
namespace app\support;
use support\Request;
use support\think\Db;
class EnterpriseOpenApiAuthService
{
public function authenticate(Request $request): array
{
$appKey = trim((string)$request->header('x-axy-app-key', ''));
$timestamp = trim((string)$request->header('x-axy-timestamp', ''));
$nonce = trim((string)$request->header('x-axy-nonce', ''));
$signature = trim((string)$request->header('x-axy-signature', ''));
if ($appKey === '' || $timestamp === '' || $nonce === '' || $signature === '') {
throw new \RuntimeException('开放接口鉴权头不完整');
}
if (!ctype_digit($timestamp) || abs(time() - (int)$timestamp) > 300) {
throw new \RuntimeException('请求时间戳已过期');
}
$app = Db::name('enterprise_customer_apps')->where('app_key', $appKey)->find();
if (!$app || ($app['status'] ?? 'enabled') !== 'enabled') {
throw new \RuntimeException('应用 Key 不存在或已停用');
}
$customer = Db::name('enterprise_customers')->where('id', $app['customer_id'])->find();
if (!$customer || ($customer['status'] ?? 'enabled') !== 'enabled') {
throw new \RuntimeException('客户不存在或已停用');
}
$this->storeNonce($appKey, $nonce, (int)$timestamp);
$secret = (new EnterpriseCustomerService())->decryptSecret((string)($app['app_secret_cipher'] ?? ''));
if ($secret === '') {
throw new \RuntimeException('应用密钥不可用');
}
$rawBody = $request->rawBody();
$pathWithQuery = $request->uri();
$base = strtoupper($request->method()) . $pathWithQuery . $timestamp . $nonce . hash('sha256', $rawBody);
$expected = hash_hmac('sha256', $base, $secret);
if (!hash_equals($expected, strtolower($signature))) {
throw new \RuntimeException('请求签名无效');
}
Db::name('enterprise_customer_apps')->where('id', $app['id'])->update([
'last_used_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
return [
'app' => $app,
'customer' => $customer,
];
}
private function storeNonce(string $appKey, string $nonce, int $timestamp): void
{
$expireBefore = date('Y-m-d H:i:s', time() - 600);
Db::name('enterprise_api_nonces')->where('created_at', '<', $expireBefore)->delete();
try {
Db::name('enterprise_api_nonces')->insert([
'app_key' => $appKey,
'nonce' => $nonce,
'request_timestamp' => $timestamp,
'created_at' => date('Y-m-d H:i:s'),
]);
} catch (\Throwable $e) {
throw new \RuntimeException('请求 nonce 已使用');
}
}
}