Просмотр исходного кода

refactor(thirdparty): 重构第三方模块代码

- 优化了 ThirdPartyCredentialController 和 ThirdPartyServiceController 的代码结构
- 新增 Config 和 Credential DTO 类,用于处理配置和凭证数据
- 重构 BaseRequest 类,使用新的 DTO 类处理配置和凭证
- 更新 UrsGetUserInfoRequest 和 WebhookReceiver 类,采用新的数据处理方式
- 移除了未使用的代码和冗余的注释
notfff 7 месяцев назад
Родитель
Сommit
663532e2f2

+ 15 - 0
ThirdParty/Urs/Dto/Config.php

@@ -0,0 +1,15 @@
+<?php
+
+namespace ThirdParty\Urs\Dto;
+
+/**
+ * Config配置
+ *
+ */
+class Config extends \App\Module\ThirdParty\Dto\Credential
+{
+
+
+
+
+}

+ 37 - 0
ThirdParty/Urs/Dto/Credential.php

@@ -0,0 +1,37 @@
+<?php
+
+namespace ThirdParty\Urs\Dto;
+
+/**
+ * 通讯密钥
+ */
+class Credential extends \App\Module\ThirdParty\Dto\Credential
+{
+
+    /**
+     * 请求密钥
+     *
+     * @var string $apiKey
+     */
+    public $apiKey;
+
+    /**
+     * 生态ID
+     *
+     * @var int $ecologyId
+     */
+    public $ecologyId;
+
+
+    public function getApiKey()
+    {
+        return $this->apiKey ?? "";
+
+    }
+
+    public function getEcologyId()
+    {
+        return $this->ecologyId ?? "1";
+    }
+
+}

+ 30 - 0
ThirdParty/Urs/Request/BaseRequest.php

@@ -0,0 +1,30 @@
+<?php
+
+namespace ThirdParty\Urs\Request;
+
+
+use ThirdParty\Urs\Dto\Config;
+
+abstract class BaseRequest extends \App\Module\ThirdParty\Services\BaseRequest
+{
+
+    /**
+     * 构造函数
+     */
+    public function __construct()
+    {
+        // 使用'urs'作为服务代码,需要在thirdparty_services表中注册
+        parent::__construct('urs');
+    }
+
+    protected function getConfig(string $c = ''): \ThirdParty\Urs\Dto\Config
+    {
+        return Config::fromArray($this->service->config);
+    }
+
+    protected function getCredential(string $c = ''): \ThirdParty\Urs\Dto\Credential
+    {
+        return \ThirdParty\Urs\Dto\Credential::fromArray($this->service->config);
+    }
+
+}

+ 9 - 15
ThirdParty/Urs/Request/UrsGetUserInfoRequest.php

@@ -11,16 +11,9 @@ use ThirdParty\Urs\Util\CryptoService;
  * 专门处理获取用户信息请求,遵循"一个Request类只完成一种请求"的原则
  * 根据用户密钥获取用户ID
  */
-class UrsGetUserInfoRequest extends BaseRequest
+class UrsGetUserInfoRequest extends \ThirdParty\Urs\Request\BaseRequest
 {
-    /**
-     * 构造函数
-     */
-    public function __construct()
-    {
-        // 使用'urs'作为服务代码,需要在thirdparty_services表中注册
-        parent::__construct('urs');
-    }
+
 
     /**
      * 处理获取用户信息请求
@@ -29,7 +22,7 @@ class UrsGetUserInfoRequest extends BaseRequest
      * @return array 返回包含userId的数组
      * @throws \Exception
      */
-    protected function handler(array $params): array
+    protected function handler(array $params =[]): array
     {
         // 验证必需参数
         if (empty($params['userKey'])) {
@@ -37,10 +30,11 @@ class UrsGetUserInfoRequest extends BaseRequest
         }
 
         // 获取URS配置
-        $config = $this->getConfig();
-        $apiUrl = $config['api_url'] ?? '';
-        $appKey = $config['app_key'] ?? '';
-        $ecologyId = $config['ecology_id'] ?? 1;
+        $c = $this->getCredential();
+
+        $apiUrl = $this->getService()->getApiUrl();
+        $appKey = $c->getApiKey() ;
+        $ecologyId = $c->getApiKey();
 
         if (empty($apiUrl) || empty($appKey)) {
             throw new \Exception('URS配置不完整,缺少api_url或app_key');
@@ -64,7 +58,7 @@ class UrsGetUserInfoRequest extends BaseRequest
         // 解密响应数据
         if (isset($response['data'], $response['iv'], $response['timestamp'], $response['sign'])) {
             $decryptedResponse = $cryptoService->decrypt($response);
-            
+
             return [
                 'success' => true,
                 'message' => '获取用户信息成功',

+ 8 - 170
ThirdParty/Urs/Webhook/UrsCheckWebhook.php

@@ -14,6 +14,7 @@ use Illuminate\Support\Facades\Log;
  */
 class UrsCheckWebhook extends WebhookReceiver
 {
+
     /**
      * 构造函数
      *
@@ -45,7 +46,7 @@ class UrsCheckWebhook extends WebhookReceiver
         $this->validateCheckRequest($request);
 
         // 处理余额检查通知
-        return $this->processCheckNotification($request);
+        return $this->processCheck($request);
     }
 
     /**
@@ -56,7 +57,7 @@ class UrsCheckWebhook extends WebhookReceiver
      */
     protected function validateCheckRequest(Request $request): void
     {
-        $requiredFields = ['user_id', 'check_type'];
+        $requiredFields = [ 'user_id', 'check_type' ];
 
         foreach ($requiredFields as $field) {
             if (!$request->has($field)) {
@@ -72,182 +73,19 @@ class UrsCheckWebhook extends WebhookReceiver
 
         // 验证检查类型
         $checkType = $request->input('check_type');
-        if (!in_array($checkType, ['balance', 'transaction', 'status', 'limit'])) {
+        if (!in_array($checkType, [ 'balance', 'transaction', 'status', 'limit' ])) {
             throw new \Exception('检查类型无效,必须是: balance, transaction, status, limit');
         }
     }
 
-    /**
-     * 处理余额检查通知
-     *
-     * @param Request $request 请求对象
-     * @return array
-     */
-    protected function processCheckNotification(Request $request): array
-    {
-        $userId = $request->input('user_id');
-        $checkType = $request->input('check_type');
-        $requestId = $request->input('request_id', '');
-
-        // 记录处理日志
-        Log::info("URS余额检查通知处理", [
-            'user_id' => $userId,
-            'check_type' => $checkType,
-            'request_id' => $requestId,
-            'webhook_request_id' => $this->getRequestId(),
-        ]);
-
-        // 根据检查类型执行不同的处理逻辑
-        switch ($checkType) {
-            case 'balance':
-                return $this->handleBalanceCheck($userId, $requestId);
-            case 'transaction':
-                return $this->handleTransactionCheck($userId, $requestId);
-            case 'status':
-                return $this->handleStatusCheck($userId, $requestId);
-            case 'limit':
-                return $this->handleLimitCheck($userId, $requestId);
-            default:
-                throw new \Exception("未知的检查类型: {$checkType}");
-        }
-    }
-
-    /**
-     * 处理余额检查
-     *
-     * @param int $userId 用户ID
-     * @param string $requestId 请求ID
-     * @return array
-     */
-    protected function handleBalanceCheck(int $userId, string $requestId): array
-    {
-        // 这里可以调用Fund模块获取用户余额
-        // 例如:$balance = FundService::getBalance($userId);
-
-        // 模拟余额数据
-        $balanceData = [
-            'total_balance' => 1000.50,
-            'available_balance' => 950.00,
-            'frozen_balance' => 50.50,
-            'currency' => 'CNY',
-        ];
-
-        return [
-            'message' => '余额检查处理完成',
-            'user_id' => $userId,
-            'request_id' => $requestId,
-            'check_type' => 'balance',
-            'data' => $balanceData,
-            'status' => 'success',
-            'processed_at' => now()->toISOString(),
-        ];
-    }
-
-    /**
-     * 处理交易记录检查
-     *
-     * @param int $userId 用户ID
-     * @param string $requestId 请求ID
-     * @return array
-     */
-    protected function handleTransactionCheck(int $userId, string $requestId): array
+    public function processCheck()
     {
-        // 这里可以调用Fund模块获取用户交易记录
-        // 例如:$transactions = FundService::getTransactions($userId);
-
-        // 模拟交易数据
-        $transactionData = [
-            'recent_transactions' => [
-                [
-                    'id' => 'TXN001',
-                    'type' => 'deposit',
-                    'amount' => 100.00,
-                    'status' => 'success',
-                    'created_at' => '2025-06-14 14:30:00',
-                ],
-                [
-                    'id' => 'TXN002',
-                    'type' => 'withdraw',
-                    'amount' => 50.00,
-                    'status' => 'pending',
-                    'created_at' => '2025-06-14 15:00:00',
-                ],
-            ],
-            'total_count' => 25,
-        ];
-
+        // 是否允许,钻石余额 ,本金总数,手续费总数,所需总数
+        // 调用 充值模块 来完成
         return [
-            'message' => '交易记录检查处理完成',
-            'user_id' => $userId,
-            'request_id' => $requestId,
-            'check_type' => 'transaction',
-            'data' => $transactionData,
-            'status' => 'success',
-            'processed_at' => now()->toISOString(),
-        ];
-    }
-
-    /**
-     * 处理状态检查
-     *
-     * @param int $userId 用户ID
-     * @param string $requestId 请求ID
-     * @return array
-     */
-    protected function handleStatusCheck(int $userId, string $requestId): array
-    {
-        // 这里可以调用相关模块获取用户状态
-        // 例如:$status = UserService::getStatus($userId);
-
-        // 模拟状态数据
-        $statusData = [
-            'account_status' => 'active',
-            'kyc_status' => 'verified',
-            'risk_level' => 'low',
-            'last_login' => '2025-06-14 16:00:00',
+            'check' => true,
         ];
 
-        return [
-            'message' => '状态检查处理完成',
-            'user_id' => $userId,
-            'request_id' => $requestId,
-            'check_type' => 'status',
-            'data' => $statusData,
-            'status' => 'success',
-            'processed_at' => now()->toISOString(),
-        ];
     }
 
-    /**
-     * 处理限额检查
-     *
-     * @param int $userId 用户ID
-     * @param string $requestId 请求ID
-     * @return array
-     */
-    protected function handleLimitCheck(int $userId, string $requestId): array
-    {
-        // 这里可以调用相关模块获取用户限额信息
-        // 例如:$limits = UserService::getLimits($userId);
-
-        // 模拟限额数据
-        $limitData = [
-            'daily_deposit_limit' => 10000.00,
-            'daily_withdraw_limit' => 5000.00,
-            'used_deposit_today' => 1500.00,
-            'used_withdraw_today' => 200.00,
-            'remaining_deposit' => 8500.00,
-            'remaining_withdraw' => 4800.00,
-        ];
-
-        return [
-            'message' => '限额检查处理完成',
-            'user_id' => $userId,
-            'request_id' => $requestId,
-            'check_type' => 'limit',
-            'data' => $limitData,
-            'status' => 'success',
-            'processed_at' => now()->toISOString(),
-        ];
-    }
 }

+ 11 - 104
ThirdParty/Urs/Webhook/UrsDepositWebhook.php

@@ -14,6 +14,7 @@ use Illuminate\Support\Facades\Log;
  */
 class UrsDepositWebhook extends WebhookReceiver
 {
+
     /**
      * 构造函数
      *
@@ -56,7 +57,7 @@ class UrsDepositWebhook extends WebhookReceiver
      */
     protected function validateDepositRequest(Request $request): void
     {
-        $requiredFields = ['user_id', 'amount', 'order_id', 'status'];
+        $requiredFields = [ 'user_id', 'amount', 'order_id' ];
 
         foreach ($requiredFields as $field) {
             if (!$request->has($field)) {
@@ -82,11 +83,6 @@ class UrsDepositWebhook extends WebhookReceiver
             throw new \Exception('订单ID不能为空');
         }
 
-        // 验证状态
-        $status = $request->input('status');
-        if (!in_array($status, ['success', 'failed', 'pending'])) {
-            throw new \Exception('状态值无效,必须是: success, failed, pending');
-        }
     }
 
     /**
@@ -97,117 +93,28 @@ class UrsDepositWebhook extends WebhookReceiver
      */
     protected function processDepositNotification(Request $request): array
     {
-        $userId = $request->input('user_id');
-        $amount = $request->input('amount');
+        $userId  = $request->input('user_id');
+        $amount  = $request->input('amount');
         $orderId = $request->input('order_id');
-        $status = $request->input('status');
-        $message = $request->input('message', '');
+
 
         // 记录处理日志
         Log::info("URS充值通知处理", [
-            'user_id' => $userId,
-            'amount' => $amount,
+            'user_id'  => $userId,
+            'amount'   => $amount,
             'order_id' => $orderId,
-            'status' => $status,
-            'message' => $message,
             'request_id' => $this->getRequestId(),
         ]);
 
-        // 根据状态执行不同的处理逻辑
-        switch ($status) {
-            case 'success':
-                return $this->handleSuccessfulDeposit($userId, $amount, $orderId);
-            case 'failed':
-                return $this->handleFailedDeposit($userId, $amount, $orderId, $message);
-            case 'pending':
-                return $this->handlePendingDeposit($userId, $amount, $orderId);
-            default:
-                throw new \Exception("未知的充值状态: {$status}");
-        }
-    }
-
-    /**
-     * 处理充值成功
-     *
-     * @param int $userId 用户ID
-     * @param float $amount 充值金额
-     * @param string $orderId 订单ID
-     * @return array
-     */
-    protected function handleSuccessfulDeposit(int $userId, float $amount, string $orderId): array
-    {
-        // 这里可以调用Fund模块的充值逻辑
-        // 例如:FundService::deposit($userId, $amount, $orderId);
+        // 进行重置钻石逻辑
+        // 先创建充值单,然后返回成功,通过会队列处理充值单
+        $rorder_id = time();
 
         return [
-            'message' => '充值成功通知处理完成',
-            'user_id' => $userId,
-            'amount' => $amount,
-            'order_id' => $orderId,
-            'status' => 'success',
-            'actions' => [
-                'balance_updated' => true,
-                'transaction_recorded' => true,
-                'user_notified' => true,
-            ],
-            'processed_at' => now()->toISOString(),
+            'rorder_id' => $rorder_id
         ];
-    }
 
-    /**
-     * 处理充值失败
-     *
-     * @param int $userId 用户ID
-     * @param float $amount 充值金额
-     * @param string $orderId 订单ID
-     * @param string $message 失败原因
-     * @return array
-     */
-    protected function handleFailedDeposit(int $userId, float $amount, string $orderId, string $message): array
-    {
-        // 这里可以调用相关的失败处理逻辑
-        // 例如:记录失败原因、退款处理等
-
-        return [
-            'message' => '充值失败通知处理完成',
-            'user_id' => $userId,
-            'amount' => $amount,
-            'order_id' => $orderId,
-            'status' => 'failed',
-            'failure_reason' => $message,
-            'actions' => [
-                'failure_logged' => true,
-                'refund_initiated' => true,
-                'user_notified' => true,
-            ],
-            'processed_at' => now()->toISOString(),
-        ];
     }
 
-    /**
-     * 处理充值待处理
-     *
-     * @param int $userId 用户ID
-     * @param float $amount 充值金额
-     * @param string $orderId 订单ID
-     * @return array
-     */
-    protected function handlePendingDeposit(int $userId, float $amount, string $orderId): array
-    {
-        // 这里可以调用待处理相关的逻辑
-        // 例如:加入处理队列、发送通知等
 
-        return [
-            'message' => '充值待处理通知处理完成',
-            'user_id' => $userId,
-            'amount' => $amount,
-            'order_id' => $orderId,
-            'status' => 'pending',
-            'actions' => [
-                'added_to_processing_queue' => true,
-                'admin_notified' => true,
-            ],
-            'processed_at' => now()->toISOString(),
-        ];
-    }
 }

+ 1 - 156
ThirdParty/Urs/Webhook/UrsRegisterWebhook.php

@@ -36,165 +36,10 @@ class UrsRegisterWebhook extends WebhookReceiver
      */
     protected function handler(string $action, Request $request): array
     {
-        // 验证操作类型
-        if ($action !== 'register') {
-            throw new \Exception("此处理器只能处理register操作,当前操作: {$action}");
-        }
-
-        // 验证必需字段
-        $this->validateRegisterRequest($request);
-
         // 处理注册通知
-        return $this->processRegisterNotification($request);
-    }
-
-    /**
-     * 验证注册请求
-     *
-     * @param Request $request 请求对象
-     * @throws \Exception
-     */
-    protected function validateRegisterRequest(Request $request): void
-    {
-        $requiredFields = ['user_id', 'username', 'status'];
-
-        foreach ($requiredFields as $field) {
-            if (!$request->has($field)) {
-                throw new \Exception("缺少必需字段: {$field}");
-            }
-        }
-
-        // 验证用户ID格式
-        $userId = $request->input('user_id');
-        if (!is_numeric($userId) || $userId <= 0) {
-            throw new \Exception('用户ID格式无效');
-        }
-
-        // 验证用户名格式
-        $username = $request->input('username');
-        if (empty($username) || strlen($username) > 50) {
-            throw new \Exception('用户名格式无效');
-        }
-
-        // 验证状态值
-        $status = $request->input('status');
-        if (!in_array($status, ['success', 'failed', 'pending'])) {
-            throw new \Exception('状态值无效,必须是: success, failed, pending');
-        }
+        return [];
     }
 
-    /**
-     * 处理注册通知
-     *
-     * @param Request $request 请求对象
-     * @return array
-     */
-    protected function processRegisterNotification(Request $request): array
-    {
-        $userId = $request->input('user_id');
-        $username = $request->input('username');
-        $status = $request->input('status');
-        $message = $request->input('message', '');
-
-        // 这里可以调用相关的业务逻辑
-        // 例如:更新用户注册状态、发送通知等
-
-        // 记录处理日志
-        Log::info("URS注册通知处理", [
-            'user_id' => $userId,
-            'username' => $username,
-            'status' => $status,
-            'message' => $message,
-            'request_id' => $this->getRequestId(),
-        ]);
 
-        // 根据状态执行不同的处理逻辑
-        switch ($status) {
-            case 'success':
-                return $this->handleSuccessfulRegistration($userId, $username);
-            case 'failed':
-                return $this->handleFailedRegistration($userId, $username, $message);
-            case 'pending':
-                return $this->handlePendingRegistration($userId, $username);
-            default:
-                throw new \Exception("未知的注册状态: {$status}");
-        }
-    }
 
-    /**
-     * 处理注册成功
-     *
-     * @param int $userId 用户ID
-     * @param string $username 用户名
-     * @return array
-     */
-    protected function handleSuccessfulRegistration(int $userId, string $username): array
-    {
-        // 这里可以调用用户模块的相关服务
-        // 例如:激活用户账户、发送欢迎邮件等
-
-        return [
-            'message' => '注册成功通知处理完成',
-            'user_id' => $userId,
-            'username' => $username,
-            'status' => 'success',
-            'actions' => [
-                'account_activated' => true,
-                'welcome_email_sent' => true,
-            ],
-            'processed_at' => now()->toISOString(),
-        ];
-    }
-
-    /**
-     * 处理注册失败
-     *
-     * @param int $userId 用户ID
-     * @param string $username 用户名
-     * @param string $message 失败原因
-     * @return array
-     */
-    protected function handleFailedRegistration(int $userId, string $username, string $message): array
-    {
-        // 这里可以调用相关的失败处理逻辑
-        // 例如:记录失败原因、发送通知等
-
-        return [
-            'message' => '注册失败通知处理完成',
-            'user_id' => $userId,
-            'username' => $username,
-            'status' => 'failed',
-            'failure_reason' => $message,
-            'actions' => [
-                'failure_logged' => true,
-                'admin_notified' => true,
-            ],
-            'processed_at' => now()->toISOString(),
-        ];
-    }
-
-    /**
-     * 处理注册待审核
-     *
-     * @param int $userId 用户ID
-     * @param string $username 用户名
-     * @return array
-     */
-    protected function handlePendingRegistration(int $userId, string $username): array
-    {
-        // 这里可以调用审核相关的逻辑
-        // 例如:加入审核队列、发送审核通知等
-
-        return [
-            'message' => '注册待审核通知处理完成',
-            'user_id' => $userId,
-            'username' => $username,
-            'status' => 'pending',
-            'actions' => [
-                'added_to_review_queue' => true,
-                'admin_notified' => true,
-            ],
-            'processed_at' => now()->toISOString(),
-        ];
-    }
 }

+ 7 - 22
ThirdParty/Urs/Webhook/UrsWithdrawWebhook.php

@@ -56,7 +56,7 @@ class UrsWithdrawWebhook extends WebhookReceiver
      */
     protected function validateWithdrawRequest(Request $request): void
     {
-        $requiredFields = ['user_id', 'amount', 'order_id', 'status'];
+        $requiredFields = ['user_id', 'amount', 'order_id'];
 
         foreach ($requiredFields as $field) {
             if (!$request->has($field)) {
@@ -82,11 +82,7 @@ class UrsWithdrawWebhook extends WebhookReceiver
             throw new \Exception('订单ID不能为空');
         }
 
-        // 验证状态
-        $status = $request->input('status');
-        if (!in_array($status, ['success', 'failed', 'pending'])) {
-            throw new \Exception('状态值无效,必须是: success, failed, pending');
-        }
+
     }
 
     /**
@@ -100,30 +96,19 @@ class UrsWithdrawWebhook extends WebhookReceiver
         $userId = $request->input('user_id');
         $amount = $request->input('amount');
         $orderId = $request->input('order_id');
-        $status = $request->input('status');
-        $message = $request->input('message', '');
+
+
 
         // 记录处理日志
-        Log::info("URS提取通知处理", [
+        Log::info("URS提取 钻石 通知处理", [
             'user_id' => $userId,
             'amount' => $amount,
             'order_id' => $orderId,
-            'status' => $status,
-            'message' => $message,
+
             'request_id' => $this->getRequestId(),
         ]);
 
-        // 根据状态执行不同的处理逻辑
-        switch ($status) {
-            case 'success':
-                return $this->handleSuccessfulWithdraw($userId, $amount, $orderId);
-            case 'failed':
-                return $this->handleFailedWithdraw($userId, $amount, $orderId, $message);
-            case 'pending':
-                return $this->handlePendingWithdraw($userId, $amount, $orderId);
-            default:
-                throw new \Exception("未知的提取状态: {$status}");
-        }
+
     }
 
     /**

+ 22 - 26
app/Module/ThirdParty/AdminControllers/ThirdPartyCredentialController.php

@@ -44,16 +44,16 @@ class ThirdPartyCredentialController extends AdminController
      */
     protected function grid(): Grid
     {
-        return Grid::make(new ThirdPartyCredentialRepository(), function (Grid $grid) {
+        return Grid::make(new ThirdPartyCredentialRepository(['service']), function (Grid $grid) {
             // 基础设置
             $grid->column('id', 'ID')->sortable();
-            
+
             // 关联服务
             $grid->column('service.name', '所属服务')->sortable();
             $grid->column('service.code', '服务代码');
-            
+
             $grid->column('name', '凭证名称')->sortable();
-            
+
             // 认证类型
             $grid->column('type', '认证类型')->display(function ($type) {
                 $authType = AUTH_TYPE::tryFrom($type);
@@ -70,7 +70,7 @@ class ThirdPartyCredentialController extends AdminController
             $grid->column('environment', '环境')->display(function ($env) {
                 $colors = [
                     'production' => 'danger',
-                    'staging' => 'warning', 
+                    'staging' => 'warning',
                     'development' => 'info',
                     'testing' => 'secondary',
                 ];
@@ -87,8 +87,8 @@ class ThirdPartyCredentialController extends AdminController
 
             // 状态
             $grid->column('is_active', '状态')->display(function ($active) {
-                return $active ? 
-                    '<span class="badge badge-success"><i class="fa fa-check"></i> 激活</span>' : 
+                return $active ?
+                    '<span class="badge badge-success"><i class="fa fa-check"></i> 激活</span>' :
                     '<span class="badge badge-secondary"><i class="fa fa-times"></i> 未激活</span>';
             });
 
@@ -97,7 +97,7 @@ class ThirdPartyCredentialController extends AdminController
                 if (!$time) {
                     return '<span class="badge badge-success">永不过期</span>';
                 }
-                
+
                 $expireTime = \Carbon\Carbon::parse($time);
                 if ($expireTime->isPast()) {
                     return '<span class="badge badge-danger">已过期</span>';
@@ -154,7 +154,7 @@ class ThirdPartyCredentialController extends AdminController
                 if ($actions->row->is_active) {
                     $actions->append('<a href="/admin/thirdparty/credentials/' . $actions->getKey() . '/test" class="btn btn-xs btn-warning"><i class="fa fa-flask"></i> 测试</a>');
                 }
-                
+
                 $actions->append('<a href="/admin/thirdparty/credentials/' . $actions->getKey() . '/usage" class="btn btn-xs btn-info"><i class="fa fa-chart-line"></i> 使用统计</a>');
             });
 
@@ -170,14 +170,14 @@ class ThirdPartyCredentialController extends AdminController
      */
     protected function detail($id): Show
     {
-        return Show::make($id, new ThirdPartyCredentialRepository(), function (Show $show) {
+        return Show::make($id, new ThirdPartyCredentialRepository(['service']), function (Show $show) {
             $show->field('id', 'ID');
-            
+
             $show->field('service.name', '所属服务');
             $show->field('service.code', '服务代码');
-            
+
             $show->field('name', '凭证名称');
-            
+
             $show->field('type', '认证类型')->as(function ($type) {
                 $authType = AUTH_TYPE::tryFrom($type);
                 return $authType ? $authType->getLabel() : $type;
@@ -201,11 +201,11 @@ class ThirdPartyCredentialController extends AdminController
                 if (!$time) {
                     return '永不过期';
                 }
-                
+
                 $expireTime = \Carbon\Carbon::parse($time);
-                $status = $expireTime->isPast() ? ' (已过期)' : 
+                $status = $expireTime->isPast() ? ' (已过期)' :
                          ($expireTime->diffInDays() <= 7 ? ' (即将过期)' : '');
-                
+
                 return $expireTime->format('Y-m-d H:i:s') . $status;
             });
 
@@ -236,7 +236,7 @@ class ThirdPartyCredentialController extends AdminController
                 ->help('选择要配置凭证的第三方服务');
 
             $form->text('name', '凭证名称')->required()->help('凭证的显示名称');
-            
+
             $form->select('type', '认证类型')
                 ->options(AUTH_TYPE::getOptions())
                 ->required()
@@ -245,7 +245,7 @@ class ThirdPartyCredentialController extends AdminController
             $form->select('environment', '环境')
                 ->options([
                     'production' => '生产环境',
-                    'staging' => '预发布环境', 
+                    'staging' => '预发布环境',
                     'development' => '开发环境',
                     'testing' => '测试环境',
                 ])
@@ -257,7 +257,7 @@ class ThirdPartyCredentialController extends AdminController
             $form->datetime('expires_at', '过期时间')->help('留空表示永不过期');
 
             // 凭证信息(根据认证类型动态显示)
-            $form->json('credentials', '凭证信息')
+            $form->keyValue('credentials', '凭证信息')
                 ->required()
                 ->help('根据认证类型填写相应的凭证信息,如API Key、Secret等');
 
@@ -266,13 +266,9 @@ class ThirdPartyCredentialController extends AdminController
             $form->display('created_at', '创建时间');
             $form->display('updated_at', '更新时间');
 
-            // 保存前处理
-            $form->saving(function (Form $form) {
-                // 加密敏感信息
-                if ($form->credentials) {
-                    $form->credentials = encrypt($form->credentials);
-                }
-            });
+
+
+
         });
     }
 }

+ 5 - 8
app/Module/ThirdParty/AdminControllers/ThirdPartyServiceController.php

@@ -50,7 +50,7 @@ class ThirdPartyServiceController extends AdminController
             $grid->column('id', 'ID')->sortable();
             $grid->column('name', '服务名称')->sortable();
             $grid->column('code', '服务代码')->sortable();
-            
+
             // 服务类型
             $grid->column('type', '服务类型')->display(function ($type) {
                 $serviceType = SERVICE_TYPE::tryFrom($type);
@@ -139,7 +139,7 @@ class ThirdPartyServiceController extends AdminController
             $grid->actions(function (Grid\Displayers\Actions $actions) {
                 $actions->append('<a href="/admin/thirdparty/credentials?service_id=' . $actions->getKey() . '" class="btn btn-xs btn-primary"><i class="fa fa-key"></i> 凭证</a>');
                 $actions->append('<a href="/admin/thirdparty/logs?service_id=' . $actions->getKey() . '" class="btn btn-xs btn-info"><i class="fa fa-list"></i> 日志</a>');
-                
+
                 if ($actions->row->status === SERVICE_STATUS::ACTIVE->value) {
                     $actions->append('<a href="/admin/thirdparty/services/' . $actions->getKey() . '/test" class="btn btn-xs btn-warning"><i class="fa fa-flask"></i> 测试</a>');
                 }
@@ -161,7 +161,7 @@ class ThirdPartyServiceController extends AdminController
             $show->field('id', 'ID');
             $show->field('name', '服务名称');
             $show->field('code', '服务代码');
-            
+
             $show->field('type', '服务类型')->as(function ($type) {
                 $serviceType = SERVICE_TYPE::tryFrom($type);
                 return $serviceType ? $serviceType->getLabel() : $type;
@@ -238,7 +238,7 @@ class ThirdPartyServiceController extends AdminController
 
             $form->text('name', '服务名称')->required()->help('第三方服务的显示名称');
             $form->text('code', '服务代码')->help('唯一标识符,留空自动生成');
-            
+
             $form->select('type', '服务类型')->options(SERVICE_TYPE::getOptions())->required();
             $form->text('provider', '服务提供商')->required();
             $form->textarea('description', '服务描述');
@@ -277,10 +277,7 @@ class ThirdPartyServiceController extends AdminController
 
             // 保存前处理
             $form->saving(function (Form $form) {
-                // 如果没有提供代码,自动生成
-                if (empty($form->code)) {
-                    $form->code = ThirdPartyService::generateCode($form->name, $form->provider);
-                }
+
 
                 // 处理keyValue字段,转换为JSON存储
                 $keyValueFields = ['config', 'headers', 'params'];

+ 10 - 0
app/Module/ThirdParty/Dto/Config.php

@@ -0,0 +1,10 @@
+<?php
+
+namespace App\Module\ThirdParty\Dto;
+
+use UCore\Dto\BaseDto;
+
+class Config extends BaseDto
+{
+
+}

+ 20 - 0
app/Module/ThirdParty/Dto/Credential.php

@@ -0,0 +1,20 @@
+<?php
+
+namespace App\Module\ThirdParty\Dto;
+
+use UCore\Dto\BaseDto;
+
+class Credential extends BaseDto
+{
+
+    public function __serialize(): array
+    {
+        return self::toArray();
+    }
+
+    public function __unserialize(array $data): void
+    {
+         self::fromArray($data);
+    }
+
+}

+ 29 - 22
app/Module/ThirdParty/Services/BaseRequest.php

@@ -2,6 +2,8 @@
 
 namespace App\Module\ThirdParty\Services;
 
+use App\Module\ThirdParty\Dto\Config;
+use App\Module\ThirdParty\Dto\Credential;
 use App\Module\ThirdParty\Models\ThirdPartyService as ServiceModel;
 use App\Module\ThirdParty\Models\ThirdPartyCredential;
 use App\Module\ThirdParty\Models\ThirdPartyLog;
@@ -20,6 +22,7 @@ use Illuminate\Http\Client\Response;
  */
 abstract class BaseRequest
 {
+
     /**
      * 服务代码
      */
@@ -53,8 +56,8 @@ abstract class BaseRequest
     public function __construct(string $serviceCode)
     {
         $this->serviceCode = $serviceCode;
-        $this->requestId = uniqid('req_', true);
-        $this->startTime = microtime(true);
+        $this->requestId   = uniqid('req_', true);
+        $this->startTime   = microtime(true);
 
         // 初始化服务配置
         $this->initializeService();
@@ -115,7 +118,7 @@ abstract class BaseRequest
 
         } catch (\Exception $e) {
             // 记录失败日志
-            $this->logRequest($params, ['error' => $e->getMessage()], false);
+            $this->logRequest($params, [ 'error' => $e->getMessage() ], false);
 
             throw $e;
         }
@@ -127,8 +130,11 @@ abstract class BaseRequest
      * @param array $params 请求参数
      * @return array
      */
-    abstract protected function handler(array $params): array;
+    abstract protected function handler(array $params = []): array;
+
+    abstract protected function getCredential(string $params = ''): Credential;
 
+    abstract protected function getConfig(string $params = ''): Config;
 
     /**
      * 检查配额
@@ -160,24 +166,24 @@ abstract class BaseRequest
         $responseTime = (int)((microtime(true) - $this->startTime) * 1000);
 
         ThirdPartyLog::create([
-            'service_id' => $this->service->id,
-            'credential_id' => $this->credential->id,
-            'request_id' => $this->requestId,
-            'method' => 'PACKAGE_CALL',
-            'url' => $this->serviceCode,
-            'request_headers' => json_encode([]),
-            'request_body' => json_encode($params),
-            'response_status' => $success ? 200 : 500,
-            'response_headers' => json_encode([]),
-            'response_body' => json_encode($result),
-            'response_time' => $responseTime,
-            'success' => $success,
-            'error_message' => $success ? null : ($result['error'] ?? '未知错误'),
-            'level' => $success ? LOG_LEVEL::INFO->value : LOG_LEVEL::ERROR->value,
-            'ip_address' => request()->ip(),
-            'user_agent' => request()->userAgent(),
-            'called_at' => now(),
-        ]);
+                                  'service_id'       => $this->service->id,
+                                  'credential_id'    => $this->credential->id,
+                                  'request_id'       => $this->requestId,
+                                  'method'           => 'PACKAGE_CALL',
+                                  'url'              => $this->serviceCode,
+                                  'request_headers'  => json_encode([]),
+                                  'request_body'     => json_encode($params),
+                                  'response_status'  => $success ? 200 : 500,
+                                  'response_headers' => json_encode([]),
+                                  'response_body'    => json_encode($result),
+                                  'response_time'    => $responseTime,
+                                  'success'          => $success,
+                                  'error_message'    => $success ? null : ($result['error'] ?? '未知错误'),
+                                  'level'            => $success ? LOG_LEVEL::INFO->value : LOG_LEVEL::ERROR->value,
+                                  'ip_address'       => request()->ip(),
+                                  'user_agent'       => request()->userAgent(),
+                                  'called_at'        => now(),
+                              ]);
     }
 
     /**
@@ -226,4 +232,5 @@ abstract class BaseRequest
     {
         return $this->requestId;
     }
+
 }

+ 55 - 19
app/Module/ThirdParty/Services/WebhookDispatchService.php

@@ -8,7 +8,7 @@ use App\Module\ThirdParty\Models\ThirdPartyService as ServiceModel;
 
 /**
  * Webhook分发服务
- * 
+ *
  * 负责将Webhook请求分发到对应的第三方包处理器
  * 支持ThirdParty命名空间下的包注册和管理
  */
@@ -21,7 +21,7 @@ class WebhookDispatchService
      * @var array
      */
     protected static array $packageHandlers = [];
-    
+
     /**
      * 分发Webhook请求到指定包的处理器
      *
@@ -72,7 +72,7 @@ class WebhookDispatchService
         // 返回响应数据
         return $response->getData(true);
     }
-    
+
     /**
      * 注册包处理器
      *
@@ -94,7 +94,7 @@ class WebhookDispatchService
             'handler_class' => $handlerClass,
         ]);
     }
-    
+
     /**
      * 批量注册包处理器
      *
@@ -107,7 +107,7 @@ class WebhookDispatchService
             static::registerPackageHandler($packageName, $route, $handlerClass);
         }
     }
-    
+
     /**
      * 获取包的处理器类
      *
@@ -119,7 +119,7 @@ class WebhookDispatchService
     {
         return static::$packageHandlers[$packageName][$handlerRoute] ?? null;
     }
-    
+
     /**
      * 根据包名获取服务配置对象
      *
@@ -160,8 +160,7 @@ class WebhookDispatchService
      */
     protected function validateWebhookSignature(Request $request, ServiceModel $service): bool
     {
-        $config = $service->config ?? [];
-        $webhookSecret = $config['webhook_secret'] ?? null;
+        $webhookSecret = $service->webhook_secret;
 
         if (!$webhookSecret) {
             // 如果没有配置密钥,则跳过签名验证
@@ -173,12 +172,49 @@ class WebhookDispatchService
             return false;
         }
 
-        $payload = $request->getContent();
-        $expectedSignature = hash_hmac('sha256', $payload, $webhookSecret);
+        // 使用POST参数排序后拼接的方式生成签名字符串
+        $signString = $this->buildSignString($request->post());
+        $expectedSignature = hash_hmac('sha256', $signString, $webhookSecret);
 
         return hash_equals($expectedSignature, $signature);
     }
 
+    /**
+     * 构建签名字符串(支付宝方式:参数排序后拼接)
+     *
+     * @param array $params 请求参数
+     * @return string
+     */
+    protected function buildSignString(array $params): string
+    {
+        // 过滤空值参数
+        $params = array_filter($params, function ($value) {
+            return $value !== '' && $value !== null;
+        });
+
+        // 按参数名排序
+        ksort($params);
+
+        // 拼接参数
+        $stringToBeSigned = '';
+        foreach ($params as $key => $value) {
+            // 跳过签名参数本身
+            if ($key === 'sign' || $key === 'signature') {
+                continue;
+            }
+
+            // 处理数组和对象类型的值
+            if (is_array($value) || is_object($value)) {
+                $value = json_encode($value, JSON_UNESCAPED_UNICODE);
+            }
+
+            $stringToBeSigned .= $key . '=' . $value . '&';
+        }
+
+        // 去除最后一个&符号
+        return rtrim($stringToBeSigned, '&');
+    }
+
     /**
      * 获取已注册的包列表
      *
@@ -198,10 +234,10 @@ class WebhookDispatchService
 
         return $packages;
     }
-    
+
     /**
      * 获取指定包的处理器列表
-     * 
+     *
      * @param string $packageName 包名
      * @return array
      */
@@ -209,10 +245,10 @@ class WebhookDispatchService
     {
         return static::$packageHandlers[$packageName] ?? [];
     }
-    
+
     /**
      * 检查包是否已注册
-     * 
+     *
      * @param string $packageName 包名
      * @return bool
      */
@@ -220,10 +256,10 @@ class WebhookDispatchService
     {
         return isset(static::$packageHandlers[$packageName]);
     }
-    
+
     /**
      * 检查包的处理器是否已注册
-     * 
+     *
      * @param string $packageName 包名
      * @param string $handlerRoute Handler路由
      * @return bool
@@ -232,10 +268,10 @@ class WebhookDispatchService
     {
         return isset(static::$packageHandlers[$packageName][$handlerRoute]);
     }
-    
+
     /**
      * 注销包处理器
-     * 
+     *
      * @param string $packageName 包名
      * @param string|null $handlerRoute Handler路由,为空则注销整个包
      */
@@ -254,7 +290,7 @@ class WebhookDispatchService
             ]);
         }
     }
-    
+
     /**
      * 清空所有已注册的包处理器
      */