/** * Sincroniza produtos da API 2Service com o WooCommerce */ function twoservice_sync_products() { // Obter token de sessão $auth_result = twoservice_authenticate(); if (!$auth_result['success']) { return array( 'success' => false, 'message' => $auth_result['message'] ); } $session_token = $auth_result['token']; // Obter produtos da API $products_result = twoservice_get_products($session_token); if (!$products_result['success']) { return array( 'success' => false, 'message' => $products_result['message'] ); } $products = $products_result['products']; $products_count = count($products); $created_count = 0; $updated_count = 0; $failed_count = 0; // Processar cada produto foreach ($products as $product) { $sync_result = twoservice_sync_single_product($product, $session_token); if ($sync_result['success']) { if ($sync_result['created']) { $created_count++; } else { $updated_count++; } } else { $failed_count++; } } return array( 'success' => true, 'message' => sprintf( __('Sincronização concluída. %d produtos processados, %d criados, %d atualizados, %d falharam.', '2service-dashboard'), $products_count, $created_count, $updated_count, $failed_count ) ); } /** * Autentica na API 2Service e obtém um token de sessão */ function twoservice_authenticate() { // Usar credenciais fixas $username = TWOSERVICE_USERNAME; $password = TWOSERVICE_PASSWORD; // Preparar dados para autenticação $auth_data = array( 'UserName' => $username, 'Password' => $password ); // Fazer requisição de autenticação $response = wp_remote_post(TWOSERVICE_API_URL . 'dealers/authenticate', array( 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json' ), 'body' => json_encode($auth_data), 'timeout' => 60, 'sslverify' => false )); // Verificar se houve erro na requisição if (is_wp_error($response)) { return array( 'success' => false, 'message' => $response->get_error_message() ); } // Obter corpo da resposta $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Verificar se a resposta é válida e contém o token if ( is_array($data) && isset($data['IsSuccessful']) && $data['IsSuccessful'] === true && isset($data['Result']['SessionToken']) ) { return array( 'success' => true, 'token' => $data['Result']['SessionToken'] ); } else { $error_message = isset($data['Message']) ? $data['Message'] : __('Resposta de autenticação inválida', '2service-dashboard'); return array( 'success' => false, 'message' => $error_message ); } } /** * Obtém produtos da API 2Service */ function twoservice_get_products($session_token) { // Construir endpoint com parâmetros $endpoint = TWOSERVICE_API_URL . 'dealers/parts?SessionToken=' . urlencode($session_token); // Fazer requisição à API $response = wp_remote_get($endpoint, array( 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $session_token ), 'timeout' => 60, 'sslverify' => false )); // Verificar se houve erro na requisição if (is_wp_error($response)) { return array( 'success' => false, 'message' => $response->get_error_message() ); } // Obter corpo da resposta $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Verificar se a resposta é válida if ( is_array($data) && isset($data['IsSuccessful']) && $data['IsSuccessful'] === true && isset($data['Result']) ) { $parts = $data['Result']; $products = array(); // Transformar os dados da API para o formato esperado foreach ($parts as $part) { $products[] = array( 'Id' => $part['PartNumber'], 'Name' => $part['Description'], 'Price' => isset($part['Price']) ? $part['Price'] : 0, 'Description' => isset($part['Description']) ? $part['Description'] : '', 'ImageUrl' => isset($part['ImageUrl']) ? $part['ImageUrl'] : '', 'AvailableStockQuantity' => isset($part['AvailableStockQuantity']) ? $part['AvailableStockQuantity'] : 0 ); } return array( 'success' => true, 'products' => $products ); } else { $error_message = isset($data['Message']) ? $data['Message'] : __('Erro desconhecido na API', '2service-dashboard'); return array( 'success' => false, 'message' => $error_message ); } } /** * Obtém detalhes de um produto específico da API 2Service */ function twoservice_get_product_details($product_id, $session_token) { // Construir endpoint com parâmetros $endpoint = TWOSERVICE_API_URL . 'dealers/part?PartNumber=' . urlencode($product_id) . '&SessionToken=' . urlencode($session_token); // Fazer requisição à API $response = wp_remote_get($endpoint, array( 'headers' => array( 'Content-Type' => 'application/json', 'Accept' => 'application/json', 'Authorization' => 'Bearer ' . $session_token ), 'timeout' => 60, 'sslverify' => false )); // Verificar se houve erro na requisição if (is_wp_error($response)) { return array( 'success' => false, 'message' => $response->get_error_message() ); } // Obter corpo da resposta $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Verificar se a resposta é válida if ( is_array($data) && isset($data['IsSuccessful']) && $data['IsSuccessful'] === true && isset($data['Result']) ) { $part = $data['Result']; // Transformar os dados da API para o formato esperado $product = array( 'Id' => $part['PartNumber'], 'Name' => $part['Description'], 'Price' => isset($part['Price']) ? $part['Price'] : 0, 'Description' => isset($part['Description']) ? $part['Description'] : '', 'ImageUrl' => isset($part['ImageUrl']) ? $part['ImageUrl'] : '', 'AvailableStockQuantity' => isset($part['AvailableStockQuantity']) ? $part['AvailableStockQuantity'] : 0 ); return array( 'success' => true, 'product' => $product ); } else { $error_message = isset($data['Message']) ? $data['Message'] : __('Erro desconhecido na API', '2service-dashboard'); return array( 'success' => false, 'message' => $error_message ); } } /** * Sincroniza um único produto da API 2Service com o WooCommerce */ function twoservice_sync_single_product($product_data, $session_token) { // Verificar se o produto já existe no WooCommerce $wc_product_id = twoservice_get_wc_product_by_sku($product_data['Id']); $created = false; try { // Se o produto não existe, criar novo if (!$wc_product_id) { $product = new WC_Product_Simple(); $created = true; } else { $product = wc_get_product($wc_product_id); // Se o produto não for do tipo simples, converter if (!$product || !is_a($product, 'WC_Product_Simple')) { $product = new WC_Product_Simple($wc_product_id); } } // Configurar dados básicos do produto $product->set_name($product_data['Name']); $product->set_sku($product_data['Id']); $product->set_regular_price($product_data['Price']); $product->set_description($product_data['Description'] ?? ''); // Configurar stock $product->set_manage_stock(true); $product->set_stock_quantity($product_data['AvailableStockQuantity'] ?? 0); $product->set_stock_status($product_data['AvailableStockQuantity'] > 0 ? 'instock' : 'outofstock'); // Configurar imagens if (!empty($product_data['ImageUrl'])) { twoservice_set_product_image($product, $product_data['ImageUrl']); } // Salvar produto $product_id = $product->save(); // Salvar metadados adicionais update_post_meta($product_id, '_twoservice_product_id', $product_data['Id']); update_post_meta($product_id, '_twoservice_last_sync', current_time('mysql')); return array( 'success' => true, 'created' => $created, 'product_id' => $product_id ); } catch (Exception $e) { return array( 'success' => false, 'message' => $e->getMessage() ); } } /** * Obtém um produto WooCommerce pelo SKU */ function twoservice_get_wc_product_by_sku($sku) { global $wpdb; $product_id = $wpdb->get_var($wpdb->prepare(" SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_sku' AND meta_value = %s LIMIT 1 ", $sku)); return $product_id ? intval($product_id) : false; } /** * Define a imagem principal do produto */ function twoservice_set_product_image($product, $image_url) { // Verificar se a imagem já existe $attachment_id = twoservice_get_attachment_id_by_url($image_url); // Se não existe, fazer upload if (!$attachment_id) { $attachment_id = twoservice_upload_image_from_url($image_url, $product->get_name()); } // Se temos um ID de anexo válido, definir como imagem do produto if ($attachment_id) { $product->set_image_id($attachment_id); } } /** * Obtém o ID de um anexo pela URL */ function twoservice_get_attachment_id_by_url($url) { global $wpdb; // Remover parâmetros de consulta $url = preg_replace('/\?.*/', '', $url); // Obter apenas o nome do arquivo $filename = basename($url); // Procurar anexo pelo nome do arquivo $attachment_id = $wpdb->get_var($wpdb->prepare(" SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value LIKE %s LIMIT 1 ", '%' . $filename)); return $attachment_id ? intval($attachment_id) : false; } /** * Faz upload de uma imagem a partir de uma URL */ function twoservice_upload_image_from_url($url, $title = '') { // Obter dados da imagem $response = wp_remote_get($url, array( 'timeout' => 60, 'sslverify' => false )); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) { return false; } $image_data = wp_remote_retrieve_body($response); // Obter tipo de conteúdo $content_type = wp_remote_retrieve_header($response, 'content-type'); // Determinar extensão do arquivo $extension = ''; switch ($content_type) { case 'image/jpeg': $extension = 'jpg'; break; case 'image/png': $extension = 'png'; break; case 'image/gif': $extension = 'gif'; break; default: return false; } // Gerar nome de arquivo único $filename = sanitize_title($title ?: 'product-image') . '-' . uniqid() . '.' . $extension; // Obter diretório de upload $upload_dir = wp_upload_dir(); $upload_path = $upload_dir['path'] . '/' . $filename; $upload_url = $upload_dir['url'] . '/' . $filename; // Salvar arquivo file_put_contents($upload_path, $image_data); // Preparar dados para anexo $attachment = array( 'post_mime_type' => $content_type, 'post_title' => $title ?: $filename, 'post_content' => '', 'post_status' => 'inherit', 'guid' => $upload_url ); // Inserir anexo $attachment_id = wp_insert_attachment($attachment, $upload_path); if (!$attachment_id) { return false; } // Gerar metadados require_once(ABSPATH . 'wp-admin/includes/image.php'); $attachment_data = wp_generate_attachment_metadata($attachment_id, $upload_path); wp_update_attachment_metadata($attachment_id, $attachment_data); return $attachment_id; }