改进 HTTP 请求

This commit is contained in:
iVampireSP.com 2023-07-01 12:30:33 +08:00
parent 802bfaec87
commit 41c3345a84
No known key found for this signature in database
GPG Key ID: 2F7B001CA27A8132

View File

@ -2,6 +2,8 @@
namespace App\Support; namespace App\Support;
use Illuminate\Support\Facades\Log;
class WHMCS class WHMCS
{ {
private string $url; private string $url;
@ -79,14 +81,16 @@ private function request($action, $params = []): ?array
$json = json_decode($response, true); $json = json_decode($response, true);
throw_if( if (is_null($json)) {
is_null($json), Log::error('WHMCS response is not valid JSON', [$response]);
new \Exception('WHMCS response is not valid JSON')
);
new \Exception('WHMCS response is not valid JSON');
}
throw_if( throw_if(
isset($json['result']) && $json['result'] !== 'success', isset($json['result']) && $json['result'] !== 'success',
new \Exception($json['message']) new \Exception('Request WHMCS Error: ' . $json['message'])
); );
return $json; return $json;
@ -98,9 +102,10 @@ public function api($action, $params = []): ?array
'api_token' => $this->api_token 'api_token' => $this->api_token
], $params); ], $params);
$url = $this->url . '/modules/addons/PortIOInvoice/api/' . $action . '.php';
$ch = curl_init(); $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->url . '/modules/addons/PortIOInvoice/api/' . $action . '.php'); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt( curl_setopt(
$ch, $ch,
@ -109,18 +114,29 @@ public function api($action, $params = []): ?array
); );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch); $response = curl_exec($ch);
$json = json_decode($response, true);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch); curl_close($ch);
$json = json_decode($response, true); if (is_null($json)) {
Log::error('WHMCS response is not valid JSON', [$url, $code, $response]);
new \Exception('WHMCS response is not valid JSON');
}
$message = '未知错误';
if (isset($json['message'])) {
$message = $json['message'];
}
throw_if( throw_if(
is_null($json), isset($json['result']) && $json['result'] !== 'success',
new \Exception('WHMCS response is not valid JSON') new \Exception('Request WHMCS Error: ' . $message)
); );
throw_if( throw_if(
isset($json['status']) && $json['status'] !== true, isset($json['status']) && $json['status'] !== true,
new \Exception($json['message'] ?? '未知错误') new \Exception($message)
); );
return $json; return $json;
@ -146,5 +162,4 @@ public function api_openTicket(string $email, string $title, string $content)
'department_id' => $this->config['department_id'] ?? 1, 'department_id' => $this->config['department_id'] ?? 1,
]); ]);
} }
} }