TestServiceCommand.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. <?php
  2. namespace App\Module\ThirdParty\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Module\ThirdParty\Services\ThirdPartyService;
  5. use App\Module\ThirdParty\Models\ThirdPartyService as ServiceModel;
  6. /**
  7. * 第三方服务测试命令
  8. */
  9. class TestServiceCommand extends Command
  10. {
  11. /**
  12. * 命令签名
  13. *
  14. * @var string
  15. */
  16. protected $signature = 'thirdparty:test-service
  17. {service : 服务ID或代码}
  18. {--endpoint= : 测试端点}
  19. {--method=GET : HTTP方法}
  20. {--data= : 测试数据(JSON格式)}
  21. {--environment=production : 环境}
  22. {--timeout=30 : 超时时间}';
  23. /**
  24. * 命令描述
  25. *
  26. * @var string
  27. */
  28. protected $description = '测试第三方服务连接和API调用';
  29. /**
  30. * 执行命令
  31. *
  32. * @return int
  33. */
  34. public function handle(): int
  35. {
  36. $serviceIdentifier = $this->argument('service');
  37. $endpoint = $this->option('endpoint') ?? '';
  38. $method = strtoupper($this->option('method'));
  39. $environment = $this->option('environment');
  40. $timeout = (int)$this->option('timeout');
  41. $this->info("开始测试第三方服务: {$serviceIdentifier}");
  42. try {
  43. // 获取服务
  44. $service = $this->getService($serviceIdentifier);
  45. $this->displayServiceInfo($service);
  46. // 解析测试数据
  47. $data = $this->parseTestData();
  48. // 执行测试
  49. $result = $this->performTest($service, $endpoint, $method, $data, $environment, $timeout);
  50. $this->displayTestResult($result);
  51. return $result['success'] ? Command::SUCCESS : Command::FAILURE;
  52. } catch (\Exception $e) {
  53. $this->error("测试失败: {$e->getMessage()}");
  54. return Command::FAILURE;
  55. }
  56. }
  57. /**
  58. * 获取服务
  59. *
  60. * @param string $identifier
  61. * @return ServiceModel
  62. * @throws \Exception
  63. */
  64. protected function getService(string $identifier): ServiceModel
  65. {
  66. // 尝试按ID查找
  67. if (is_numeric($identifier)) {
  68. $service = ServiceModel::find($identifier);
  69. if ($service) {
  70. return $service;
  71. }
  72. }
  73. // 按代码查找
  74. $service = ServiceModel::where('code', $identifier)->first();
  75. if ($service) {
  76. return $service;
  77. }
  78. throw new \Exception("服务不存在: {$identifier}");
  79. }
  80. /**
  81. * 显示服务信息
  82. *
  83. * @param ServiceModel $service
  84. * @return void
  85. */
  86. protected function displayServiceInfo(ServiceModel $service): void
  87. {
  88. $this->line('');
  89. $this->info('服务信息:');
  90. $this->line(str_repeat('-', 50));
  91. $this->line("名称: {$service->name}");
  92. $this->line("代码: {$service->code}");
  93. $this->line("类型: {$service->getTypeLabel()}");
  94. $this->line("提供商: {$service->provider}");
  95. $this->line("状态: {$service->getStatusLabel()}");
  96. $this->line("认证类型: {$service->getAuthTypeLabel()}");
  97. $this->line("基础URL: {$service->base_url}");
  98. $this->line('');
  99. }
  100. /**
  101. * 解析测试数据
  102. *
  103. * @return array
  104. * @throws \Exception
  105. */
  106. protected function parseTestData(): array
  107. {
  108. $dataOption = $this->option('data');
  109. if (!$dataOption) {
  110. return [];
  111. }
  112. $data = json_decode($dataOption, true);
  113. if (json_last_error() !== JSON_ERROR_NONE) {
  114. throw new \Exception("测试数据格式错误: " . json_last_error_msg());
  115. }
  116. return $data;
  117. }
  118. /**
  119. * 执行测试
  120. *
  121. * @param ServiceModel $service
  122. * @param string $endpoint
  123. * @param string $method
  124. * @param array $data
  125. * @param string $environment
  126. * @param int $timeout
  127. * @return array
  128. */
  129. protected function performTest(
  130. ServiceModel $service,
  131. string $endpoint,
  132. string $method,
  133. array $data,
  134. string $environment,
  135. int $timeout
  136. ): array {
  137. $result = [
  138. 'success' => false,
  139. 'message' => '',
  140. 'details' => [],
  141. ];
  142. try {
  143. // 检查服务状态
  144. if (!$service->isAvailable()) {
  145. $result['message'] = "服务不可用,状态: {$service->getStatusLabel()}";
  146. return $result;
  147. }
  148. // 检查凭证
  149. $credential = $service->getActiveCredential($environment);
  150. if (!$credential) {
  151. $result['message'] = "环境 {$environment} 没有可用的认证凭证";
  152. return $result;
  153. }
  154. if ($credential->isExpired()) {
  155. $result['message'] = '认证凭证已过期';
  156. return $result;
  157. }
  158. $this->line("使用凭证: {$credential->name} ({$environment})");
  159. // 如果没有指定端点,只测试凭证
  160. if (empty($endpoint)) {
  161. $result = $this->testCredential($credential);
  162. return $result;
  163. }
  164. // 执行API调用测试
  165. $result = $this->testApiCall($service, $endpoint, $method, $data, $environment, $timeout);
  166. } catch (\Exception $e) {
  167. $result['message'] = $e->getMessage();
  168. $result['details']['exception'] = get_class($e);
  169. }
  170. return $result;
  171. }
  172. /**
  173. * 测试凭证
  174. *
  175. * @param \App\Module\ThirdParty\Models\ThirdPartyCredential $credential
  176. * @return array
  177. */
  178. protected function testCredential($credential): array
  179. {
  180. $this->line('测试凭证配置...');
  181. // 验证凭证配置
  182. $validation = $credential->validateCredentials();
  183. if (!$validation['valid']) {
  184. return [
  185. 'success' => false,
  186. 'message' => '凭证配置不完整: ' . implode(', ', $validation['missing_fields']),
  187. 'details' => $validation,
  188. ];
  189. }
  190. // 生成认证头
  191. try {
  192. $headers = $credential->generateAuthHeaders();
  193. return [
  194. 'success' => true,
  195. 'message' => '凭证测试成功',
  196. 'details' => [
  197. 'auth_type' => $credential->getTypeLabel(),
  198. 'headers_generated' => !empty($headers),
  199. 'expires_at' => $credential->expires_at?->toDateTimeString(),
  200. ],
  201. ];
  202. } catch (\Exception $e) {
  203. return [
  204. 'success' => false,
  205. 'message' => '凭证测试失败: ' . $e->getMessage(),
  206. 'details' => [],
  207. ];
  208. }
  209. }
  210. /**
  211. * 测试API调用
  212. *
  213. * @param ServiceModel $service
  214. * @param string $endpoint
  215. * @param string $method
  216. * @param array $data
  217. * @param string $environment
  218. * @param int $timeout
  219. * @return array
  220. */
  221. protected function testApiCall(
  222. ServiceModel $service,
  223. string $endpoint,
  224. string $method,
  225. array $data,
  226. string $environment,
  227. int $timeout
  228. ): array {
  229. $this->line("测试API调用: {$method} {$endpoint}");
  230. try {
  231. $options = [
  232. 'environment' => $environment,
  233. 'timeout' => $timeout,
  234. ];
  235. $result = ThirdPartyService::callApi(
  236. $service->code,
  237. $endpoint,
  238. $data,
  239. $method,
  240. $options
  241. );
  242. return [
  243. 'success' => $result['success'],
  244. 'message' => $result['success'] ? 'API调用成功' : 'API调用失败',
  245. 'details' => [
  246. 'status_code' => $result['status_code'],
  247. 'response_time' => $result['response_time'] . 'ms',
  248. 'request_id' => $result['request_id'],
  249. 'data' => $result['data'],
  250. ],
  251. ];
  252. } catch (\Exception $e) {
  253. return [
  254. 'success' => false,
  255. 'message' => 'API调用失败: ' . $e->getMessage(),
  256. 'details' => [],
  257. ];
  258. }
  259. }
  260. /**
  261. * 显示测试结果
  262. *
  263. * @param array $result
  264. * @return void
  265. */
  266. protected function displayTestResult(array $result): void
  267. {
  268. $this->line('');
  269. $this->line(str_repeat('-', 50));
  270. if ($result['success']) {
  271. $this->info('✓ 测试成功');
  272. } else {
  273. $this->error('✗ 测试失败');
  274. }
  275. $this->line("结果: {$result['message']}");
  276. if (!empty($result['details'])) {
  277. $this->line('');
  278. $this->line('详细信息:');
  279. foreach ($result['details'] as $key => $value) {
  280. if (is_array($value)) {
  281. $value = json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  282. }
  283. $this->line(" {$key}: {$value}");
  284. }
  285. }
  286. $this->line('');
  287. }
  288. /**
  289. * 显示使用示例
  290. *
  291. * @return void
  292. */
  293. protected function showExamples(): void
  294. {
  295. $this->line('');
  296. $this->info('使用示例:');
  297. $this->line('');
  298. $this->line('# 测试服务凭证');
  299. $this->line('php artisan thirdparty:test-service aliyun_sms');
  300. $this->line('');
  301. $this->line('# 测试API调用');
  302. $this->line('php artisan thirdparty:test-service aliyun_sms --endpoint=/api/test --method=POST');
  303. $this->line('');
  304. $this->line('# 带测试数据');
  305. $this->line('php artisan thirdparty:test-service alipay --endpoint=/api/pay --data=\'{"amount":100}\'');
  306. $this->line('');
  307. $this->line('# 指定环境');
  308. $this->line('php artisan thirdparty:test-service wechat_pay --environment=staging');
  309. $this->line('');
  310. }
  311. }