第三方请求

This commit is contained in:
2026-08-03 09:28:17 +08:00
parent 90e44a2a20
commit 6e464df949
2 changed files with 86 additions and 6 deletions

View File

@@ -550,3 +550,62 @@ function doCurl(string $url, array $params = [])
throw new \Exception(lang('system_busy'));
}
}
/**
* 使用 multipart/form-data 请求第三方 API。
* 普通值作为文本字段发送,资源或 StreamInterface 可直接作为文件字段发送。
* 不要手动设置 Content-TypeGuzzle 会自动生成带 boundary 的请求头。
*
* @param string $url
* @param array $params
* @param array $headers
* @param array $options Guzzle 请求选项,例如 timeout、verify、proxy 等
* @return mixed JSON 响应返回数组,非 JSON 响应返回原始字符串
* @throws \Exception
*/
function third_party_form_request(
string $url,
array $params = [],
array $headers = [],
array $options = []
): mixed {
$multipart = [];
foreach ($params as $name => $value) {
$isList = is_array($value) && (
function_exists('array_is_list')
? array_is_list($value)
: $value === [] || array_keys($value) === range(0, count($value) - 1)
);
$values = $isList ? $value : [$value];
foreach ($values as $item) {
$multipart[] = [
'name' => (string) $name,
'contents' => is_null($item) ? '' : $item,
];
}
}
$requestOptions = array_merge([
'timeout' => 7,
'connect_timeout' => 7,
'verify' => true,
'http_errors' => false,
], $options);
$requestOptions['multipart'] = $multipart;
$requestOptions['headers'] = array_merge(['Accept' => 'application/json'], $headers);
try {
$response = (new Client())->request('POST', $url, $requestOptions);
$statusCode = $response->getStatusCode();
$contents = $response->getBody()->getContents();
if ($statusCode < 200 || $statusCode >= 300) {
throw new \Exception(lang('system_busy'));
}
$data = json_decode($contents, true);
return json_last_error() === JSON_ERROR_NONE ? $data : $contents;
} catch (GuzzleException $e) {
throw new \Exception(lang('system_busy'), 0, $e);
}
}