| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355 |
- <?php
- namespace App\Module\ThirdParty\Commands;
- use Illuminate\Console\Command;
- use App\Module\ThirdParty\Services\ThirdPartyService;
- use App\Module\ThirdParty\Models\ThirdPartyService as ServiceModel;
- /**
- * 第三方服务测试命令
- */
- class TestServiceCommand extends Command
- {
- /**
- * 命令签名
- *
- * @var string
- */
- protected $signature = 'thirdparty:test-service
- {service : 服务ID或代码}
- {--endpoint= : 测试端点}
- {--method=GET : HTTP方法}
- {--data= : 测试数据(JSON格式)}
- {--environment=production : 环境}
- {--timeout=30 : 超时时间}';
- /**
- * 命令描述
- *
- * @var string
- */
- protected $description = '测试第三方服务连接和API调用';
- /**
- * 执行命令
- *
- * @return int
- */
- public function handle(): int
- {
- $serviceIdentifier = $this->argument('service');
- $endpoint = $this->option('endpoint') ?? '';
- $method = strtoupper($this->option('method'));
- $environment = $this->option('environment');
- $timeout = (int)$this->option('timeout');
- $this->info("开始测试第三方服务: {$serviceIdentifier}");
- try {
- // 获取服务
- $service = $this->getService($serviceIdentifier);
- $this->displayServiceInfo($service);
- // 解析测试数据
- $data = $this->parseTestData();
- // 执行测试
- $result = $this->performTest($service, $endpoint, $method, $data, $environment, $timeout);
-
- $this->displayTestResult($result);
- return $result['success'] ? Command::SUCCESS : Command::FAILURE;
- } catch (\Exception $e) {
- $this->error("测试失败: {$e->getMessage()}");
- return Command::FAILURE;
- }
- }
- /**
- * 获取服务
- *
- * @param string $identifier
- * @return ServiceModel
- * @throws \Exception
- */
- protected function getService(string $identifier): ServiceModel
- {
- // 尝试按ID查找
- if (is_numeric($identifier)) {
- $service = ServiceModel::find($identifier);
- if ($service) {
- return $service;
- }
- }
- // 按代码查找
- $service = ServiceModel::where('code', $identifier)->first();
- if ($service) {
- return $service;
- }
- throw new \Exception("服务不存在: {$identifier}");
- }
- /**
- * 显示服务信息
- *
- * @param ServiceModel $service
- * @return void
- */
- protected function displayServiceInfo(ServiceModel $service): void
- {
- $this->line('');
- $this->info('服务信息:');
- $this->line(str_repeat('-', 50));
- $this->line("名称: {$service->name}");
- $this->line("代码: {$service->code}");
- $this->line("类型: {$service->getTypeLabel()}");
- $this->line("提供商: {$service->provider}");
- $this->line("状态: {$service->getStatusLabel()}");
- $this->line("认证类型: {$service->getAuthTypeLabel()}");
- $this->line("基础URL: {$service->base_url}");
- $this->line('');
- }
- /**
- * 解析测试数据
- *
- * @return array
- * @throws \Exception
- */
- protected function parseTestData(): array
- {
- $dataOption = $this->option('data');
-
- if (!$dataOption) {
- return [];
- }
- $data = json_decode($dataOption, true);
- if (json_last_error() !== JSON_ERROR_NONE) {
- throw new \Exception("测试数据格式错误: " . json_last_error_msg());
- }
- return $data;
- }
- /**
- * 执行测试
- *
- * @param ServiceModel $service
- * @param string $endpoint
- * @param string $method
- * @param array $data
- * @param string $environment
- * @param int $timeout
- * @return array
- */
- protected function performTest(
- ServiceModel $service,
- string $endpoint,
- string $method,
- array $data,
- string $environment,
- int $timeout
- ): array {
- $result = [
- 'success' => false,
- 'message' => '',
- 'details' => [],
- ];
- try {
- // 检查服务状态
- if (!$service->isAvailable()) {
- $result['message'] = "服务不可用,状态: {$service->getStatusLabel()}";
- return $result;
- }
- // 检查凭证
- $credential = $service->getActiveCredential($environment);
- if (!$credential) {
- $result['message'] = "环境 {$environment} 没有可用的认证凭证";
- return $result;
- }
- if ($credential->isExpired()) {
- $result['message'] = '认证凭证已过期';
- return $result;
- }
- $this->line("使用凭证: {$credential->name} ({$environment})");
- // 如果没有指定端点,只测试凭证
- if (empty($endpoint)) {
- $result = $this->testCredential($credential);
- return $result;
- }
- // 执行API调用测试
- $result = $this->testApiCall($service, $endpoint, $method, $data, $environment, $timeout);
- } catch (\Exception $e) {
- $result['message'] = $e->getMessage();
- $result['details']['exception'] = get_class($e);
- }
- return $result;
- }
- /**
- * 测试凭证
- *
- * @param \App\Module\ThirdParty\Models\ThirdPartyCredential $credential
- * @return array
- */
- protected function testCredential($credential): array
- {
- $this->line('测试凭证配置...');
- // 验证凭证配置
- $validation = $credential->validateCredentials();
- if (!$validation['valid']) {
- return [
- 'success' => false,
- 'message' => '凭证配置不完整: ' . implode(', ', $validation['missing_fields']),
- 'details' => $validation,
- ];
- }
- // 生成认证头
- try {
- $headers = $credential->generateAuthHeaders();
-
- return [
- 'success' => true,
- 'message' => '凭证测试成功',
- 'details' => [
- 'auth_type' => $credential->getTypeLabel(),
- 'headers_generated' => !empty($headers),
- 'expires_at' => $credential->expires_at?->toDateTimeString(),
- ],
- ];
- } catch (\Exception $e) {
- return [
- 'success' => false,
- 'message' => '凭证测试失败: ' . $e->getMessage(),
- 'details' => [],
- ];
- }
- }
- /**
- * 测试API调用
- *
- * @param ServiceModel $service
- * @param string $endpoint
- * @param string $method
- * @param array $data
- * @param string $environment
- * @param int $timeout
- * @return array
- */
- protected function testApiCall(
- ServiceModel $service,
- string $endpoint,
- string $method,
- array $data,
- string $environment,
- int $timeout
- ): array {
- $this->line("测试API调用: {$method} {$endpoint}");
- try {
- $options = [
- 'environment' => $environment,
- 'timeout' => $timeout,
- ];
- $result = ThirdPartyService::callApi(
- $service->code,
- $endpoint,
- $data,
- $method,
- $options
- );
- return [
- 'success' => $result['success'],
- 'message' => $result['success'] ? 'API调用成功' : 'API调用失败',
- 'details' => [
- 'status_code' => $result['status_code'],
- 'response_time' => $result['response_time'] . 'ms',
- 'request_id' => $result['request_id'],
- 'data' => $result['data'],
- ],
- ];
- } catch (\Exception $e) {
- return [
- 'success' => false,
- 'message' => 'API调用失败: ' . $e->getMessage(),
- 'details' => [],
- ];
- }
- }
- /**
- * 显示测试结果
- *
- * @param array $result
- * @return void
- */
- protected function displayTestResult(array $result): void
- {
- $this->line('');
- $this->line(str_repeat('-', 50));
-
- if ($result['success']) {
- $this->info('✓ 测试成功');
- } else {
- $this->error('✗ 测试失败');
- }
- $this->line("结果: {$result['message']}");
- if (!empty($result['details'])) {
- $this->line('');
- $this->line('详细信息:');
- foreach ($result['details'] as $key => $value) {
- if (is_array($value)) {
- $value = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
- }
- $this->line(" {$key}: {$value}");
- }
- }
- $this->line('');
- }
- /**
- * 显示使用示例
- *
- * @return void
- */
- protected function showExamples(): void
- {
- $this->line('');
- $this->info('使用示例:');
- $this->line('');
- $this->line('# 测试服务凭证');
- $this->line('php artisan thirdparty:test-service aliyun_sms');
- $this->line('');
- $this->line('# 测试API调用');
- $this->line('php artisan thirdparty:test-service aliyun_sms --endpoint=/api/test --method=POST');
- $this->line('');
- $this->line('# 带测试数据');
- $this->line('php artisan thirdparty:test-service alipay --endpoint=/api/pay --data=\'{"amount":100}\'');
- $this->line('');
- $this->line('# 指定环境');
- $this->line('php artisan thirdparty:test-service wechat_pay --environment=staging');
- $this->line('');
- }
- }
|