p2 project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.6 KiB

<?php
namespace app\utility;
use app\home\service\BaseHomeService;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use think\facade\Log;
class RequestChatServer extends BaseHomeService
{
public function ReqChatServer(string $url, array $data, string $method = 'POST'): array
{
try {
if (!in_array($method, ['POST','PUT'])) {
return $this->toData('500', '请求方法不在支持列表中');
}
Log::info("Guzzle请求: URL==".$url." 请求Param==".json_encode($data));
$resBody = [];
$client = new Client();
if ($method == 'PUT') {
$response = $client->put($url, [
'json' => $data,
]);
} else {
$response = $client->post($url, [
'json' => $data,
]);
}
$statusCode = $response->getStatusCode();
Log::error("Guzzle请求响应:code==".$statusCode." body==". $response->getBody());
if ($statusCode == 200) {
$resBody = json_decode($response->getBody(), true); // 转换为数组
}
return $resBody;
} catch (GuzzleException $e) {
Log::error("Guzzle请求异常 - guzzle: " . $e->getMessage());
return $this->toData('500', $e->getMessage());
} catch (\Exception $exception) {
Log::error("Guzzle请求异常 - exception: " . $exception->getMessage());
return $this->toData('500', $exception->getMessage());
}
}
}