86 lines
2.8 KiB
PHP
86 lines
2.8 KiB
PHP
<?php
|
|
|
|
if (!function_exists('send_api_request')) {
|
|
/**
|
|
* Send external API requests with cURL.
|
|
*
|
|
* @param string $method HTTP method: GET, POST, PUT, PATCH, DELETE
|
|
* @param string $url Full URL to request
|
|
* @param array $headers Optional headers (e.g., Authorization, Content-Type)
|
|
* @param mixed $body Optional request body (array for form, JSON string for raw)
|
|
* @param bool $as_json Decode response as JSON (default: true)
|
|
* @return mixed Decoded JSON, raw string, or false on error
|
|
*/
|
|
function send_api_request($method, $url, $headers = [], $body = null, $as_json = true) {
|
|
$curl = curl_init();
|
|
|
|
// Set HTTP method
|
|
$method = strtoupper($method);
|
|
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
|
|
|
|
// Attach body if needed
|
|
if (in_array($method, ['POST', 'PUT', 'PATCH']) && $body !== null) {
|
|
if (is_array($body)) {
|
|
// Form-encoded
|
|
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($body));
|
|
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
|
|
} else {
|
|
// Assume JSON string
|
|
curl_setopt($curl, CURLOPT_POSTFIELDS, $body);
|
|
$headers[] = 'Content-Type: application/json';
|
|
}
|
|
}
|
|
|
|
// Set cURL options
|
|
curl_setopt_array($curl, [
|
|
CURLOPT_URL => $url,
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_ENCODING => '',
|
|
CURLOPT_MAXREDIRS => 10,
|
|
CURLOPT_TIMEOUT => 30,
|
|
CURLOPT_FOLLOWLOCATION => true,
|
|
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
|
|
]);
|
|
|
|
if (!empty($headers)) {
|
|
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
|
|
}
|
|
|
|
// Execute
|
|
$response = curl_exec($curl);
|
|
|
|
$error = curl_error($curl);
|
|
curl_close($curl);
|
|
|
|
if ($error) {
|
|
print_r($error);
|
|
exit;
|
|
log_message('error', 'cURL Error: ' . $error);
|
|
return false;
|
|
}
|
|
|
|
return $as_json ? json_decode($response, true) : $response;
|
|
}
|
|
}
|
|
|
|
if (!function_exists('json_encode_decode')) {
|
|
function json_encode_decode($type, $data) {
|
|
if ($type == 'encode'){
|
|
return json_encode( $data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE ) ;
|
|
}else{
|
|
return json_decode( $data, true ) ;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|
|
|
|
if(!function_exists('number_format_no_round')){
|
|
function number_format_no_round($number, $decimals = 2, $dec_point = '.', $thousands_sep = ',') {
|
|
$factor = pow(10, $decimals);
|
|
// Truncate instead of rounding
|
|
$truncated = floor($number * $factor) / $factor;
|
|
return number_format($truncated, $decimals, $dec_point, $thousands_sep);
|
|
}
|
|
}
|