| 1 |
<?php |
| 2 |
|
| 3 |
namespace SuperFrete_API\Http; |
| 4 |
|
| 5 |
use SuperFrete_API\Helpers\Logger; |
| 6 |
|
| 7 |
class Request { |
| 8 |
|
| 9 |
private $api_url; |
| 10 |
private $api_token; |
| 11 |
|
| 12 |
/** |
| 13 |
* Construtor para inicializar as configurações da API. |
| 14 |
*/ |
| 15 |
public function __construct() { |
| 16 |
// Set API URL based on environment |
| 17 |
$use_dev_env = get_option('superfrete_sandbox_mode') === 'yes'; |
| 18 |
|
| 19 |
if ($use_dev_env) { |
| 20 |
$this->api_url = 'https://sandbox.superfrete.com/'; |
| 21 |
$this->api_token = get_option('superfrete_api_token_sandbox'); |
| 22 |
} else { |
| 23 |
$this->api_url = 'https://api.superfrete.com/'; |
| 24 |
$this->api_token = get_option('superfrete_api_token'); |
| 25 |
} |
| 26 |
|
| 27 |
// Debug logging |
| 28 |
error_log('SuperFrete Request: API URL = ' . $this->api_url); |
| 29 |
error_log('SuperFrete Request: Token present = ' . (!empty($this->api_token) ? 'yes' : 'no')); |
| 30 |
error_log('SuperFrete Request: Use dev env = ' . ($use_dev_env ? 'yes' : 'no')); |
| 31 |
} |
| 32 |
|
| 33 |
/** |
| 34 |
* Método genérico para chamadas à API do SuperFrete. |
| 35 |
*/ |
| 36 |
public function call_superfrete_api($endpoint, $method = 'GET', $payload = [], $retorno = false) { |
| 37 |
|
| 38 |
// Enhanced debug logging |
| 39 |
$environment = (strpos($this->api_url, 'sandbox') !== false || strpos($this->api_url, 'dev') !== false) ? 'SANDBOX/DEV' : 'PRODUCTION'; |
| 40 |
$full_url = $this->api_url . $endpoint; |
| 41 |
$token_preview = !empty($this->api_token) ? substr($this->api_token, 0, 8) . '...' . substr($this->api_token, -4) : 'EMPTY'; |
| 42 |
|
| 43 |
Logger::log('SuperFrete', "API CALL [{$environment}]: {$method} {$full_url}"); |
| 44 |
Logger::log('SuperFrete', "TOKEN USADO [{$environment}]: {$token_preview}"); |
| 45 |
|
| 46 |
if (empty($this->api_token)) { |
| 47 |
Logger::log('SuperFrete', 'API token is empty - cannot make API call'); |
| 48 |
return false; |
| 49 |
} |
| 50 |
|
| 51 |
try { |
| 52 |
$headers = [ |
| 53 |
'Content-Type' => 'application/json', |
| 54 |
'Accept' => 'application/json', |
| 55 |
'Authorization' => 'Bearer ' . $this->api_token, |
| 56 |
'User-Agent' => 'WooCommerce SuperFrete Plugin (github.com/superfrete/woocommerce)', |
| 57 |
'Platform' => 'Woocommerce SuperFrete', |
| 58 |
]; |
| 59 |
|
| 60 |
$params = [ |
| 61 |
'headers' => $headers, |
| 62 |
'method' => $method, |
| 63 |
'timeout' => 30, // Increased timeout to 30 seconds |
| 64 |
]; |
| 65 |
|
| 66 |
if ($method === 'POST' && !empty($payload)) { |
| 67 |
$params['body'] = wp_json_encode($payload); |
| 68 |
error_log('SuperFrete API Payload: ' . wp_json_encode($payload)); |
| 69 |
} |
| 70 |
|
| 71 |
$start_time = microtime(true); |
| 72 |
$response = ($method === 'POST') ? wp_remote_post($this->api_url . $endpoint, $params) : wp_remote_get($this->api_url . $endpoint, $params); |
| 73 |
$end_time = microtime(true); |
| 74 |
$request_time = round(($end_time - $start_time) * 1000, 2); |
| 75 |
|
| 76 |
error_log('SuperFrete API Request Time: ' . $request_time . ' ms'); |
| 77 |
|
| 78 |
// Check for WP errors first |
| 79 |
if (is_wp_error($response)) { |
| 80 |
$error_message = $response->get_error_message(); |
| 81 |
Logger::log('SuperFrete', "WP Error na API ({$endpoint}): " . $error_message); |
| 82 |
error_log('SuperFrete API WP Error: ' . $error_message); |
| 83 |
return false; |
| 84 |
} |
| 85 |
|
| 86 |
$status_code = wp_remote_retrieve_response_code($response); |
| 87 |
$raw_body = wp_remote_retrieve_body($response); |
| 88 |
|
| 89 |
// Debug logging |
| 90 |
error_log('SuperFrete API Response: Status = ' . $status_code); |
| 91 |
error_log('SuperFrete API Response: Body = ' . substr($raw_body, 0, 500) . (strlen($raw_body) > 500 ? '...' : '')); |
| 92 |
|
| 93 |
// Check for HTTP errors |
| 94 |
if (!in_array($status_code, [200, 201, 204])) { |
| 95 |
$error_msg = "ERRO NA API ({$endpoint}): CÓDIGO {$status_code}"; |
| 96 |
|
| 97 |
// Special handling for 401 errors |
| 98 |
if ($status_code == 401) { |
| 99 |
$error_msg .= " - NÃO AUTENTICADO!"; |
| 100 |
Logger::log('SuperFrete', $error_msg); |
| 101 |
Logger::log('SuperFrete', "DETALHES [{$environment}]: URL={$full_url}, TOKEN={$token_preview}"); |
| 102 |
Logger::log('SuperFrete', "RESPOSTA: " . (strlen($raw_body) > 200 ? substr($raw_body, 0, 200) . '...' : $raw_body)); |
| 103 |
} else { |
| 104 |
Logger::log('SuperFrete', $error_msg . "\nDETALHES: " . (strlen($raw_body) > 200 ? substr($raw_body, 0, 200) . '...' : ($raw_body ?: 'SEM DETALHES'))); |
| 105 |
} |
| 106 |
|
| 107 |
return false; |
| 108 |
} |
| 109 |
|
| 110 |
// Handle empty responses (common for DELETE operations) |
| 111 |
if (empty($raw_body) && $status_code == 204) { |
| 112 |
Logger::log('SuperFrete', "API call successful ({$endpoint}) - No content returned (HTTP {$status_code})"); |
| 113 |
return true; // Success for DELETE operations |
| 114 |
} |
| 115 |
|
| 116 |
$body = json_decode($raw_body, true); |
| 117 |
|
| 118 |
// Check for JSON decode errors only if there's content to decode |
| 119 |
if (!empty($raw_body) && json_last_error() !== JSON_ERROR_NONE) { |
| 120 |
Logger::log('SuperFrete', "JSON decode error na API ({$endpoint}): " . json_last_error_msg() . " - Raw response: " . substr($raw_body, 0, 200)); |
| 121 |
error_log('SuperFrete API JSON Error: ' . json_last_error_msg()); |
| 122 |
return false; |
| 123 |
} |
| 124 |
|
| 125 |
// Check for API-level errors |
| 126 |
if (isset($body['success']) && $body['success'] === false) { |
| 127 |
$error_message = isset($body['message']) ? $body['message'] : 'Erro desconhecido'; |
| 128 |
$errors = $this->extract_api_errors($body); |
| 129 |
Logger::log('SuperFrete', "API Error ({$endpoint}): {$error_message}\nDetalhes: {$errors}"); |
| 130 |
error_log('SuperFrete API Error: ' . $error_message . ' - Details: ' . $errors); |
| 131 |
return false; |
| 132 |
} |
| 133 |
|
| 134 |
Logger::log('SuperFrete', "API call successful ({$endpoint}) - Time: {$request_time}ms"); |
| 135 |
return $body; |
| 136 |
|
| 137 |
} catch (Exception $exc) { |
| 138 |
Logger::log('SuperFrete', "Exception na API ({$endpoint}): " . $exc->getMessage()); |
| 139 |
error_log('SuperFrete API Exception: ' . $exc->getMessage()); |
| 140 |
return false; |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
/** |
| 145 |
* Extract error details from API response |
| 146 |
*/ |
| 147 |
private function extract_api_errors($body) { |
| 148 |
$errors = []; |
| 149 |
|
| 150 |
if (isset($body['errors'])) { |
| 151 |
foreach ($body['errors'] as $field => $field_errors) { |
| 152 |
if (is_array($field_errors)) { |
| 153 |
$errors[] = $field . ': ' . implode(', ', $field_errors); |
| 154 |
} else { |
| 155 |
$errors[] = $field . ': ' . $field_errors; |
| 156 |
} |
| 157 |
} |
| 158 |
} elseif (isset($body['error'])) { |
| 159 |
if (is_array($body['error'])) { |
| 160 |
foreach ($body['error'] as $error) { |
| 161 |
if (is_array($error)) { |
| 162 |
$errors[] = implode(', ', $error); |
| 163 |
} else { |
| 164 |
$errors[] = $error; |
| 165 |
} |
| 166 |
} |
| 167 |
} else { |
| 168 |
$errors[] = $body['error']; |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
return empty($errors) ? 'Sem detalhes' : implode('; ', $errors); |
| 173 |
} |
| 174 |
|
| 175 |
/** |
| 176 |
* Register webhook with SuperFrete API |
| 177 |
*/ |
| 178 |
public function register_webhook($webhook_url, $events = ['order.posted', 'order.delivered']) |
| 179 |
{ |
| 180 |
Logger::log('SuperFrete', 'Iniciando registro de webhook...'); |
| 181 |
Logger::log('SuperFrete', "Token sendo usado: " . (empty($this->api_token) ? 'VAZIO' : 'Presente')); |
| 182 |
Logger::log('SuperFrete', "URL da API: " . $this->api_url); |
| 183 |
|
| 184 |
// First, check for existing webhooks and clean them up |
| 185 |
Logger::log('SuperFrete', 'Verificando webhooks existentes...'); |
| 186 |
$existing_webhooks = $this->list_webhooks(); |
| 187 |
|
| 188 |
if ($existing_webhooks && is_array($existing_webhooks)) { |
| 189 |
Logger::log('SuperFrete', 'Encontrados ' . count($existing_webhooks) . ' webhooks existentes'); |
| 190 |
|
| 191 |
foreach ($existing_webhooks as $webhook) { |
| 192 |
if (isset($webhook['id'])) { |
| 193 |
Logger::log('SuperFrete', 'Removendo webhook existente ID: ' . $webhook['id']); |
| 194 |
$this->delete_webhook($webhook['id'], false); // Don't clear options during cleanup |
| 195 |
} |
| 196 |
} |
| 197 |
} else { |
| 198 |
Logger::log('SuperFrete', 'Nenhum webhook existente encontrado'); |
| 199 |
} |
| 200 |
|
| 201 |
// Now register the new webhook |
| 202 |
$payload = [ |
| 203 |
'name' => 'WooCommerce SuperFrete Plugin Webhook', |
| 204 |
'url' => $webhook_url, |
| 205 |
'events' => $events |
| 206 |
]; |
| 207 |
|
| 208 |
Logger::log('SuperFrete', 'Registrando novo webhook: ' . wp_json_encode($payload)); |
| 209 |
|
| 210 |
$response = $this->call_superfrete_api('/api/v0/webhook', 'POST', $payload, true); |
| 211 |
|
| 212 |
if ($response && isset($response['secret_token'])) { |
| 213 |
// Store webhook secret for signature verification |
| 214 |
update_option('superfrete_webhook_secret', $response['secret_token']); |
| 215 |
update_option('superfrete_webhook_registered', 'yes'); |
| 216 |
update_option('superfrete_webhook_url', $webhook_url); |
| 217 |
update_option('superfrete_webhook_id', $response['id'] ?? ''); |
| 218 |
|
| 219 |
Logger::log('SuperFrete', 'Webhook registrado com sucesso. ID: ' . ($response['id'] ?? 'N/A')); |
| 220 |
return $response; |
| 221 |
} |
| 222 |
|
| 223 |
Logger::log('SuperFrete', 'Falha ao registrar webhook: ' . wp_json_encode($response)); |
| 224 |
update_option('superfrete_webhook_registered', 'no'); |
| 225 |
return false; |
| 226 |
} |
| 227 |
|
| 228 |
/** |
| 229 |
* Update existing webhook |
| 230 |
*/ |
| 231 |
public function update_webhook($webhook_id, $webhook_url, $events = ['order.posted', 'order.delivered']) |
| 232 |
{ |
| 233 |
$payload = [ |
| 234 |
'name' => 'WooCommerce SuperFrete Plugin Webhook', |
| 235 |
'url' => $webhook_url, |
| 236 |
'events' => $events |
| 237 |
]; |
| 238 |
|
| 239 |
Logger::log('SuperFrete', 'Atualizando webhook ID: ' . $webhook_id); |
| 240 |
|
| 241 |
$response = $this->call_superfrete_api('/api/v0/webhook/' . $webhook_id, 'PUT', $payload, true); |
| 242 |
|
| 243 |
if ($response) { |
| 244 |
update_option('superfrete_webhook_url', $webhook_url); |
| 245 |
Logger::log('SuperFrete', 'Webhook atualizado com sucesso'); |
| 246 |
return $response; |
| 247 |
} |
| 248 |
|
| 249 |
Logger::log('SuperFrete', 'Falha ao atualizar webhook: ' . wp_json_encode($response)); |
| 250 |
return false; |
| 251 |
} |
| 252 |
|
| 253 |
/** |
| 254 |
* Delete webhook from SuperFrete |
| 255 |
*/ |
| 256 |
public function delete_webhook($webhook_id, $clear_options = true) |
| 257 |
{ |
| 258 |
Logger::log('SuperFrete', 'Removendo webhook ID: ' . $webhook_id); |
| 259 |
|
| 260 |
$response = $this->call_superfrete_api('/api/v0/webhook/' . $webhook_id, 'DELETE', [], true); |
| 261 |
|
| 262 |
if ($response !== false) { |
| 263 |
if ($clear_options) { |
| 264 |
update_option('superfrete_webhook_registered', 'no'); |
| 265 |
update_option('superfrete_webhook_url', ''); |
| 266 |
update_option('superfrete_webhook_id', ''); |
| 267 |
} |
| 268 |
Logger::log('SuperFrete', 'Webhook removido com sucesso'); |
| 269 |
return true; |
| 270 |
} |
| 271 |
|
| 272 |
Logger::log('SuperFrete', 'Falha ao remover webhook: ' . wp_json_encode($response)); |
| 273 |
return false; |
| 274 |
} |
| 275 |
|
| 276 |
/** |
| 277 |
* List registered webhooks |
| 278 |
*/ |
| 279 |
public function list_webhooks() |
| 280 |
{ |
| 281 |
Logger::log('SuperFrete', 'Listando webhooks registrados'); |
| 282 |
|
| 283 |
$response = $this->call_superfrete_api('/api/v0/webhook', 'GET', [], true); |
| 284 |
|
| 285 |
if ($response) { |
| 286 |
Logger::log('SuperFrete', 'Webhooks listados: ' . wp_json_encode($response)); |
| 287 |
return $response; |
| 288 |
} |
| 289 |
|
| 290 |
Logger::log('SuperFrete', 'Falha ao listar webhooks'); |
| 291 |
return false; |
| 292 |
} |
| 293 |
} |
| 294 |
|