nhance/app/Helpers/api_helper.php
2025-07-01 20:10:50 +05:30

69 lines
2.2 KiB
PHP

<?php
if (!function_exists('call_third_party_api')) {
function call_third_party_api($url, $method = 'GET', $headers = [], $body = [])
{
$ch = curl_init();
// Normalize method
$method = strtoupper($method);
// Detect content type from headers
$contentType = 'application/json'; // default
foreach ($headers as $h) {
if (stripos($h, 'Content-Type:') !== false) {
$contentType = trim(substr($h, strlen('Content-Type:')));
}
}
// echo '<pre>';
// print_r($headers);
// print_r($body);
// die;
// Setup curl options
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HTTPHEADER => $headers,
];
// Only include body for applicable methods
if (!empty($body) && in_array($method, ['POST', 'PUT', 'PATCH', 'DELETE'])) {
if (stripos($contentType, 'application/json') !== false) {
$options[CURLOPT_POSTFIELDS] = json_encode($body);
} elseif (stripos($contentType, 'application/x-www-form-urlencoded') !== false) {
$options[CURLOPT_POSTFIELDS] = http_build_query($body);
} elseif (stripos($contentType, 'multipart/form-data') !== false) {
$options[CURLOPT_POSTFIELDS] = $body; // For file uploads or multipart fields
} else {
// Default fallback
$options[CURLOPT_POSTFIELDS] = $body;
}
}
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$error = curl_error($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($error) {
return [
'status' => false,
'message' => 'Curl error: ' . $error
];
}
$decoded = json_decode($response, true);
return [
'status' => ($httpCode >= 200 && $httpCode < 300),
'data' => $decoded ?: $response, // fallback to raw response
'code' => $httpCode
];
}
}